babylon.no-module.max.js 4.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232962339623496235962369623796238962399624096241962429624396244962459624696247962489624996250962519625296253962549625596256962579625896259962609626196262962639626496265962669626796268962699627096271962729627396274962759627696277962789627996280962819628296283962849628596286962879628896289962909629196292962939629496295962969629796298962999630096301963029630396304963059630696307963089630996310963119631296313963149631596316963179631896319963209632196322963239632496325963269632796328963299633096331963329633396334963359633696337963389633996340963419634296343963449634596346963479634896349963509635196352963539635496355963569635796358963599636096361963629636396364963659636696367963689636996370963719637296373963749637596376963779637896379963809638196382963839638496385963869638796388963899639096391963929639396394963959639696397963989639996400964019640296403964049640596406964079640896409964109641196412964139641496415964169641796418964199642096421964229642396424964259642696427964289642996430964319643296433964349643596436964379643896439964409644196442964439644496445964469644796448964499645096451964529645396454964559645696457964589645996460964619646296463964649646596466964679646896469964709647196472964739647496475964769647796478964799648096481964829648396484964859648696487964889648996490964919649296493964949649596496964979649896499965009650196502965039650496505965069650796508965099651096511965129651396514965159651696517965189651996520965219652296523965249652596526965279652896529965309653196532965339653496535965369653796538965399654096541965429654396544965459654696547965489654996550965519655296553965549655596556965579655896559965609656196562965639656496565965669656796568965699657096571965729657396574965759657696577965789657996580965819658296583965849658596586965879658896589965909659196592965939659496595965969659796598965999660096601966029660396604966059660696607966089660996610966119661296613966149661596616966179661896619966209662196622966239662496625966269662796628966299663096631966329663396634966359663696637966389663996640966419664296643966449664596646966479664896649966509665196652966539665496655966569665796658966599666096661966629666396664966659666696667966689666996670966719667296673966749667596676966779667896679966809668196682966839668496685966869668796688966899669096691966929669396694966959669696697966989669996700967019670296703967049670596706967079670896709967109671196712967139671496715967169671796718967199672096721967229672396724967259672696727967289672996730967319673296733967349673596736967379673896739967409674196742967439674496745967469674796748967499675096751967529675396754967559675696757967589675996760967619676296763967649676596766967679676896769967709677196772967739677496775967769677796778967799678096781967829678396784967859678696787967889678996790967919679296793967949679596796967979679896799968009680196802968039680496805968069680796808968099681096811968129681396814968159681696817968189681996820968219682296823968249682596826968279682896829968309683196832968339683496835968369683796838968399684096841968429684396844968459684696847968489684996850968519685296853968549685596856968579685896859968609686196862968639686496865968669686796868968699687096871968729687396874968759687696877968789687996880968819688296883968849688596886968879688896889968909689196892968939689496895968969689796898968999690096901969029690396904969059690696907969089690996910969119691296913969149691596916969179691896919969209692196922969239692496925969269692796928969299693096931969329693396934969359693696937969389693996940969419694296943969449694596946969479694896949969509695196952969539695496955969569695796958969599696096961969629696396964969659696696967969689696996970969719697296973969749697596976969779697896979969809698196982969839698496985969869698796988969899699096991969929699396994969959699696997969989699997000970019700297003970049700597006970079700897009970109701197012970139701497015970169701797018970199702097021970229702397024970259702697027970289702997030970319703297033970349703597036970379703897039970409704197042970439704497045970469704797048970499705097051970529705397054970559705697057970589705997060970619706297063970649706597066970679706897069970709707197072970739707497075970769707797078970799708097081970829708397084970859708697087970889708997090970919709297093970949709597096970979709897099971009710197102971039710497105971069710797108971099711097111971129711397114971159711697117971189711997120971219712297123971249712597126971279712897129971309713197132971339713497135971369713797138971399714097141971429714397144971459714697147971489714997150971519715297153971549715597156971579715897159971609716197162971639716497165971669716797168971699717097171971729717397174971759717697177971789717997180971819718297183971849718597186971879718897189971909719197192971939719497195971969719797198971999720097201972029720397204972059720697207972089720997210972119721297213972149721597216972179721897219972209722197222972239722497225972269722797228972299723097231972329723397234972359723697237972389723997240972419724297243972449724597246972479724897249972509725197252972539725497255972569725797258972599726097261972629726397264972659726697267972689726997270972719727297273972749727597276972779727897279972809728197282972839728497285972869728797288972899729097291972929729397294972959729697297972989729997300973019730297303973049730597306973079730897309973109731197312973139731497315973169731797318973199732097321973229732397324973259732697327973289732997330973319733297333973349733597336973379733897339973409734197342973439734497345973469734797348973499735097351973529735397354973559735697357973589735997360973619736297363973649736597366973679736897369973709737197372973739737497375973769737797378973799738097381973829738397384973859738697387973889738997390973919739297393973949739597396973979739897399974009740197402974039740497405974069740797408974099741097411974129741397414974159741697417974189741997420974219742297423974249742597426974279742897429974309743197432974339743497435974369743797438974399744097441974429744397444974459744697447974489744997450974519745297453974549745597456974579745897459974609746197462974639746497465974669746797468974699747097471974729747397474974759747697477974789747997480974819748297483974849748597486974879748897489974909749197492974939749497495974969749797498974999750097501975029750397504975059750697507975089750997510975119751297513975149751597516975179751897519975209752197522975239752497525975269752797528975299753097531975329753397534975359753697537975389753997540975419754297543975449754597546975479754897549975509755197552975539755497555975569755797558975599756097561975629756397564975659756697567975689756997570975719757297573975749757597576975779757897579975809758197582975839758497585975869758797588975899759097591975929759397594975959759697597975989759997600976019760297603976049760597606976079760897609976109761197612976139761497615976169761797618976199762097621976229762397624976259762697627976289762997630976319763297633976349763597636976379763897639976409764197642976439764497645976469764797648976499765097651976529765397654976559765697657976589765997660976619766297663976649766597666976679766897669976709767197672976739767497675976769767797678976799768097681976829768397684976859768697687976889768997690976919769297693976949769597696976979769897699977009770197702977039770497705977069770797708
  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.slice();
  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 ? samplers.slice() : [];
  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. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "key", {
  240. /**
  241. * Unique key for this effect
  242. */
  243. get: function () {
  244. return this._key;
  245. },
  246. enumerable: true,
  247. configurable: true
  248. });
  249. /**
  250. * If the effect has been compiled and prepared.
  251. * @returns if the effect is compiled and prepared.
  252. */
  253. Effect.prototype.isReady = function () {
  254. return this._isReady;
  255. };
  256. /**
  257. * The engine the effect was initialized with.
  258. * @returns the engine.
  259. */
  260. Effect.prototype.getEngine = function () {
  261. return this._engine;
  262. };
  263. /**
  264. * The compiled webGL program for the effect
  265. * @returns the webGL program.
  266. */
  267. Effect.prototype.getProgram = function () {
  268. return this._program;
  269. };
  270. /**
  271. * The set of names of attribute variables for the shader.
  272. * @returns An array of attribute names.
  273. */
  274. Effect.prototype.getAttributesNames = function () {
  275. return this._attributesNames;
  276. };
  277. /**
  278. * Returns the attribute at the given index.
  279. * @param index The index of the attribute.
  280. * @returns The location of the attribute.
  281. */
  282. Effect.prototype.getAttributeLocation = function (index) {
  283. return this._attributes[index];
  284. };
  285. /**
  286. * Returns the attribute based on the name of the variable.
  287. * @param name of the attribute to look up.
  288. * @returns the attribute location.
  289. */
  290. Effect.prototype.getAttributeLocationByName = function (name) {
  291. var index = this._attributesNames.indexOf(name);
  292. return this._attributes[index];
  293. };
  294. /**
  295. * The number of attributes.
  296. * @returns the numnber of attributes.
  297. */
  298. Effect.prototype.getAttributesCount = function () {
  299. return this._attributes.length;
  300. };
  301. /**
  302. * Gets the index of a uniform variable.
  303. * @param uniformName of the uniform to look up.
  304. * @returns the index.
  305. */
  306. Effect.prototype.getUniformIndex = function (uniformName) {
  307. return this._uniformsNames.indexOf(uniformName);
  308. };
  309. /**
  310. * Returns the attribute based on the name of the variable.
  311. * @param uniformName of the uniform to look up.
  312. * @returns the location of the uniform.
  313. */
  314. Effect.prototype.getUniform = function (uniformName) {
  315. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  316. };
  317. /**
  318. * Returns an array of sampler variable names
  319. * @returns The array of sampler variable neames.
  320. */
  321. Effect.prototype.getSamplers = function () {
  322. return this._samplers;
  323. };
  324. /**
  325. * The error from the last compilation.
  326. * @returns the error string.
  327. */
  328. Effect.prototype.getCompilationError = function () {
  329. return this._compilationError;
  330. };
  331. /**
  332. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  333. * @param func The callback to be used.
  334. */
  335. Effect.prototype.executeWhenCompiled = function (func) {
  336. if (this.isReady()) {
  337. func(this);
  338. return;
  339. }
  340. this.onCompileObservable.add(function (effect) {
  341. func(effect);
  342. });
  343. };
  344. /** @ignore */
  345. Effect.prototype._loadVertexShader = function (vertex, callback) {
  346. if (BABYLON.Tools.IsWindowObjectExist()) {
  347. // DOM element ?
  348. if (vertex instanceof HTMLElement) {
  349. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  350. callback(vertexCode);
  351. return;
  352. }
  353. }
  354. // Base64 encoded ?
  355. if (vertex.substr(0, 7) === "base64:") {
  356. var vertexBinary = window.atob(vertex.substr(7));
  357. callback(vertexBinary);
  358. return;
  359. }
  360. // Is in local store ?
  361. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  362. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  363. return;
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  374. };
  375. /** @ignore */
  376. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. callback(fragmentCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (fragment.substr(0, 7) === "base64:") {
  387. var fragmentBinary = window.atob(fragment.substr(7));
  388. callback(fragmentBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  393. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  394. return;
  395. }
  396. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  397. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  398. return;
  399. }
  400. var fragmentShaderUrl;
  401. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  402. fragmentShaderUrl = fragment;
  403. }
  404. else {
  405. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  406. }
  407. // Fragment shader
  408. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  409. };
  410. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  411. // Rebuild shaders source code
  412. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  413. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  414. vertexCode = prefix + vertexCode;
  415. fragmentCode = prefix + fragmentCode;
  416. // Number lines of shaders source code
  417. var i = 2;
  418. var regex = /\n/gm;
  419. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  420. i = 2;
  421. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  422. // Dump shaders name and formatted source code
  423. if (this.name.vertexElement) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  426. }
  427. else if (this.name.vertex) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  430. }
  431. else {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  434. }
  435. };
  436. ;
  437. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  438. var preparedSourceCode = this._processPrecision(sourceCode);
  439. if (this._engine.webGLVersion == 1) {
  440. callback(preparedSourceCode);
  441. return;
  442. }
  443. // Already converted
  444. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  445. callback(preparedSourceCode.replace("#version 300 es", ""));
  446. return;
  447. }
  448. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  449. // Remove extensions
  450. // #extension GL_OES_standard_derivatives : enable
  451. // #extension GL_EXT_shader_texture_lod : enable
  452. // #extension GL_EXT_frag_depth : enable
  453. // #extension GL_EXT_draw_buffers : require
  454. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  455. var result = preparedSourceCode.replace(regex, "");
  456. // Migrate to GLSL v300
  457. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  458. result = result.replace(/attribute[ \t]/g, "in ");
  459. result = result.replace(/[ \t]attribute/g, " in");
  460. if (isFragment) {
  461. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  462. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/texture2D\s*\(/g, "texture(");
  464. result = result.replace(/textureCube\s*\(/g, "texture(");
  465. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  466. result = result.replace(/gl_FragColor/g, "glFragColor");
  467. result = result.replace(/gl_FragData/g, "glFragData");
  468. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  469. }
  470. callback(result);
  471. };
  472. Effect.prototype._processIncludes = function (sourceCode, callback) {
  473. var _this = this;
  474. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  475. var match = regex.exec(sourceCode);
  476. var returnValue = new String(sourceCode);
  477. while (match != null) {
  478. var includeFile = match[1];
  479. // Uniform declaration
  480. if (includeFile.indexOf("__decl__") !== -1) {
  481. includeFile = includeFile.replace(/__decl__/, "");
  482. if (this._engine.supportsUniformBuffers) {
  483. includeFile = includeFile.replace(/Vertex/, "Ubo");
  484. includeFile = includeFile.replace(/Fragment/, "Ubo");
  485. }
  486. includeFile = includeFile + "Declaration";
  487. }
  488. if (Effect.IncludesShadersStore[includeFile]) {
  489. // Substitution
  490. var includeContent = Effect.IncludesShadersStore[includeFile];
  491. if (match[2]) {
  492. var splits = match[3].split(",");
  493. for (var index = 0; index < splits.length; index += 2) {
  494. var source = new RegExp(splits[index], "g");
  495. var dest = splits[index + 1];
  496. includeContent = includeContent.replace(source, dest);
  497. }
  498. }
  499. if (match[4]) {
  500. var indexString = match[5];
  501. if (indexString.indexOf("..") !== -1) {
  502. var indexSplits = indexString.split("..");
  503. var minIndex = parseInt(indexSplits[0]);
  504. var maxIndex = parseInt(indexSplits[1]);
  505. var sourceIncludeContent = includeContent.slice(0);
  506. includeContent = "";
  507. if (isNaN(maxIndex)) {
  508. maxIndex = this._indexParameters[indexSplits[1]];
  509. }
  510. for (var i = minIndex; i < maxIndex; i++) {
  511. if (!this._engine.supportsUniformBuffers) {
  512. // Ubo replacement
  513. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  514. return p1 + "{X}";
  515. });
  516. }
  517. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  518. }
  519. }
  520. else {
  521. if (!this._engine.supportsUniformBuffers) {
  522. // Ubo replacement
  523. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  524. return p1 + "{X}";
  525. });
  526. }
  527. includeContent = includeContent.replace(/\{X\}/g, indexString);
  528. }
  529. }
  530. // Replace
  531. returnValue = returnValue.replace(match[0], includeContent);
  532. }
  533. else {
  534. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  535. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  536. Effect.IncludesShadersStore[includeFile] = fileContent;
  537. _this._processIncludes(returnValue, callback);
  538. });
  539. return;
  540. }
  541. match = regex.exec(sourceCode);
  542. }
  543. callback(returnValue);
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else { // Sorry we did everything we can
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  714. * @param channel Name of the sampler variable.
  715. * @param texture Texture to set.
  716. */
  717. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  718. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  719. };
  720. /**
  721. * Sets an array of textures on the engine to be used in the shader.
  722. * @param channel Name of the variable.
  723. * @param textures Textures to set.
  724. */
  725. Effect.prototype.setTextureArray = function (channel, textures) {
  726. if (this._samplers.indexOf(channel + "Ex") === -1) {
  727. var initialPos = this._samplers.indexOf(channel);
  728. for (var index = 1; index < textures.length; index++) {
  729. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  730. }
  731. }
  732. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  733. };
  734. /**
  735. * 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)
  736. * @param channel Name of the sampler variable.
  737. * @param postProcess Post process to get the input texture from.
  738. */
  739. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  740. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  741. };
  742. /**
  743. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  744. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  745. * @param channel Name of the sampler variable.
  746. * @param postProcess Post process to get the output texture from.
  747. */
  748. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  749. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  750. };
  751. /** @ignore */
  752. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  753. var cache = this._valueCache[uniformName];
  754. var flag = matrix.updateFlag;
  755. if (cache !== undefined && cache === flag) {
  756. return false;
  757. }
  758. this._valueCache[uniformName] = flag;
  759. return true;
  760. };
  761. /** @ignore */
  762. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  763. var cache = this._valueCache[uniformName];
  764. if (!cache) {
  765. cache = [x, y];
  766. this._valueCache[uniformName] = cache;
  767. return true;
  768. }
  769. var changed = false;
  770. if (cache[0] !== x) {
  771. cache[0] = x;
  772. changed = true;
  773. }
  774. if (cache[1] !== y) {
  775. cache[1] = y;
  776. changed = true;
  777. }
  778. return changed;
  779. };
  780. /** @ignore */
  781. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  782. var cache = this._valueCache[uniformName];
  783. if (!cache) {
  784. cache = [x, y, z];
  785. this._valueCache[uniformName] = cache;
  786. return true;
  787. }
  788. var changed = false;
  789. if (cache[0] !== x) {
  790. cache[0] = x;
  791. changed = true;
  792. }
  793. if (cache[1] !== y) {
  794. cache[1] = y;
  795. changed = true;
  796. }
  797. if (cache[2] !== z) {
  798. cache[2] = z;
  799. changed = true;
  800. }
  801. return changed;
  802. };
  803. /** @ignore */
  804. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y, z, w];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. if (cache[2] !== z) {
  821. cache[2] = z;
  822. changed = true;
  823. }
  824. if (cache[3] !== w) {
  825. cache[3] = w;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /**
  831. * Binds a buffer to a uniform.
  832. * @param buffer Buffer to bind.
  833. * @param name Name of the uniform variable to bind to.
  834. */
  835. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  836. var bufferName = this._uniformBuffersNames[name];
  837. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  838. return;
  839. }
  840. Effect._baseCache[bufferName] = buffer;
  841. this._engine.bindUniformBufferBase(buffer, bufferName);
  842. };
  843. /**
  844. * Binds block to a uniform.
  845. * @param blockName Name of the block to bind.
  846. * @param index Index to bind.
  847. */
  848. Effect.prototype.bindUniformBlock = function (blockName, index) {
  849. this._engine.bindUniformBlock(this._program, blockName, index);
  850. };
  851. /**
  852. * Sets an interger value on a uniform variable.
  853. * @param uniformName Name of the variable.
  854. * @param value Value to be set.
  855. * @returns this effect.
  856. */
  857. Effect.prototype.setInt = function (uniformName, value) {
  858. var cache = this._valueCache[uniformName];
  859. if (cache !== undefined && cache === value)
  860. return this;
  861. this._valueCache[uniformName] = value;
  862. this._engine.setInt(this.getUniform(uniformName), value);
  863. return this;
  864. };
  865. /**
  866. * Sets an int array on a uniform variable.
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * 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)
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setIntArray2 = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setIntArray2(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * 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)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setIntArray3 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setIntArray3(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * 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)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setIntArray4 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setIntArray4(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * Sets an float array on a uniform variable.
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * 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)
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * 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)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * 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)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an array on a uniform variable.
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * 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)
  966. * @param uniformName Name of the variable.
  967. * @param array array to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setArray2 = function (uniformName, array) {
  971. this._valueCache[uniformName] = null;
  972. this._engine.setArray2(this.getUniform(uniformName), array);
  973. return this;
  974. };
  975. /**
  976. * 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)
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. Effect.prototype.setArray3 = function (uniformName, array) {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setArray3(this.getUniform(uniformName), array);
  984. return this;
  985. };
  986. /**
  987. * 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)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. Effect.prototype.setArray4 = function (uniformName, array) {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setArray4(this.getUniform(uniformName), array);
  995. return this;
  996. };
  997. /**
  998. * Sets matrices on a uniform variable.
  999. * @param uniformName Name of the variable.
  1000. * @param matrices matrices to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1004. if (!matrices) {
  1005. return this;
  1006. }
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1009. return this;
  1010. };
  1011. /**
  1012. * Sets matrix on a uniform variable.
  1013. * @param uniformName Name of the variable.
  1014. * @param matrix matrix to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1018. if (this._cacheMatrix(uniformName, matrix)) {
  1019. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1020. }
  1021. return this;
  1022. };
  1023. /**
  1024. * 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)
  1025. * @param uniformName Name of the variable.
  1026. * @param matrix matrix to be set.
  1027. * @returns this effect.
  1028. */
  1029. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1030. this._valueCache[uniformName] = null;
  1031. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1032. return this;
  1033. };
  1034. /**
  1035. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1036. * @param uniformName Name of the variable.
  1037. * @param matrix matrix to be set.
  1038. * @returns this effect.
  1039. */
  1040. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1041. this._valueCache[uniformName] = null;
  1042. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1043. return this;
  1044. };
  1045. /**
  1046. * Sets a float on a uniform variable.
  1047. * @param uniformName Name of the variable.
  1048. * @param value value to be set.
  1049. * @returns this effect.
  1050. */
  1051. Effect.prototype.setFloat = function (uniformName, value) {
  1052. var cache = this._valueCache[uniformName];
  1053. if (cache !== undefined && cache === value)
  1054. return this;
  1055. this._valueCache[uniformName] = value;
  1056. this._engine.setFloat(this.getUniform(uniformName), value);
  1057. return this;
  1058. };
  1059. /**
  1060. * Sets a boolean on a uniform variable.
  1061. * @param uniformName Name of the variable.
  1062. * @param bool value to be set.
  1063. * @returns this effect.
  1064. */
  1065. Effect.prototype.setBool = function (uniformName, bool) {
  1066. var cache = this._valueCache[uniformName];
  1067. if (cache !== undefined && cache === bool)
  1068. return this;
  1069. this._valueCache[uniformName] = bool;
  1070. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a Vector2 on a uniform variable.
  1075. * @param uniformName Name of the variable.
  1076. * @param vector2 vector2 to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1080. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1081. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1082. }
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float2 on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param x First float in float2.
  1089. * @param y Second float in float2.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1093. if (this._cacheFloat2(uniformName, x, y)) {
  1094. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1095. }
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a Vector3 on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param vector3 Value to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1105. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1106. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a float3 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param x First float in float3.
  1114. * @param y Second float in float3.
  1115. * @param z Third float in float3.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1119. if (this._cacheFloat3(uniformName, x, y, z)) {
  1120. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1121. }
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets a Vector4 on a uniform variable.
  1126. * @param uniformName Name of the variable.
  1127. * @param vector4 Value to be set.
  1128. * @returns this effect.
  1129. */
  1130. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1131. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1132. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1133. }
  1134. return this;
  1135. };
  1136. /**
  1137. * Sets a float4 on a uniform variable.
  1138. * @param uniformName Name of the variable.
  1139. * @param x First float in float4.
  1140. * @param y Second float in float4.
  1141. * @param z Third float in float4.
  1142. * @param w Fourth float in float4.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1146. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Color3 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param color3 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setColor3 = function (uniformName, color3) {
  1158. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1159. this._engine.setColor3(this.getUniform(uniformName), color3);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a Color4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param color3 Value to be set.
  1167. * @param alpha Alpha value to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1171. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1172. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a Color4 on a uniform variable
  1178. * @param uniformName defines the name of the variable
  1179. * @param color4 defines the value to be set
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1183. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1184. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Resets the cache of effects.
  1190. */
  1191. Effect.ResetCache = function () {
  1192. Effect._baseCache = {};
  1193. };
  1194. Effect._uniqueIdSeed = 0;
  1195. Effect._baseCache = {};
  1196. /**
  1197. * Store of each shader (The can be looked up using effect.key)
  1198. */
  1199. Effect.ShadersStore = {};
  1200. /**
  1201. * Store of each included file for a shader (The can be looked up using effect.key)
  1202. */
  1203. Effect.IncludesShadersStore = {};
  1204. return Effect;
  1205. }());
  1206. BABYLON.Effect = Effect;
  1207. })(BABYLON || (BABYLON = {}));
  1208. //# sourceMappingURL=babylon.effect.js.map
  1209. //# sourceMappingURL=babylon.types.js.map
  1210. var BABYLON;
  1211. (function (BABYLON) {
  1212. var KeyboardEventTypes = /** @class */ (function () {
  1213. function KeyboardEventTypes() {
  1214. }
  1215. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1216. get: function () {
  1217. return KeyboardEventTypes._KEYDOWN;
  1218. },
  1219. enumerable: true,
  1220. configurable: true
  1221. });
  1222. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1223. get: function () {
  1224. return KeyboardEventTypes._KEYUP;
  1225. },
  1226. enumerable: true,
  1227. configurable: true
  1228. });
  1229. KeyboardEventTypes._KEYDOWN = 0x01;
  1230. KeyboardEventTypes._KEYUP = 0x02;
  1231. return KeyboardEventTypes;
  1232. }());
  1233. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1234. var KeyboardInfo = /** @class */ (function () {
  1235. function KeyboardInfo(type, event) {
  1236. this.type = type;
  1237. this.event = event;
  1238. }
  1239. return KeyboardInfo;
  1240. }());
  1241. BABYLON.KeyboardInfo = KeyboardInfo;
  1242. /**
  1243. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1244. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1245. */
  1246. var KeyboardInfoPre = /** @class */ (function (_super) {
  1247. __extends(KeyboardInfoPre, _super);
  1248. function KeyboardInfoPre(type, event) {
  1249. var _this = _super.call(this, type, event) || this;
  1250. _this.skipOnPointerObservable = false;
  1251. return _this;
  1252. }
  1253. return KeyboardInfoPre;
  1254. }(KeyboardInfo));
  1255. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1256. })(BABYLON || (BABYLON = {}));
  1257. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1258. var BABYLON;
  1259. (function (BABYLON) {
  1260. var PointerEventTypes = /** @class */ (function () {
  1261. function PointerEventTypes() {
  1262. }
  1263. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1264. get: function () {
  1265. return PointerEventTypes._POINTERDOWN;
  1266. },
  1267. enumerable: true,
  1268. configurable: true
  1269. });
  1270. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1271. get: function () {
  1272. return PointerEventTypes._POINTERUP;
  1273. },
  1274. enumerable: true,
  1275. configurable: true
  1276. });
  1277. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1278. get: function () {
  1279. return PointerEventTypes._POINTERMOVE;
  1280. },
  1281. enumerable: true,
  1282. configurable: true
  1283. });
  1284. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1285. get: function () {
  1286. return PointerEventTypes._POINTERWHEEL;
  1287. },
  1288. enumerable: true,
  1289. configurable: true
  1290. });
  1291. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1292. get: function () {
  1293. return PointerEventTypes._POINTERPICK;
  1294. },
  1295. enumerable: true,
  1296. configurable: true
  1297. });
  1298. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1299. get: function () {
  1300. return PointerEventTypes._POINTERTAP;
  1301. },
  1302. enumerable: true,
  1303. configurable: true
  1304. });
  1305. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1306. get: function () {
  1307. return PointerEventTypes._POINTERDOUBLETAP;
  1308. },
  1309. enumerable: true,
  1310. configurable: true
  1311. });
  1312. PointerEventTypes._POINTERDOWN = 0x01;
  1313. PointerEventTypes._POINTERUP = 0x02;
  1314. PointerEventTypes._POINTERMOVE = 0x04;
  1315. PointerEventTypes._POINTERWHEEL = 0x08;
  1316. PointerEventTypes._POINTERPICK = 0x10;
  1317. PointerEventTypes._POINTERTAP = 0x20;
  1318. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1319. return PointerEventTypes;
  1320. }());
  1321. BABYLON.PointerEventTypes = PointerEventTypes;
  1322. var PointerInfoBase = /** @class */ (function () {
  1323. function PointerInfoBase(type, event) {
  1324. this.type = type;
  1325. this.event = event;
  1326. }
  1327. return PointerInfoBase;
  1328. }());
  1329. BABYLON.PointerInfoBase = PointerInfoBase;
  1330. /**
  1331. * This class is used to store pointer related info for the onPrePointerObservable event.
  1332. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1333. */
  1334. var PointerInfoPre = /** @class */ (function (_super) {
  1335. __extends(PointerInfoPre, _super);
  1336. function PointerInfoPre(type, event, localX, localY) {
  1337. var _this = _super.call(this, type, event) || this;
  1338. _this.skipOnPointerObservable = false;
  1339. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1340. return _this;
  1341. }
  1342. return PointerInfoPre;
  1343. }(PointerInfoBase));
  1344. BABYLON.PointerInfoPre = PointerInfoPre;
  1345. /**
  1346. * This type contains all the data related to a pointer event in Babylon.js.
  1347. * 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.
  1348. */
  1349. var PointerInfo = /** @class */ (function (_super) {
  1350. __extends(PointerInfo, _super);
  1351. function PointerInfo(type, event, pickInfo) {
  1352. var _this = _super.call(this, type, event) || this;
  1353. _this.pickInfo = pickInfo;
  1354. return _this;
  1355. }
  1356. return PointerInfo;
  1357. }(PointerInfoBase));
  1358. BABYLON.PointerInfo = PointerInfo;
  1359. })(BABYLON || (BABYLON = {}));
  1360. //# sourceMappingURL=babylon.pointerEvents.js.map
  1361. var BABYLON;
  1362. (function (BABYLON) {
  1363. BABYLON.ToGammaSpace = 1 / 2.2;
  1364. BABYLON.ToLinearSpace = 2.2;
  1365. BABYLON.Epsilon = 0.001;
  1366. /**
  1367. * Class used to hold a RBG color
  1368. */
  1369. var Color3 = /** @class */ (function () {
  1370. /**
  1371. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1372. * @param r defines the red component (between 0 and 1, default is 0)
  1373. * @param g defines the green component (between 0 and 1, default is 0)
  1374. * @param b defines the blue component (between 0 and 1, default is 0)
  1375. */
  1376. function Color3(
  1377. /**
  1378. * Defines the red component (between 0 and 1, default is 0)
  1379. */
  1380. r,
  1381. /**
  1382. * Defines the green component (between 0 and 1, default is 0)
  1383. */
  1384. g,
  1385. /**
  1386. * Defines the blue component (between 0 and 1, default is 0)
  1387. */
  1388. b) {
  1389. if (r === void 0) { r = 0; }
  1390. if (g === void 0) { g = 0; }
  1391. if (b === void 0) { b = 0; }
  1392. this.r = r;
  1393. this.g = g;
  1394. this.b = b;
  1395. }
  1396. /**
  1397. * Creates a string with the Color3 current values
  1398. * @returns the string representation of the Color3 object
  1399. */
  1400. Color3.prototype.toString = function () {
  1401. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1402. };
  1403. /**
  1404. * Returns the string "Color3"
  1405. * @returns "Color3"
  1406. */
  1407. Color3.prototype.getClassName = function () {
  1408. return "Color3";
  1409. };
  1410. /**
  1411. * Compute the Color3 hash code
  1412. * @returns an unique number that can be used to hash Color3 objects
  1413. */
  1414. Color3.prototype.getHashCode = function () {
  1415. var hash = this.r || 0;
  1416. hash = (hash * 397) ^ (this.g || 0);
  1417. hash = (hash * 397) ^ (this.b || 0);
  1418. return hash;
  1419. };
  1420. // Operators
  1421. /**
  1422. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1423. * @param array defines the array where to store the r,g,b components
  1424. * @param index defines an optional index in the target array to define where to start storing values
  1425. * @returns the current Color3 object
  1426. */
  1427. Color3.prototype.toArray = function (array, index) {
  1428. if (index === undefined) {
  1429. index = 0;
  1430. }
  1431. array[index] = this.r;
  1432. array[index + 1] = this.g;
  1433. array[index + 2] = this.b;
  1434. return this;
  1435. };
  1436. /**
  1437. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1438. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1439. * @returns a new {BABYLON.Color4} object
  1440. */
  1441. Color3.prototype.toColor4 = function (alpha) {
  1442. if (alpha === void 0) { alpha = 1; }
  1443. return new Color4(this.r, this.g, this.b, alpha);
  1444. };
  1445. /**
  1446. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1447. * @returns the new array
  1448. */
  1449. Color3.prototype.asArray = function () {
  1450. var result = new Array();
  1451. this.toArray(result, 0);
  1452. return result;
  1453. };
  1454. /**
  1455. * Returns the luminance value
  1456. * @returns a float value
  1457. */
  1458. Color3.prototype.toLuminance = function () {
  1459. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1460. };
  1461. /**
  1462. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1463. * @param otherColor defines the second operand
  1464. * @returns the new Color3 object
  1465. */
  1466. Color3.prototype.multiply = function (otherColor) {
  1467. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1468. };
  1469. /**
  1470. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1471. * @param otherColor defines the second operand
  1472. * @param result defines the Color3 object where to store the result
  1473. * @returns the current Color3
  1474. */
  1475. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1476. result.r = this.r * otherColor.r;
  1477. result.g = this.g * otherColor.g;
  1478. result.b = this.b * otherColor.b;
  1479. return this;
  1480. };
  1481. /**
  1482. * Determines equality between Color3 objects
  1483. * @param otherColor defines the second operand
  1484. * @returns true if the rgb values are equal to the given ones
  1485. */
  1486. Color3.prototype.equals = function (otherColor) {
  1487. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1488. };
  1489. /**
  1490. * Determines equality between the current Color3 object and a set of r,b,g values
  1491. * @param r defines the red component to check
  1492. * @param g defines the green component to check
  1493. * @param b defines the blue component to check
  1494. * @returns true if the rgb values are equal to the given ones
  1495. */
  1496. Color3.prototype.equalsFloats = function (r, g, b) {
  1497. return this.r === r && this.g === g && this.b === b;
  1498. };
  1499. /**
  1500. * Multiplies in place each rgb value by scale
  1501. * @param scale defines the scaling factor
  1502. * @returns the updated Color3
  1503. */
  1504. Color3.prototype.scale = function (scale) {
  1505. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1506. };
  1507. /**
  1508. * Multiplies the rgb values by scale and stores the result into "result"
  1509. * @param scale defines the scaling factor
  1510. * @param result defines the Color3 object where to store the result
  1511. * @returns the unmodified current Color3
  1512. */
  1513. Color3.prototype.scaleToRef = function (scale, result) {
  1514. result.r = this.r * scale;
  1515. result.g = this.g * scale;
  1516. result.b = this.b * scale;
  1517. return this;
  1518. };
  1519. /**
  1520. * Scale the current Color3 values by a factor and add the result to a given Color3
  1521. * @param scale defines the scale factor
  1522. * @param result defines color to store the result into
  1523. * @returns the unmodified current Color3
  1524. */
  1525. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1526. result.r += this.r * scale;
  1527. result.g += this.g * scale;
  1528. result.b += this.b * scale;
  1529. return this;
  1530. };
  1531. /**
  1532. * Clamps the rgb values by the min and max values and stores the result into "result"
  1533. * @param min defines minimum clamping value (default is 0)
  1534. * @param max defines maximum clamping value (default is 1)
  1535. * @param result defines color to store the result into
  1536. * @returns the original Color3
  1537. */
  1538. Color3.prototype.clampToRef = function (min, max, result) {
  1539. if (min === void 0) { min = 0; }
  1540. if (max === void 0) { max = 1; }
  1541. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1542. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1543. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1544. return this;
  1545. };
  1546. /**
  1547. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1548. * @param otherColor defines the second operand
  1549. * @returns the new Color3
  1550. */
  1551. Color3.prototype.add = function (otherColor) {
  1552. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1553. };
  1554. /**
  1555. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1556. * @param otherColor defines the second operand
  1557. * @param result defines Color3 object to store the result into
  1558. * @returns the unmodified current Color3
  1559. */
  1560. Color3.prototype.addToRef = function (otherColor, result) {
  1561. result.r = this.r + otherColor.r;
  1562. result.g = this.g + otherColor.g;
  1563. result.b = this.b + otherColor.b;
  1564. return this;
  1565. };
  1566. /**
  1567. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1568. * @param otherColor defines the second operand
  1569. * @returns the new Color3
  1570. */
  1571. Color3.prototype.subtract = function (otherColor) {
  1572. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1573. };
  1574. /**
  1575. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1576. * @param otherColor defines the second operand
  1577. * @param result defines Color3 object to store the result into
  1578. * @returns the unmodified current Color3
  1579. */
  1580. Color3.prototype.subtractToRef = function (otherColor, result) {
  1581. result.r = this.r - otherColor.r;
  1582. result.g = this.g - otherColor.g;
  1583. result.b = this.b - otherColor.b;
  1584. return this;
  1585. };
  1586. /**
  1587. * Copy the current object
  1588. * @returns a new Color3 copied the current one
  1589. */
  1590. Color3.prototype.clone = function () {
  1591. return new Color3(this.r, this.g, this.b);
  1592. };
  1593. /**
  1594. * Copies the rgb values from the source in the current Color3
  1595. * @param source defines the source Color3 object
  1596. * @returns the updated Color3 object
  1597. */
  1598. Color3.prototype.copyFrom = function (source) {
  1599. this.r = source.r;
  1600. this.g = source.g;
  1601. this.b = source.b;
  1602. return this;
  1603. };
  1604. /**
  1605. * Updates the Color3 rgb values from the given floats
  1606. * @param r defines the red component to read from
  1607. * @param g defines the green component to read from
  1608. * @param b defines the blue component to read from
  1609. * @returns the current Color3 object
  1610. */
  1611. Color3.prototype.copyFromFloats = function (r, g, b) {
  1612. this.r = r;
  1613. this.g = g;
  1614. this.b = b;
  1615. return this;
  1616. };
  1617. /**
  1618. * Updates the Color3 rgb values from the given floats
  1619. * @param r defines the red component to read from
  1620. * @param g defines the green component to read from
  1621. * @param b defines the blue component to read from
  1622. * @returns the current Color3 object
  1623. */
  1624. Color3.prototype.set = function (r, g, b) {
  1625. return this.copyFromFloats(r, g, b);
  1626. };
  1627. /**
  1628. * Compute the Color3 hexadecimal code as a string
  1629. * @returns a string containing the hexadecimal representation of the Color3 object
  1630. */
  1631. Color3.prototype.toHexString = function () {
  1632. var intR = (this.r * 255) | 0;
  1633. var intG = (this.g * 255) | 0;
  1634. var intB = (this.b * 255) | 0;
  1635. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1636. };
  1637. /**
  1638. * Computes a new Color3 converted from the current one to linear space
  1639. * @returns a new Color3 object
  1640. */
  1641. Color3.prototype.toLinearSpace = function () {
  1642. var convertedColor = new Color3();
  1643. this.toLinearSpaceToRef(convertedColor);
  1644. return convertedColor;
  1645. };
  1646. /**
  1647. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1648. * @param convertedColor defines the Color3 object where to store the linear space version
  1649. * @returns the unmodified Color3
  1650. */
  1651. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1652. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1653. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1654. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1655. return this;
  1656. };
  1657. /**
  1658. * Computes a new Color3 converted from the current one to gamma space
  1659. * @returns a new Color3 object
  1660. */
  1661. Color3.prototype.toGammaSpace = function () {
  1662. var convertedColor = new Color3();
  1663. this.toGammaSpaceToRef(convertedColor);
  1664. return convertedColor;
  1665. };
  1666. /**
  1667. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1668. * @param convertedColor defines the Color3 object where to store the gamma space version
  1669. * @returns the unmodified Color3
  1670. */
  1671. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1672. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1673. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1674. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1675. return this;
  1676. };
  1677. // Statics
  1678. /**
  1679. * Creates a new Color3 from the string containing valid hexadecimal values
  1680. * @param hex defines a string containing valid hexadecimal values
  1681. * @returns a new Color3 object
  1682. */
  1683. Color3.FromHexString = function (hex) {
  1684. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1685. return new Color3(0, 0, 0);
  1686. }
  1687. var r = parseInt(hex.substring(1, 3), 16);
  1688. var g = parseInt(hex.substring(3, 5), 16);
  1689. var b = parseInt(hex.substring(5, 7), 16);
  1690. return Color3.FromInts(r, g, b);
  1691. };
  1692. /**
  1693. * Creates a new Vector3 from the starting index of the given array
  1694. * @param array defines the source array
  1695. * @param offset defines an offset in the source array
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.FromArray = function (array, offset) {
  1699. if (offset === void 0) { offset = 0; }
  1700. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1701. };
  1702. /**
  1703. * Creates a new Color3 from integer values (< 256)
  1704. * @param r defines the red component to read from (value between 0 and 255)
  1705. * @param g defines the green component to read from (value between 0 and 255)
  1706. * @param b defines the blue component to read from (value between 0 and 255)
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.FromInts = function (r, g, b) {
  1710. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1711. };
  1712. /**
  1713. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1714. * @param start defines the start Color3 value
  1715. * @param end defines the end Color3 value
  1716. * @param amount defines the gradient value between start and end
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Lerp = function (start, end, amount) {
  1720. var r = start.r + ((end.r - start.r) * amount);
  1721. var g = start.g + ((end.g - start.g) * amount);
  1722. var b = start.b + ((end.b - start.b) * amount);
  1723. return new Color3(r, g, b);
  1724. };
  1725. /**
  1726. * Returns a Color3 value containing a red color
  1727. * @returns a new Color3 object
  1728. */
  1729. Color3.Red = function () { return new Color3(1, 0, 0); };
  1730. /**
  1731. * Returns a Color3 value containing a green color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Green = function () { return new Color3(0, 1, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a blue color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1740. /**
  1741. * Returns a Color3 value containing a black color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Black = function () { return new Color3(0, 0, 0); };
  1745. /**
  1746. * Returns a Color3 value containing a white color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.White = function () { return new Color3(1, 1, 1); };
  1750. /**
  1751. * Returns a Color3 value containing a purple color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1755. /**
  1756. * Returns a Color3 value containing a magenta color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1760. /**
  1761. * Returns a Color3 value containing a yellow color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a gray color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1770. /**
  1771. * Returns a Color3 value containing a teal color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1775. /**
  1776. * Returns a Color3 value containing a random color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1780. return Color3;
  1781. }());
  1782. BABYLON.Color3 = Color3;
  1783. /**
  1784. * Class used to hold a RBGA color
  1785. */
  1786. var Color4 = /** @class */ (function () {
  1787. /**
  1788. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1789. * @param r defines the red component (between 0 and 1, default is 0)
  1790. * @param g defines the green component (between 0 and 1, default is 0)
  1791. * @param b defines the blue component (between 0 and 1, default is 0)
  1792. * @param a defines the alpha component (between 0 and 1, default is 1)
  1793. */
  1794. function Color4(
  1795. /**
  1796. * Defines the red component (between 0 and 1, default is 0)
  1797. */
  1798. r,
  1799. /**
  1800. * Defines the green component (between 0 and 1, default is 0)
  1801. */
  1802. g,
  1803. /**
  1804. * Defines the blue component (between 0 and 1, default is 0)
  1805. */
  1806. b,
  1807. /**
  1808. * Defines the alpha component (between 0 and 1, default is 1)
  1809. */
  1810. a) {
  1811. if (r === void 0) { r = 0; }
  1812. if (g === void 0) { g = 0; }
  1813. if (b === void 0) { b = 0; }
  1814. if (a === void 0) { a = 1; }
  1815. this.r = r;
  1816. this.g = g;
  1817. this.b = b;
  1818. this.a = a;
  1819. }
  1820. // Operators
  1821. /**
  1822. * Adds in place the given Color4 values to the current Color4 object
  1823. * @param right defines the second operand
  1824. * @returns the current updated Color4 object
  1825. */
  1826. Color4.prototype.addInPlace = function (right) {
  1827. this.r += right.r;
  1828. this.g += right.g;
  1829. this.b += right.b;
  1830. this.a += right.a;
  1831. return this;
  1832. };
  1833. /**
  1834. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1835. * @returns the new array
  1836. */
  1837. Color4.prototype.asArray = function () {
  1838. var result = new Array();
  1839. this.toArray(result, 0);
  1840. return result;
  1841. };
  1842. /**
  1843. * Stores from the starting index in the given array the Color4 successive values
  1844. * @param array defines the array where to store the r,g,b components
  1845. * @param index defines an optional index in the target array to define where to start storing values
  1846. * @returns the current Color4 object
  1847. */
  1848. Color4.prototype.toArray = function (array, index) {
  1849. if (index === undefined) {
  1850. index = 0;
  1851. }
  1852. array[index] = this.r;
  1853. array[index + 1] = this.g;
  1854. array[index + 2] = this.b;
  1855. array[index + 3] = this.a;
  1856. return this;
  1857. };
  1858. /**
  1859. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1860. * @param right defines the second operand
  1861. * @returns a new Color4 object
  1862. */
  1863. Color4.prototype.add = function (right) {
  1864. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1865. };
  1866. /**
  1867. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1868. * @param right defines the second operand
  1869. * @returns a new Color4 object
  1870. */
  1871. Color4.prototype.subtract = function (right) {
  1872. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1873. };
  1874. /**
  1875. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1876. * @param right defines the second operand
  1877. * @param result defines the Color4 object where to store the result
  1878. * @returns the current Color4 object
  1879. */
  1880. Color4.prototype.subtractToRef = function (right, result) {
  1881. result.r = this.r - right.r;
  1882. result.g = this.g - right.g;
  1883. result.b = this.b - right.b;
  1884. result.a = this.a - right.a;
  1885. return this;
  1886. };
  1887. /**
  1888. * Creates a new Color4 with the current Color4 values multiplied by scale
  1889. * @param scale defines the scaling factor to apply
  1890. * @returns a new Color4 object
  1891. */
  1892. Color4.prototype.scale = function (scale) {
  1893. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1894. };
  1895. /**
  1896. * Multiplies the current Color4 values by scale and stores the result in "result"
  1897. * @param scale defines the scaling factor to apply
  1898. * @param result defines the Color4 object where to store the result
  1899. * @returns the current unmodified Color4
  1900. */
  1901. Color4.prototype.scaleToRef = function (scale, result) {
  1902. result.r = this.r * scale;
  1903. result.g = this.g * scale;
  1904. result.b = this.b * scale;
  1905. result.a = this.a * scale;
  1906. return this;
  1907. };
  1908. /**
  1909. * Scale the current Color4 values by a factor and add the result to a given Color4
  1910. * @param scale defines the scale factor
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the unmodified current Color4
  1913. */
  1914. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1915. result.r += this.r * scale;
  1916. result.g += this.g * scale;
  1917. result.b += this.b * scale;
  1918. result.a += this.a * scale;
  1919. return this;
  1920. };
  1921. /**
  1922. * Clamps the rgb values by the min and max values and stores the result into "result"
  1923. * @param min defines minimum clamping value (default is 0)
  1924. * @param max defines maximum clamping value (default is 1)
  1925. * @param result defines color to store the result into.
  1926. * @returns the cuurent Color4
  1927. */
  1928. Color4.prototype.clampToRef = function (min, max, result) {
  1929. if (min === void 0) { min = 0; }
  1930. if (max === void 0) { max = 1; }
  1931. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1932. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1933. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1934. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1935. return this;
  1936. };
  1937. /**
  1938. * Multipy an Color4 value by another and return a new Color4 object
  1939. * @param color defines the Color4 value to multiply by
  1940. * @returns a new Color4 object
  1941. */
  1942. Color4.prototype.multiply = function (color) {
  1943. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1944. };
  1945. /**
  1946. * Multipy a Color4 value by another and push the result in a reference value
  1947. * @param color defines the Color4 value to multiply by
  1948. * @param result defines the Color4 to fill the result in
  1949. * @returns the result Color4
  1950. */
  1951. Color4.prototype.multiplyToRef = function (color, result) {
  1952. result.r = this.r * color.r;
  1953. result.g = this.g * color.g;
  1954. result.b = this.b * color.b;
  1955. result.a = this.a * color.a;
  1956. return result;
  1957. };
  1958. /**
  1959. * Creates a string with the Color4 current values
  1960. * @returns the string representation of the Color4 object
  1961. */
  1962. Color4.prototype.toString = function () {
  1963. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1964. };
  1965. /**
  1966. * Returns the string "Color4"
  1967. * @returns "Color4"
  1968. */
  1969. Color4.prototype.getClassName = function () {
  1970. return "Color4";
  1971. };
  1972. /**
  1973. * Compute the Color4 hash code
  1974. * @returns an unique number that can be used to hash Color4 objects
  1975. */
  1976. Color4.prototype.getHashCode = function () {
  1977. var hash = this.r || 0;
  1978. hash = (hash * 397) ^ (this.g || 0);
  1979. hash = (hash * 397) ^ (this.b || 0);
  1980. hash = (hash * 397) ^ (this.a || 0);
  1981. return hash;
  1982. };
  1983. /**
  1984. * Creates a new Color4 copied from the current one
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.clone = function () {
  1988. return new Color4(this.r, this.g, this.b, this.a);
  1989. };
  1990. /**
  1991. * Copies the given Color4 values into the current one
  1992. * @param source defines the source Color4 object
  1993. * @returns the current updated Color4 object
  1994. */
  1995. Color4.prototype.copyFrom = function (source) {
  1996. this.r = source.r;
  1997. this.g = source.g;
  1998. this.b = source.b;
  1999. this.a = source.a;
  2000. return this;
  2001. };
  2002. /**
  2003. * Copies the given float values into the current one
  2004. * @param r defines the red component to read from
  2005. * @param g defines the green component to read from
  2006. * @param b defines the blue component to read from
  2007. * @param a defines the alpha component to read from
  2008. * @returns the current updated Color4 object
  2009. */
  2010. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2011. this.r = r;
  2012. this.g = g;
  2013. this.b = b;
  2014. this.a = a;
  2015. return this;
  2016. };
  2017. /**
  2018. * Copies the given float values into the current one
  2019. * @param r defines the red component to read from
  2020. * @param g defines the green component to read from
  2021. * @param b defines the blue component to read from
  2022. * @param a defines the alpha component to read from
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.set = function (r, g, b, a) {
  2026. return this.copyFromFloats(r, g, b, a);
  2027. };
  2028. /**
  2029. * Compute the Color4 hexadecimal code as a string
  2030. * @returns a string containing the hexadecimal representation of the Color4 object
  2031. */
  2032. Color4.prototype.toHexString = function () {
  2033. var intR = (this.r * 255) | 0;
  2034. var intG = (this.g * 255) | 0;
  2035. var intB = (this.b * 255) | 0;
  2036. var intA = (this.a * 255) | 0;
  2037. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2038. };
  2039. /**
  2040. * Computes a new Color4 converted from the current one to linear space
  2041. * @returns a new Color4 object
  2042. */
  2043. Color4.prototype.toLinearSpace = function () {
  2044. var convertedColor = new Color4();
  2045. this.toLinearSpaceToRef(convertedColor);
  2046. return convertedColor;
  2047. };
  2048. /**
  2049. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2050. * @param convertedColor defines the Color4 object where to store the linear space version
  2051. * @returns the unmodified Color4
  2052. */
  2053. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2054. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2055. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2056. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2057. convertedColor.a = this.a;
  2058. return this;
  2059. };
  2060. /**
  2061. * Computes a new Color4 converted from the current one to gamma space
  2062. * @returns a new Color4 object
  2063. */
  2064. Color4.prototype.toGammaSpace = function () {
  2065. var convertedColor = new Color4();
  2066. this.toGammaSpaceToRef(convertedColor);
  2067. return convertedColor;
  2068. };
  2069. /**
  2070. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2071. * @param convertedColor defines the Color4 object where to store the gamma space version
  2072. * @returns the unmodified Color4
  2073. */
  2074. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2075. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2076. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2077. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2078. convertedColor.a = this.a;
  2079. return this;
  2080. };
  2081. // Statics
  2082. /**
  2083. * Creates a new Color4 from the string containing valid hexadecimal values
  2084. * @param hex defines a string containing valid hexadecimal values
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.FromHexString = function (hex) {
  2088. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2089. return new Color4(0.0, 0.0, 0.0, 0.0);
  2090. }
  2091. var r = parseInt(hex.substring(1, 3), 16);
  2092. var g = parseInt(hex.substring(3, 5), 16);
  2093. var b = parseInt(hex.substring(5, 7), 16);
  2094. var a = parseInt(hex.substring(7, 9), 16);
  2095. return Color4.FromInts(r, g, b, a);
  2096. };
  2097. /**
  2098. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2099. * @param left defines the start value
  2100. * @param right defines the end value
  2101. * @param amount defines the gradient factor
  2102. * @returns a new Color4 object
  2103. */
  2104. Color4.Lerp = function (left, right, amount) {
  2105. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2106. Color4.LerpToRef(left, right, amount, result);
  2107. return result;
  2108. };
  2109. /**
  2110. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2111. * @param left defines the start value
  2112. * @param right defines the end value
  2113. * @param amount defines the gradient factor
  2114. * @param result defines the Color4 object where to store data
  2115. */
  2116. Color4.LerpToRef = function (left, right, amount, result) {
  2117. result.r = left.r + (right.r - left.r) * amount;
  2118. result.g = left.g + (right.g - left.g) * amount;
  2119. result.b = left.b + (right.b - left.b) * amount;
  2120. result.a = left.a + (right.a - left.a) * amount;
  2121. };
  2122. /**
  2123. * Creates a new Color4 from the starting index element of the given array
  2124. * @param array defines the source array to read from
  2125. * @param offset defines the offset in the source array
  2126. * @returns a new Color4 object
  2127. */
  2128. Color4.FromArray = function (array, offset) {
  2129. if (offset === void 0) { offset = 0; }
  2130. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2131. };
  2132. /**
  2133. * Creates a new Color3 from integer values (< 256)
  2134. * @param r defines the red component to read from (value between 0 and 255)
  2135. * @param g defines the green component to read from (value between 0 and 255)
  2136. * @param b defines the blue component to read from (value between 0 and 255)
  2137. * @param a defines the alpha component to read from (value between 0 and 255)
  2138. * @returns a new Color3 object
  2139. */
  2140. Color4.FromInts = function (r, g, b, a) {
  2141. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2142. };
  2143. /**
  2144. * Check the content of a given array and convert it to an array containing RGBA data
  2145. * If the original array was already containing count * 4 values then it is returned directly
  2146. * @param colors defines the array to check
  2147. * @param count defines the number of RGBA data to expect
  2148. * @returns an array containing count * 4 values (RGBA)
  2149. */
  2150. Color4.CheckColors4 = function (colors, count) {
  2151. // Check if color3 was used
  2152. if (colors.length === count * 3) {
  2153. var colors4 = [];
  2154. for (var index = 0; index < colors.length; index += 3) {
  2155. var newIndex = (index / 3) * 4;
  2156. colors4[newIndex] = colors[index];
  2157. colors4[newIndex + 1] = colors[index + 1];
  2158. colors4[newIndex + 2] = colors[index + 2];
  2159. colors4[newIndex + 3] = 1.0;
  2160. }
  2161. return colors4;
  2162. }
  2163. return colors;
  2164. };
  2165. return Color4;
  2166. }());
  2167. BABYLON.Color4 = Color4;
  2168. var Vector2 = /** @class */ (function () {
  2169. /**
  2170. * Creates a new Vector2 from the given x and y coordinates.
  2171. */
  2172. function Vector2(x, y) {
  2173. this.x = x;
  2174. this.y = y;
  2175. }
  2176. /**
  2177. * Returns a string with the Vector2 coordinates.
  2178. */
  2179. Vector2.prototype.toString = function () {
  2180. return "{X: " + this.x + " Y:" + this.y + "}";
  2181. };
  2182. /**
  2183. * Returns the string "Vector2"
  2184. */
  2185. Vector2.prototype.getClassName = function () {
  2186. return "Vector2";
  2187. };
  2188. /**
  2189. * Returns the Vector2 hash code as a number.
  2190. */
  2191. Vector2.prototype.getHashCode = function () {
  2192. var hash = this.x || 0;
  2193. hash = (hash * 397) ^ (this.y || 0);
  2194. return hash;
  2195. };
  2196. // Operators
  2197. /**
  2198. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2199. * Returns the Vector2.
  2200. */
  2201. Vector2.prototype.toArray = function (array, index) {
  2202. if (index === void 0) { index = 0; }
  2203. array[index] = this.x;
  2204. array[index + 1] = this.y;
  2205. return this;
  2206. };
  2207. /**
  2208. * Returns a new array with 2 elements : the Vector2 coordinates.
  2209. */
  2210. Vector2.prototype.asArray = function () {
  2211. var result = new Array();
  2212. this.toArray(result, 0);
  2213. return result;
  2214. };
  2215. /**
  2216. * Sets the Vector2 coordinates with the given Vector2 coordinates.
  2217. * Returns the updated Vector2.
  2218. */
  2219. Vector2.prototype.copyFrom = function (source) {
  2220. this.x = source.x;
  2221. this.y = source.y;
  2222. return this;
  2223. };
  2224. /**
  2225. * Sets the Vector2 coordinates with the given floats.
  2226. * Returns the updated Vector2.
  2227. */
  2228. Vector2.prototype.copyFromFloats = function (x, y) {
  2229. this.x = x;
  2230. this.y = y;
  2231. return this;
  2232. };
  2233. /**
  2234. * Sets the Vector2 coordinates with the given floats.
  2235. * Returns the updated Vector2.
  2236. */
  2237. Vector2.prototype.set = function (x, y) {
  2238. return this.copyFromFloats(x, y);
  2239. };
  2240. /**
  2241. * Returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates.
  2242. */
  2243. Vector2.prototype.add = function (otherVector) {
  2244. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2245. };
  2246. /**
  2247. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates.
  2248. * Returns the Vector2.
  2249. */
  2250. Vector2.prototype.addToRef = function (otherVector, result) {
  2251. result.x = this.x + otherVector.x;
  2252. result.y = this.y + otherVector.y;
  2253. return this;
  2254. };
  2255. /**
  2256. * Set the Vector2 coordinates by adding the given Vector2 coordinates.
  2257. * Returns the updated Vector2.
  2258. */
  2259. Vector2.prototype.addInPlace = function (otherVector) {
  2260. this.x += otherVector.x;
  2261. this.y += otherVector.y;
  2262. return this;
  2263. };
  2264. /**
  2265. * Returns a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates.
  2266. */
  2267. Vector2.prototype.addVector3 = function (otherVector) {
  2268. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2269. };
  2270. /**
  2271. * Returns a new Vector2 set with the subtracted coordinates of the given one from the current Vector2.
  2272. */
  2273. Vector2.prototype.subtract = function (otherVector) {
  2274. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2275. };
  2276. /**
  2277. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2278. * Returns the Vector2.
  2279. */
  2280. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2281. result.x = this.x - otherVector.x;
  2282. result.y = this.y - otherVector.y;
  2283. return this;
  2284. };
  2285. /**
  2286. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates.
  2287. * Returns the updated Vector2.
  2288. */
  2289. Vector2.prototype.subtractInPlace = function (otherVector) {
  2290. this.x -= otherVector.x;
  2291. this.y -= otherVector.y;
  2292. return this;
  2293. };
  2294. /**
  2295. * Multiplies in place the current Vector2 coordinates by the given ones.
  2296. * Returns the updated Vector2.
  2297. */
  2298. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2299. this.x *= otherVector.x;
  2300. this.y *= otherVector.y;
  2301. return this;
  2302. };
  2303. /**
  2304. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates.
  2305. */
  2306. Vector2.prototype.multiply = function (otherVector) {
  2307. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2308. };
  2309. /**
  2310. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates.
  2311. * Returns the Vector2.
  2312. */
  2313. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2314. result.x = this.x * otherVector.x;
  2315. result.y = this.y * otherVector.y;
  2316. return this;
  2317. };
  2318. /**
  2319. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the given floats.
  2320. */
  2321. Vector2.prototype.multiplyByFloats = function (x, y) {
  2322. return new Vector2(this.x * x, this.y * y);
  2323. };
  2324. /**
  2325. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates.
  2326. */
  2327. Vector2.prototype.divide = function (otherVector) {
  2328. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2329. };
  2330. /**
  2331. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates.
  2332. * Returns the Vector2.
  2333. */
  2334. Vector2.prototype.divideToRef = function (otherVector, result) {
  2335. result.x = this.x / otherVector.x;
  2336. result.y = this.y / otherVector.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Divides the current Vector3 coordinates by the given ones.
  2341. * Returns the updated Vector3.
  2342. */
  2343. Vector2.prototype.divideInPlace = function (otherVector) {
  2344. return this.divideToRef(otherVector, this);
  2345. };
  2346. /**
  2347. * Returns a new Vector2 with current Vector2 negated coordinates.
  2348. */
  2349. Vector2.prototype.negate = function () {
  2350. return new Vector2(-this.x, -this.y);
  2351. };
  2352. /**
  2353. * Multiply the Vector2 coordinates by scale.
  2354. * Returns the updated Vector2.
  2355. */
  2356. Vector2.prototype.scaleInPlace = function (scale) {
  2357. this.x *= scale;
  2358. this.y *= scale;
  2359. return this;
  2360. };
  2361. /**
  2362. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2363. */
  2364. Vector2.prototype.scale = function (scale) {
  2365. var result = new Vector2(0, 0);
  2366. this.scaleToRef(scale, result);
  2367. return result;
  2368. };
  2369. /**
  2370. * Scale the current Vector2 values by a factor to a given Vector2
  2371. * @param scale defines the scale factor
  2372. * @param result defines the Vector2 object where to store the result
  2373. * @returns the unmodified current Vector2
  2374. */
  2375. Vector2.prototype.scaleToRef = function (scale, result) {
  2376. result.x = this.x * scale;
  2377. result.y = this.y * scale;
  2378. return this;
  2379. };
  2380. /**
  2381. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2382. * @param scale defines the scale factor
  2383. * @param result defines the Vector2 object where to store the result
  2384. * @returns the unmodified current Vector2
  2385. */
  2386. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2387. result.x += this.x * scale;
  2388. result.y += this.y * scale;
  2389. return this;
  2390. };
  2391. /**
  2392. * Boolean : True if the given vector coordinates strictly equal the current Vector2 ones.
  2393. */
  2394. Vector2.prototype.equals = function (otherVector) {
  2395. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2396. };
  2397. /**
  2398. * Boolean : True if the given vector coordinates are close to the current ones by a distance of epsilon.
  2399. */
  2400. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2401. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2402. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2403. };
  2404. // Properties
  2405. /**
  2406. * Returns the vector length (float).
  2407. */
  2408. Vector2.prototype.length = function () {
  2409. return Math.sqrt(this.x * this.x + this.y * this.y);
  2410. };
  2411. /**
  2412. * Returns the vector squared length (float);
  2413. */
  2414. Vector2.prototype.lengthSquared = function () {
  2415. return (this.x * this.x + this.y * this.y);
  2416. };
  2417. // Methods
  2418. /**
  2419. * Normalize the vector.
  2420. * Returns the updated Vector2.
  2421. */
  2422. Vector2.prototype.normalize = function () {
  2423. var len = this.length();
  2424. if (len === 0)
  2425. return this;
  2426. var num = 1.0 / len;
  2427. this.x *= num;
  2428. this.y *= num;
  2429. return this;
  2430. };
  2431. /**
  2432. * Returns a new Vector2 copied from the Vector2.
  2433. */
  2434. Vector2.prototype.clone = function () {
  2435. return new Vector2(this.x, this.y);
  2436. };
  2437. // Statics
  2438. /**
  2439. * Returns a new Vector2(0, 0)
  2440. */
  2441. Vector2.Zero = function () {
  2442. return new Vector2(0, 0);
  2443. };
  2444. /**
  2445. * Returns a new Vector2(1, 1)
  2446. */
  2447. Vector2.One = function () {
  2448. return new Vector2(1, 1);
  2449. };
  2450. /**
  2451. * Returns a new Vector2 set from the given index element of the given array.
  2452. */
  2453. Vector2.FromArray = function (array, offset) {
  2454. if (offset === void 0) { offset = 0; }
  2455. return new Vector2(array[offset], array[offset + 1]);
  2456. };
  2457. /**
  2458. * Sets "result" from the given index element of the given array.
  2459. */
  2460. Vector2.FromArrayToRef = function (array, offset, result) {
  2461. result.x = array[offset];
  2462. result.y = array[offset + 1];
  2463. };
  2464. /**
  2465. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2.
  2466. */
  2467. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2468. var squared = amount * amount;
  2469. var cubed = amount * squared;
  2470. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2471. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2472. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2473. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2474. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2475. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2476. return new Vector2(x, y);
  2477. };
  2478. /**
  2479. * 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".
  2480. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2481. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2482. */
  2483. Vector2.Clamp = function (value, min, max) {
  2484. var x = value.x;
  2485. x = (x > max.x) ? max.x : x;
  2486. x = (x < min.x) ? min.x : x;
  2487. var y = value.y;
  2488. y = (y > max.y) ? max.y : y;
  2489. y = (y < min.y) ? min.y : y;
  2490. return new Vector2(x, y);
  2491. };
  2492. /**
  2493. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2494. */
  2495. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2496. var squared = amount * amount;
  2497. var cubed = amount * squared;
  2498. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2499. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2500. var part3 = (cubed - (2.0 * squared)) + amount;
  2501. var part4 = cubed - squared;
  2502. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2503. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2504. return new Vector2(x, y);
  2505. };
  2506. /**
  2507. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2508. */
  2509. Vector2.Lerp = function (start, end, amount) {
  2510. var x = start.x + ((end.x - start.x) * amount);
  2511. var y = start.y + ((end.y - start.y) * amount);
  2512. return new Vector2(x, y);
  2513. };
  2514. /**
  2515. * Returns the dot product (float) of the vector "left" and the vector "right".
  2516. */
  2517. Vector2.Dot = function (left, right) {
  2518. return left.x * right.x + left.y * right.y;
  2519. };
  2520. /**
  2521. * Returns a new Vector2 equal to the normalized given vector.
  2522. */
  2523. Vector2.Normalize = function (vector) {
  2524. var newVector = vector.clone();
  2525. newVector.normalize();
  2526. return newVector;
  2527. };
  2528. /**
  2529. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2530. */
  2531. Vector2.Minimize = function (left, right) {
  2532. var x = (left.x < right.x) ? left.x : right.x;
  2533. var y = (left.y < right.y) ? left.y : right.y;
  2534. return new Vector2(x, y);
  2535. };
  2536. /**
  2537. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2538. */
  2539. Vector2.Maximize = function (left, right) {
  2540. var x = (left.x > right.x) ? left.x : right.x;
  2541. var y = (left.y > right.y) ? left.y : right.y;
  2542. return new Vector2(x, y);
  2543. };
  2544. /**
  2545. * Returns a new Vecto2 set with the transformed coordinates of the given vector by the given transformation matrix.
  2546. */
  2547. Vector2.Transform = function (vector, transformation) {
  2548. var r = Vector2.Zero();
  2549. Vector2.TransformToRef(vector, transformation, r);
  2550. return r;
  2551. };
  2552. /**
  2553. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates.
  2554. */
  2555. Vector2.TransformToRef = function (vector, transformation, result) {
  2556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2558. result.x = x;
  2559. result.y = y;
  2560. };
  2561. /**
  2562. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2563. */
  2564. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2565. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2566. var sign = a < 0 ? -1 : 1;
  2567. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2568. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2569. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2570. };
  2571. /**
  2572. * Returns the distance (float) between the vectors "value1" and "value2".
  2573. */
  2574. Vector2.Distance = function (value1, value2) {
  2575. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2576. };
  2577. /**
  2578. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2579. */
  2580. Vector2.DistanceSquared = function (value1, value2) {
  2581. var x = value1.x - value2.x;
  2582. var y = value1.y - value2.y;
  2583. return (x * x) + (y * y);
  2584. };
  2585. /**
  2586. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2587. */
  2588. Vector2.Center = function (value1, value2) {
  2589. var center = value1.add(value2);
  2590. center.scaleInPlace(0.5);
  2591. return center;
  2592. };
  2593. /**
  2594. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2595. */
  2596. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2597. var l2 = Vector2.DistanceSquared(segA, segB);
  2598. if (l2 === 0.0) {
  2599. return Vector2.Distance(p, segA);
  2600. }
  2601. var v = segB.subtract(segA);
  2602. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2603. var proj = segA.add(v.multiplyByFloats(t, t));
  2604. return Vector2.Distance(p, proj);
  2605. };
  2606. return Vector2;
  2607. }());
  2608. BABYLON.Vector2 = Vector2;
  2609. /**
  2610. * Classed used to store (x,y,z) vector representation
  2611. * A Vector3 is the main object used in 3D geometry
  2612. * It can represent etiher the coordinates of a point the space, either a direction
  2613. * Reminder: Babylon.js uses a left handed forward facing system
  2614. */
  2615. var Vector3 = /** @class */ (function () {
  2616. /**
  2617. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2618. * @param x defines the first coordinates (on X axis)
  2619. * @param y defines the second coordinates (on Y axis)
  2620. * @param z defines the third coordinates (on Z axis)
  2621. */
  2622. function Vector3(
  2623. /**
  2624. * Defines the first coordinates (on X axis)
  2625. */
  2626. x,
  2627. /**
  2628. * Defines the second coordinates (on Y axis)
  2629. */
  2630. y,
  2631. /**
  2632. * Defines the third coordinates (on Z axis)
  2633. */
  2634. z) {
  2635. this.x = x;
  2636. this.y = y;
  2637. this.z = z;
  2638. }
  2639. /**
  2640. * Creates a string representation of the Vector3
  2641. * @returns a string with the Vector3 coordinates.
  2642. */
  2643. Vector3.prototype.toString = function () {
  2644. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2645. };
  2646. /**
  2647. * Gets the class name
  2648. * @returns the string "Vector3"
  2649. */
  2650. Vector3.prototype.getClassName = function () {
  2651. return "Vector3";
  2652. };
  2653. /**
  2654. * Creates the Vector3 hash code
  2655. * @returns a number which tends to be unique between Vector3 instances
  2656. */
  2657. Vector3.prototype.getHashCode = function () {
  2658. var hash = this.x || 0;
  2659. hash = (hash * 397) ^ (this.y || 0);
  2660. hash = (hash * 397) ^ (this.z || 0);
  2661. return hash;
  2662. };
  2663. // Operators
  2664. /**
  2665. * Creates an array containing three elements : the coordinates of the Vector3
  2666. * @returns a new array of numbers
  2667. */
  2668. Vector3.prototype.asArray = function () {
  2669. var result = [];
  2670. this.toArray(result, 0);
  2671. return result;
  2672. };
  2673. /**
  2674. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2675. * @param array defines the destination array
  2676. * @param index defines the offset in the destination array
  2677. * @returns the current Vector3
  2678. */
  2679. Vector3.prototype.toArray = function (array, index) {
  2680. if (index === void 0) { index = 0; }
  2681. array[index] = this.x;
  2682. array[index + 1] = this.y;
  2683. array[index + 2] = this.z;
  2684. return this;
  2685. };
  2686. /**
  2687. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2688. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2689. */
  2690. Vector3.prototype.toQuaternion = function () {
  2691. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2692. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2693. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2694. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2695. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2696. var cosy = Math.cos(this.y * 0.5);
  2697. var siny = Math.sin(this.y * 0.5);
  2698. result.x = coszMinusx * siny;
  2699. result.y = -sinzMinusx * siny;
  2700. result.z = sinxPlusz * cosy;
  2701. result.w = cosxPlusz * cosy;
  2702. return result;
  2703. };
  2704. /**
  2705. * Adds the given vector to the current Vector3
  2706. * @param otherVector defines the second operand
  2707. * @returns the current updated Vector3
  2708. */
  2709. Vector3.prototype.addInPlace = function (otherVector) {
  2710. this.x += otherVector.x;
  2711. this.y += otherVector.y;
  2712. this.z += otherVector.z;
  2713. return this;
  2714. };
  2715. /**
  2716. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2717. * @param otherVector defines the second operand
  2718. * @returns the resulting Vector3
  2719. */
  2720. Vector3.prototype.add = function (otherVector) {
  2721. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2722. };
  2723. /**
  2724. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2725. * @param otherVector defines the second operand
  2726. * @param result defines the Vector3 object where to store the result
  2727. * @returns the current Vector3
  2728. */
  2729. Vector3.prototype.addToRef = function (otherVector, result) {
  2730. result.x = this.x + otherVector.x;
  2731. result.y = this.y + otherVector.y;
  2732. result.z = this.z + otherVector.z;
  2733. return this;
  2734. };
  2735. /**
  2736. * Subtract the given vector from the current Vector3
  2737. * @param otherVector defines the second operand
  2738. * @returns the current updated Vector3
  2739. */
  2740. Vector3.prototype.subtractInPlace = function (otherVector) {
  2741. this.x -= otherVector.x;
  2742. this.y -= otherVector.y;
  2743. this.z -= otherVector.z;
  2744. return this;
  2745. };
  2746. /**
  2747. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2748. * @param otherVector defines the second operand
  2749. * @returns the resulting Vector3
  2750. */
  2751. Vector3.prototype.subtract = function (otherVector) {
  2752. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2753. };
  2754. /**
  2755. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2756. * @param otherVector defines the second operand
  2757. * @param result defines the Vector3 object where to store the result
  2758. * @returns the current Vector3
  2759. */
  2760. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2761. result.x = this.x - otherVector.x;
  2762. result.y = this.y - otherVector.y;
  2763. result.z = this.z - otherVector.z;
  2764. return this;
  2765. };
  2766. /**
  2767. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2768. * @param x defines the x coordinate of the operand
  2769. * @param y defines the y coordinate of the operand
  2770. * @param z defines the z coordinate of the operand
  2771. * @returns the resulting Vector3
  2772. */
  2773. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2774. return new Vector3(this.x - x, this.y - y, this.z - z);
  2775. };
  2776. /**
  2777. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2778. * @param x defines the x coordinate of the operand
  2779. * @param y defines the y coordinate of the operand
  2780. * @param z defines the z coordinate of the operand
  2781. * @param result defines the Vector3 object where to store the result
  2782. * @returns the current Vector3
  2783. */
  2784. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2785. result.x = this.x - x;
  2786. result.y = this.y - y;
  2787. result.z = this.z - z;
  2788. return this;
  2789. };
  2790. /**
  2791. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2792. * @returns a new Vector3
  2793. */
  2794. Vector3.prototype.negate = function () {
  2795. return new Vector3(-this.x, -this.y, -this.z);
  2796. };
  2797. /**
  2798. * Multiplies the Vector3 coordinates by the float "scale"
  2799. * @param scale defines the multiplier factor
  2800. * @returns the current updated Vector3
  2801. */
  2802. Vector3.prototype.scaleInPlace = function (scale) {
  2803. this.x *= scale;
  2804. this.y *= scale;
  2805. this.z *= scale;
  2806. return this;
  2807. };
  2808. /**
  2809. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2810. * @param scale defines the multiplier factor
  2811. * @returns a new Vector3
  2812. */
  2813. Vector3.prototype.scale = function (scale) {
  2814. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2815. };
  2816. /**
  2817. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2818. * @param scale defines the multiplier factor
  2819. * @param result defines the Vector3 object where to store the result
  2820. * @returns the current Vector3
  2821. */
  2822. Vector3.prototype.scaleToRef = function (scale, result) {
  2823. result.x = this.x * scale;
  2824. result.y = this.y * scale;
  2825. result.z = this.z * scale;
  2826. return this;
  2827. };
  2828. /**
  2829. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2830. * @param scale defines the scale factor
  2831. * @param result defines the Vector3 object where to store the result
  2832. * @returns the unmodified current Vector3
  2833. */
  2834. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2835. result.x += this.x * scale;
  2836. result.y += this.y * scale;
  2837. result.z += this.z * scale;
  2838. return this;
  2839. };
  2840. /**
  2841. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2842. * @param otherVector defines the second operand
  2843. * @returns true if both vectors are equals
  2844. */
  2845. Vector3.prototype.equals = function (otherVector) {
  2846. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2847. };
  2848. /**
  2849. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2850. * @param otherVector defines the second operand
  2851. * @param epsilon defines the minimal distance to define values as equals
  2852. * @returns true if both vectors are distant less than epsilon
  2853. */
  2854. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2855. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2856. 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);
  2857. };
  2858. /**
  2859. * Returns true if the current Vector3 coordinates equals the given floats
  2860. * @param x defines the x coordinate of the operand
  2861. * @param y defines the y coordinate of the operand
  2862. * @param z defines the z coordinate of the operand
  2863. * @returns true if both vectors are equals
  2864. */
  2865. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2866. return this.x === x && this.y === y && this.z === z;
  2867. };
  2868. /**
  2869. * Multiplies the current Vector3 coordinates by the given ones
  2870. * @param otherVector defines the second operand
  2871. * @returns the current updated Vector3
  2872. */
  2873. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2874. this.x *= otherVector.x;
  2875. this.y *= otherVector.y;
  2876. this.z *= otherVector.z;
  2877. return this;
  2878. };
  2879. /**
  2880. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2881. * @param otherVector defines the second operand
  2882. * @returns the new Vector3
  2883. */
  2884. Vector3.prototype.multiply = function (otherVector) {
  2885. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2886. };
  2887. /**
  2888. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  2889. * @param otherVector defines the second operand
  2890. * @param result defines the Vector3 object where to store the result
  2891. * @returns the current Vector3
  2892. */
  2893. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2894. result.x = this.x * otherVector.x;
  2895. result.y = this.y * otherVector.y;
  2896. result.z = this.z * otherVector.z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  2901. * @param x defines the x coordinate of the operand
  2902. * @param y defines the y coordinate of the operand
  2903. * @param z defines the z coordinate of the operand
  2904. * @returns the new Vector3
  2905. */
  2906. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2907. return new Vector3(this.x * x, this.y * y, this.z * z);
  2908. };
  2909. /**
  2910. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  2911. * @param otherVector defines the second operand
  2912. * @returns the new Vector3
  2913. */
  2914. Vector3.prototype.divide = function (otherVector) {
  2915. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2916. };
  2917. /**
  2918. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  2919. * @param otherVector defines the second operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.divideToRef = function (otherVector, result) {
  2924. result.x = this.x / otherVector.x;
  2925. result.y = this.y / otherVector.y;
  2926. result.z = this.z / otherVector.z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Divides the current Vector3 coordinates by the given ones.
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.divideInPlace = function (otherVector) {
  2935. return this.divideToRef(otherVector, this);
  2936. };
  2937. /**
  2938. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  2939. * @param other defines the second operand
  2940. * @returns the current updated Vector3
  2941. */
  2942. Vector3.prototype.minimizeInPlace = function (other) {
  2943. if (other.x < this.x)
  2944. this.x = other.x;
  2945. if (other.y < this.y)
  2946. this.y = other.y;
  2947. if (other.z < this.z)
  2948. this.z = other.z;
  2949. return this;
  2950. };
  2951. /**
  2952. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  2953. * @param other defines the second operand
  2954. * @returns the current updated Vector3
  2955. */
  2956. Vector3.prototype.maximizeInPlace = function (other) {
  2957. if (other.x > this.x)
  2958. this.x = other.x;
  2959. if (other.y > this.y)
  2960. this.y = other.y;
  2961. if (other.z > this.z)
  2962. this.z = other.z;
  2963. return this;
  2964. };
  2965. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2966. /**
  2967. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2968. */
  2969. get: function () {
  2970. var absX = Math.abs(this.x);
  2971. var absY = Math.abs(this.y);
  2972. if (absX !== absY) {
  2973. return true;
  2974. }
  2975. var absZ = Math.abs(this.z);
  2976. if (absX !== absZ) {
  2977. return true;
  2978. }
  2979. if (absY !== absZ) {
  2980. return true;
  2981. }
  2982. return false;
  2983. },
  2984. enumerable: true,
  2985. configurable: true
  2986. });
  2987. // Properties
  2988. /**
  2989. * Gets the length of the Vector3
  2990. * @returns the length of the Vecto3
  2991. */
  2992. Vector3.prototype.length = function () {
  2993. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2994. };
  2995. /**
  2996. * Gets the squared length of the Vector3
  2997. * @returns squared length of the Vector3
  2998. */
  2999. Vector3.prototype.lengthSquared = function () {
  3000. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3001. };
  3002. /**
  3003. * Normalize the current Vector3.
  3004. * Please note that this is an in place operation.
  3005. * @returns the current updated Vector3
  3006. */
  3007. Vector3.prototype.normalize = function () {
  3008. var len = this.length();
  3009. if (len === 0 || len === 1.0)
  3010. return this;
  3011. var num = 1.0 / len;
  3012. this.x *= num;
  3013. this.y *= num;
  3014. this.z *= num;
  3015. return this;
  3016. };
  3017. /**
  3018. * Normalize the current Vector3 to a new vector
  3019. * @returns the new Vector3
  3020. */
  3021. Vector3.prototype.normalizeToNew = function () {
  3022. var normalized = new Vector3(0, 0, 0);
  3023. this.normalizeToRef(normalized);
  3024. return normalized;
  3025. };
  3026. /**
  3027. * Normalize the current Vector3 to the reference
  3028. * @param reference define the Vector3 to update
  3029. * @returns the updated Vector3
  3030. */
  3031. Vector3.prototype.normalizeToRef = function (reference) {
  3032. var len = this.length();
  3033. if (len === 0 || len === 1.0) {
  3034. reference.set(this.x, this.y, this.z);
  3035. return reference;
  3036. }
  3037. var scale = 1.0 / len;
  3038. this.scaleToRef(scale, reference);
  3039. return reference;
  3040. };
  3041. /**
  3042. * Creates a new Vector3 copied from the current Vector3
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.clone = function () {
  3046. return new Vector3(this.x, this.y, this.z);
  3047. };
  3048. /**
  3049. * Copies the given vector coordinates to the current Vector3 ones
  3050. * @param source defines the source Vector3
  3051. * @returns the current updated Vector3
  3052. */
  3053. Vector3.prototype.copyFrom = function (source) {
  3054. this.x = source.x;
  3055. this.y = source.y;
  3056. this.z = source.z;
  3057. return this;
  3058. };
  3059. /**
  3060. * Copies the given floats to the current Vector3 coordinates
  3061. * @param x defines the x coordinate of the operand
  3062. * @param y defines the y coordinate of the operand
  3063. * @param z defines the z coordinate of the operand
  3064. * @returns the current updated Vector3
  3065. */
  3066. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3067. this.x = x;
  3068. this.y = y;
  3069. this.z = z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Copies the given floats to the current Vector3 coordinates
  3074. * @param x defines the x coordinate of the operand
  3075. * @param y defines the y coordinate of the operand
  3076. * @param z defines the z coordinate of the operand
  3077. * @returns the current updated Vector3
  3078. */
  3079. Vector3.prototype.set = function (x, y, z) {
  3080. return this.copyFromFloats(x, y, z);
  3081. };
  3082. // Statics
  3083. /**
  3084. * Get the clip factor between two vectors
  3085. * @param vector0 defines the first operand
  3086. * @param vector1 defines the second operand
  3087. * @param axis defines the axis to use
  3088. * @param size defines the size along the axis
  3089. * @returns the clip factor
  3090. */
  3091. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3092. var d0 = Vector3.Dot(vector0, axis) - size;
  3093. var d1 = Vector3.Dot(vector1, axis) - size;
  3094. var s = d0 / (d0 - d1);
  3095. return s;
  3096. };
  3097. /**
  3098. * Get angle between two vectors
  3099. * @param vector0 angle between vector0 and vector1
  3100. * @param vector1 angle between vector0 and vector1
  3101. * @param normal direction of the normal
  3102. * @return the angle between vector0 and vector1
  3103. */
  3104. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3105. var v0 = vector0.clone().normalize();
  3106. var v1 = vector1.clone().normalize();
  3107. var dot = Vector3.Dot(v0, v1);
  3108. var n = Vector3.Cross(v0, v1);
  3109. if (Vector3.Dot(n, normal) > 0) {
  3110. return Math.acos(dot);
  3111. }
  3112. return -Math.acos(dot);
  3113. };
  3114. /**
  3115. * Returns a new Vector3 set from the index "offset" of the given array
  3116. * @param array defines the source array
  3117. * @param offset defines the offset in the source array
  3118. * @returns the new Vector3
  3119. */
  3120. Vector3.FromArray = function (array, offset) {
  3121. if (!offset) {
  3122. offset = 0;
  3123. }
  3124. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3125. };
  3126. /**
  3127. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3128. * This function is deprecated. Use FromArray instead
  3129. * @param array defines the source array
  3130. * @param offset defines the offset in the source array
  3131. * @returns the new Vector3
  3132. */
  3133. Vector3.FromFloatArray = function (array, offset) {
  3134. return Vector3.FromArray(array, offset);
  3135. };
  3136. /**
  3137. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3138. * @param array defines the source array
  3139. * @param offset defines the offset in the source array
  3140. * @param result defines the Vector3 where to store the result
  3141. */
  3142. Vector3.FromArrayToRef = function (array, offset, result) {
  3143. result.x = array[offset];
  3144. result.y = array[offset + 1];
  3145. result.z = array[offset + 2];
  3146. };
  3147. /**
  3148. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3149. * This function is deprecated. Use FromArrayToRef instead.
  3150. * @param array defines the source array
  3151. * @param offset defines the offset in the source array
  3152. * @param result defines the Vector3 where to store the result
  3153. */
  3154. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3155. return Vector3.FromArrayToRef(array, offset, result);
  3156. };
  3157. /**
  3158. * Sets the given vector "result" with the given floats.
  3159. * @param x defines the x coordinate of the source
  3160. * @param y defines the y coordinate of the source
  3161. * @param z defines the z coordinate of the source
  3162. * @param result defines the Vector3 where to store the result
  3163. */
  3164. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3165. result.x = x;
  3166. result.y = y;
  3167. result.z = z;
  3168. };
  3169. /**
  3170. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3171. * @returns a new empty Vector3
  3172. */
  3173. Vector3.Zero = function () {
  3174. return new Vector3(0.0, 0.0, 0.0);
  3175. };
  3176. /**
  3177. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3178. * @returns a new unit Vector3
  3179. */
  3180. Vector3.One = function () {
  3181. return new Vector3(1.0, 1.0, 1.0);
  3182. };
  3183. /**
  3184. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3185. * @returns a new up Vector3
  3186. */
  3187. Vector3.Up = function () {
  3188. return new Vector3(0.0, 1.0, 0.0);
  3189. };
  3190. /**
  3191. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3192. * @returns a new forward Vector3
  3193. */
  3194. Vector3.Forward = function () {
  3195. return new Vector3(0.0, 0.0, 1.0);
  3196. };
  3197. /**
  3198. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3199. * @returns a new right Vector3
  3200. */
  3201. Vector3.Right = function () {
  3202. return new Vector3(1.0, 0.0, 0.0);
  3203. };
  3204. /**
  3205. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3206. * @returns a new left Vector3
  3207. */
  3208. Vector3.Left = function () {
  3209. return new Vector3(-1.0, 0.0, 0.0);
  3210. };
  3211. /**
  3212. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3213. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3214. * @param vector defines the Vector3 to transform
  3215. * @param transformation defines the transformation matrix
  3216. * @returns the transformed Vector3
  3217. */
  3218. Vector3.TransformCoordinates = function (vector, transformation) {
  3219. var result = Vector3.Zero();
  3220. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3225. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3226. * @param vector defines the Vector3 to transform
  3227. * @param transformation defines the transformation matrix
  3228. * @param result defines the Vector3 where to store the result
  3229. */
  3230. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3231. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3232. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3233. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3234. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3235. result.x = x / w;
  3236. result.y = y / w;
  3237. result.z = z / w;
  3238. };
  3239. /**
  3240. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3241. * This method computes tranformed coordinates only, not transformed direction vectors
  3242. * @param x define the x coordinate of the source vector
  3243. * @param y define the y coordinate of the source vector
  3244. * @param z define the z coordinate of the source vector
  3245. * @param transformation defines the transformation matrix
  3246. * @param result defines the Vector3 where to store the result
  3247. */
  3248. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3249. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3250. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3251. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3252. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3253. result.x = rx / rw;
  3254. result.y = ry / rw;
  3255. result.z = rz / rw;
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3259. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3260. * @param vector defines the Vector3 to transform
  3261. * @param transformation defines the transformation matrix
  3262. * @returns the new Vector3
  3263. */
  3264. Vector3.TransformNormal = function (vector, transformation) {
  3265. var result = Vector3.Zero();
  3266. Vector3.TransformNormalToRef(vector, transformation, result);
  3267. return result;
  3268. };
  3269. /**
  3270. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3271. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3272. * @param vector defines the Vector3 to transform
  3273. * @param transformation defines the transformation matrix
  3274. * @param result defines the Vector3 where to store the result
  3275. */
  3276. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3277. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3278. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3279. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3280. result.x = x;
  3281. result.y = y;
  3282. result.z = z;
  3283. };
  3284. /**
  3285. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3286. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3287. * @param x define the x coordinate of the source vector
  3288. * @param y define the y coordinate of the source vector
  3289. * @param z define the z coordinate of the source vector
  3290. * @param transformation defines the transformation matrix
  3291. * @param result defines the Vector3 where to store the result
  3292. */
  3293. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3294. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3295. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3296. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3297. };
  3298. /**
  3299. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3300. * @param value1 defines the first control point
  3301. * @param value2 defines the second control point
  3302. * @param value3 defines the third control point
  3303. * @param value4 defines the fourth control point
  3304. * @param amount defines the amount on the spline to use
  3305. * @returns the new Vector3
  3306. */
  3307. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3308. var squared = amount * amount;
  3309. var cubed = amount * squared;
  3310. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3311. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3312. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3313. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3314. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3315. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3316. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3317. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3318. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3319. return new Vector3(x, y, z);
  3320. };
  3321. /**
  3322. * 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"
  3323. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3324. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3325. * @param value defines the current value
  3326. * @param min defines the lower range value
  3327. * @param max defines the upper range value
  3328. * @returns the new Vector3
  3329. */
  3330. Vector3.Clamp = function (value, min, max) {
  3331. var x = value.x;
  3332. x = (x > max.x) ? max.x : x;
  3333. x = (x < min.x) ? min.x : x;
  3334. var y = value.y;
  3335. y = (y > max.y) ? max.y : y;
  3336. y = (y < min.y) ? min.y : y;
  3337. var z = value.z;
  3338. z = (z > max.z) ? max.z : z;
  3339. z = (z < min.z) ? min.z : z;
  3340. return new Vector3(x, y, z);
  3341. };
  3342. /**
  3343. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3344. * @param value1 defines the first control point
  3345. * @param tangent1 defines the first tangent vector
  3346. * @param value2 defines the second control point
  3347. * @param tangent2 defines the second tangent vector
  3348. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3349. * @returns the new Vector3
  3350. */
  3351. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3352. var squared = amount * amount;
  3353. var cubed = amount * squared;
  3354. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3355. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3356. var part3 = (cubed - (2.0 * squared)) + amount;
  3357. var part4 = cubed - squared;
  3358. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3359. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3360. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3361. return new Vector3(x, y, z);
  3362. };
  3363. /**
  3364. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3365. * @param start defines the start value
  3366. * @param end defines the end value
  3367. * @param amount max defines amount between both (between 0 and 1)
  3368. * @returns the new Vector3
  3369. */
  3370. Vector3.Lerp = function (start, end, amount) {
  3371. var result = new Vector3(0, 0, 0);
  3372. Vector3.LerpToRef(start, end, amount, result);
  3373. return result;
  3374. };
  3375. /**
  3376. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3377. * @param start defines the start value
  3378. * @param end defines the end value
  3379. * @param amount max defines amount between both (between 0 and 1)
  3380. * @param result defines the Vector3 where to store the result
  3381. */
  3382. Vector3.LerpToRef = function (start, end, amount, result) {
  3383. result.x = start.x + ((end.x - start.x) * amount);
  3384. result.y = start.y + ((end.y - start.y) * amount);
  3385. result.z = start.z + ((end.z - start.z) * amount);
  3386. };
  3387. /**
  3388. * Returns the dot product (float) between the vectors "left" and "right"
  3389. * @param left defines the left operand
  3390. * @param right defines the right operand
  3391. * @returns the dot product
  3392. */
  3393. Vector3.Dot = function (left, right) {
  3394. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3395. };
  3396. /**
  3397. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3398. * The cross product is then orthogonal to both "left" and "right"
  3399. * @param left defines the left operand
  3400. * @param right defines the right operand
  3401. * @returns the cross product
  3402. */
  3403. Vector3.Cross = function (left, right) {
  3404. var result = Vector3.Zero();
  3405. Vector3.CrossToRef(left, right, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the given vector "result" with the cross product of "left" and "right"
  3410. * The cross product is then orthogonal to both "left" and "right"
  3411. * @param left defines the left operand
  3412. * @param right defines the right operand
  3413. * @param result defines the Vector3 where to store the result
  3414. */
  3415. Vector3.CrossToRef = function (left, right, result) {
  3416. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3417. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3418. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3419. result.copyFrom(MathTmp.Vector3[0]);
  3420. };
  3421. /**
  3422. * Returns a new Vector3 as the normalization of the given vector
  3423. * @param vector defines the Vector3 to normalize
  3424. * @returns the new Vector3
  3425. */
  3426. Vector3.Normalize = function (vector) {
  3427. var result = Vector3.Zero();
  3428. Vector3.NormalizeToRef(vector, result);
  3429. return result;
  3430. };
  3431. /**
  3432. * Sets the given vector "result" with the normalization of the given first vector
  3433. * @param vector defines the Vector3 to normalize
  3434. * @param result defines the Vector3 where to store the result
  3435. */
  3436. Vector3.NormalizeToRef = function (vector, result) {
  3437. result.copyFrom(vector);
  3438. result.normalize();
  3439. };
  3440. /**
  3441. * Project a Vector3 onto screen space
  3442. * @param vector defines the Vector3 to project
  3443. * @param world defines the world matrix to use
  3444. * @param transform defines the transform (view x projection) matrix to use
  3445. * @param viewport defines the screen viewport to use
  3446. * @returns the new Vector3
  3447. */
  3448. Vector3.Project = function (vector, world, transform, viewport) {
  3449. var cw = viewport.width;
  3450. var ch = viewport.height;
  3451. var cx = viewport.x;
  3452. var cy = viewport.y;
  3453. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3454. 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);
  3455. var matrix = MathTmp.Matrix[0];
  3456. world.multiplyToRef(transform, matrix);
  3457. matrix.multiplyToRef(viewportMatrix, matrix);
  3458. return Vector3.TransformCoordinates(vector, matrix);
  3459. };
  3460. /**
  3461. * Unproject from screen space to object space
  3462. * @param source defines the screen space Vector3 to use
  3463. * @param viewportWidth defines the current width of the viewport
  3464. * @param viewportHeight defines the current height of the viewport
  3465. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3466. * @param transform defines the transform (view x projection) matrix to use
  3467. * @returns the new Vector3
  3468. */
  3469. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3470. var matrix = MathTmp.Matrix[0];
  3471. world.multiplyToRef(transform, matrix);
  3472. matrix.invert();
  3473. source.x = source.x / viewportWidth * 2 - 1;
  3474. source.y = -(source.y / viewportHeight * 2 - 1);
  3475. var vector = Vector3.TransformCoordinates(source, matrix);
  3476. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3477. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3478. vector = vector.scale(1.0 / num);
  3479. }
  3480. return vector;
  3481. };
  3482. /**
  3483. * Unproject from screen space to object space
  3484. * @param source defines the screen space Vector3 to use
  3485. * @param viewportWidth defines the current width of the viewport
  3486. * @param viewportHeight defines the current height of the viewport
  3487. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3488. * @param view defines the view matrix to use
  3489. * @param projection defines the projection matrix to use
  3490. * @returns the new Vector3
  3491. */
  3492. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3493. var result = Vector3.Zero();
  3494. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3495. return result;
  3496. };
  3497. /**
  3498. * Unproject from screen space to object space
  3499. * @param source defines the screen space Vector3 to use
  3500. * @param viewportWidth defines the current width of the viewport
  3501. * @param viewportHeight defines the current height of the viewport
  3502. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3503. * @param view defines the view matrix to use
  3504. * @param projection defines the projection matrix to use
  3505. * @param result defines the Vector3 where to store the result
  3506. */
  3507. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3508. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3509. };
  3510. /**
  3511. * Unproject from screen space to object space
  3512. * @param sourceX defines the screen space x coordinate to use
  3513. * @param sourceY defines the screen space y coordinate to use
  3514. * @param sourceZ defines the screen space z coordinate to use
  3515. * @param viewportWidth defines the current width of the viewport
  3516. * @param viewportHeight defines the current height of the viewport
  3517. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3518. * @param view defines the view matrix to use
  3519. * @param projection defines the projection matrix to use
  3520. * @param result defines the Vector3 where to store the result
  3521. */
  3522. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3523. var matrix = MathTmp.Matrix[0];
  3524. world.multiplyToRef(view, matrix);
  3525. matrix.multiplyToRef(projection, matrix);
  3526. matrix.invert();
  3527. var screenSource = MathTmp.Vector3[0];
  3528. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3529. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3530. screenSource.z = 2 * sourceZ - 1.0;
  3531. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3532. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3533. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3534. result.scaleInPlace(1.0 / num);
  3535. }
  3536. };
  3537. /**
  3538. * Gets the minimal coordinate values between two Vector3
  3539. * @param left defines the first operand
  3540. * @param right defines the second operand
  3541. * @returns the new Vector3
  3542. */
  3543. Vector3.Minimize = function (left, right) {
  3544. var min = left.clone();
  3545. min.minimizeInPlace(right);
  3546. return min;
  3547. };
  3548. /**
  3549. * Gets the maximal coordinate values between two Vector3
  3550. * @param left defines the first operand
  3551. * @param right defines the second operand
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Maximize = function (left, right) {
  3555. var max = left.clone();
  3556. max.maximizeInPlace(right);
  3557. return max;
  3558. };
  3559. /**
  3560. * Returns the distance between the vectors "value1" and "value2"
  3561. * @param value1 defines the first operand
  3562. * @param value2 defines the second operand
  3563. * @returns the distance
  3564. */
  3565. Vector3.Distance = function (value1, value2) {
  3566. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3567. };
  3568. /**
  3569. * Returns the squared distance between the vectors "value1" and "value2"
  3570. * @param value1 defines the first operand
  3571. * @param value2 defines the second operand
  3572. * @returns the squared distance
  3573. */
  3574. Vector3.DistanceSquared = function (value1, value2) {
  3575. var x = value1.x - value2.x;
  3576. var y = value1.y - value2.y;
  3577. var z = value1.z - value2.z;
  3578. return (x * x) + (y * y) + (z * z);
  3579. };
  3580. /**
  3581. * Returns a new Vector3 located at the center between "value1" and "value2"
  3582. * @param value1 defines the first operand
  3583. * @param value2 defines the second operand
  3584. * @returns the new Vector3
  3585. */
  3586. Vector3.Center = function (value1, value2) {
  3587. var center = value1.add(value2);
  3588. center.scaleInPlace(0.5);
  3589. return center;
  3590. };
  3591. /**
  3592. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3593. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3594. * to something in order to rotate it from its local system to the given target system
  3595. * Note: axis1, axis2 and axis3 are normalized during this operation
  3596. * @param axis1 defines the first axis
  3597. * @param axis2 defines the second axis
  3598. * @param axis3 defines the third axis
  3599. * @returns a new Vector3
  3600. */
  3601. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3602. var rotation = Vector3.Zero();
  3603. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3604. return rotation;
  3605. };
  3606. /**
  3607. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3608. * @param axis1 defines the first axis
  3609. * @param axis2 defines the second axis
  3610. * @param axis3 defines the third axis
  3611. * @param ref defines the Vector3 where to store the result
  3612. */
  3613. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3614. var quat = MathTmp.Quaternion[0];
  3615. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3616. quat.toEulerAnglesToRef(ref);
  3617. };
  3618. return Vector3;
  3619. }());
  3620. BABYLON.Vector3 = Vector3;
  3621. //Vector4 class created for EulerAngle class conversion to Quaternion
  3622. var Vector4 = /** @class */ (function () {
  3623. /**
  3624. * Creates a Vector4 object from the given floats.
  3625. */
  3626. function Vector4(x, y, z, w) {
  3627. this.x = x;
  3628. this.y = y;
  3629. this.z = z;
  3630. this.w = w;
  3631. }
  3632. /**
  3633. * Returns the string with the Vector4 coordinates.
  3634. */
  3635. Vector4.prototype.toString = function () {
  3636. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3637. };
  3638. /**
  3639. * Returns the string "Vector4".
  3640. */
  3641. Vector4.prototype.getClassName = function () {
  3642. return "Vector4";
  3643. };
  3644. /**
  3645. * Returns the Vector4 hash code.
  3646. */
  3647. Vector4.prototype.getHashCode = function () {
  3648. var hash = this.x || 0;
  3649. hash = (hash * 397) ^ (this.y || 0);
  3650. hash = (hash * 397) ^ (this.z || 0);
  3651. hash = (hash * 397) ^ (this.w || 0);
  3652. return hash;
  3653. };
  3654. // Operators
  3655. /**
  3656. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3657. */
  3658. Vector4.prototype.asArray = function () {
  3659. var result = new Array();
  3660. this.toArray(result, 0);
  3661. return result;
  3662. };
  3663. /**
  3664. * Populates the given array from the given index with the Vector4 coordinates.
  3665. * Returns the Vector4.
  3666. */
  3667. Vector4.prototype.toArray = function (array, index) {
  3668. if (index === undefined) {
  3669. index = 0;
  3670. }
  3671. array[index] = this.x;
  3672. array[index + 1] = this.y;
  3673. array[index + 2] = this.z;
  3674. array[index + 3] = this.w;
  3675. return this;
  3676. };
  3677. /**
  3678. * Adds the given vector to the current Vector4.
  3679. * Returns the updated Vector4.
  3680. */
  3681. Vector4.prototype.addInPlace = function (otherVector) {
  3682. this.x += otherVector.x;
  3683. this.y += otherVector.y;
  3684. this.z += otherVector.z;
  3685. this.w += otherVector.w;
  3686. return this;
  3687. };
  3688. /**
  3689. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3690. */
  3691. Vector4.prototype.add = function (otherVector) {
  3692. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3693. };
  3694. /**
  3695. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3696. * Returns the current Vector4.
  3697. */
  3698. Vector4.prototype.addToRef = function (otherVector, result) {
  3699. result.x = this.x + otherVector.x;
  3700. result.y = this.y + otherVector.y;
  3701. result.z = this.z + otherVector.z;
  3702. result.w = this.w + otherVector.w;
  3703. return this;
  3704. };
  3705. /**
  3706. * Subtract in place the given vector from the current Vector4.
  3707. * Returns the updated Vector4.
  3708. */
  3709. Vector4.prototype.subtractInPlace = function (otherVector) {
  3710. this.x -= otherVector.x;
  3711. this.y -= otherVector.y;
  3712. this.z -= otherVector.z;
  3713. this.w -= otherVector.w;
  3714. return this;
  3715. };
  3716. /**
  3717. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3718. */
  3719. Vector4.prototype.subtract = function (otherVector) {
  3720. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3721. };
  3722. /**
  3723. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3724. * Returns the current Vector4.
  3725. */
  3726. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3727. result.x = this.x - otherVector.x;
  3728. result.y = this.y - otherVector.y;
  3729. result.z = this.z - otherVector.z;
  3730. result.w = this.w - otherVector.w;
  3731. return this;
  3732. };
  3733. /**
  3734. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3735. */
  3736. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3737. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3738. };
  3739. /**
  3740. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3741. * Returns the current Vector4.
  3742. */
  3743. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3744. result.x = this.x - x;
  3745. result.y = this.y - y;
  3746. result.z = this.z - z;
  3747. result.w = this.w - w;
  3748. return this;
  3749. };
  3750. /**
  3751. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3752. */
  3753. Vector4.prototype.negate = function () {
  3754. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3755. };
  3756. /**
  3757. * Multiplies the current Vector4 coordinates by scale (float).
  3758. * Returns the updated Vector4.
  3759. */
  3760. Vector4.prototype.scaleInPlace = function (scale) {
  3761. this.x *= scale;
  3762. this.y *= scale;
  3763. this.z *= scale;
  3764. this.w *= scale;
  3765. return this;
  3766. };
  3767. /**
  3768. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3769. */
  3770. Vector4.prototype.scale = function (scale) {
  3771. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3772. };
  3773. /**
  3774. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3775. * Returns the current Vector4.
  3776. */
  3777. Vector4.prototype.scaleToRef = function (scale, result) {
  3778. result.x = this.x * scale;
  3779. result.y = this.y * scale;
  3780. result.z = this.z * scale;
  3781. result.w = this.w * scale;
  3782. return this;
  3783. };
  3784. /**
  3785. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3786. * @param scale defines the scale factor
  3787. * @param result defines the Vector4 object where to store the result
  3788. * @returns the unmodified current Vector4
  3789. */
  3790. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3791. result.x += this.x * scale;
  3792. result.y += this.y * scale;
  3793. result.z += this.z * scale;
  3794. result.w += this.w * scale;
  3795. return this;
  3796. };
  3797. /**
  3798. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3799. */
  3800. Vector4.prototype.equals = function (otherVector) {
  3801. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3802. };
  3803. /**
  3804. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3805. */
  3806. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3807. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3808. return otherVector
  3809. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3810. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3811. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3812. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3813. };
  3814. /**
  3815. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3816. */
  3817. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3818. return this.x === x && this.y === y && this.z === z && this.w === w;
  3819. };
  3820. /**
  3821. * Multiplies in place the current Vector4 by the given one.
  3822. * Returns the updated Vector4.
  3823. */
  3824. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3825. this.x *= otherVector.x;
  3826. this.y *= otherVector.y;
  3827. this.z *= otherVector.z;
  3828. this.w *= otherVector.w;
  3829. return this;
  3830. };
  3831. /**
  3832. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3833. */
  3834. Vector4.prototype.multiply = function (otherVector) {
  3835. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3836. };
  3837. /**
  3838. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3839. * Returns the current Vector4.
  3840. */
  3841. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3842. result.x = this.x * otherVector.x;
  3843. result.y = this.y * otherVector.y;
  3844. result.z = this.z * otherVector.z;
  3845. result.w = this.w * otherVector.w;
  3846. return this;
  3847. };
  3848. /**
  3849. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3850. */
  3851. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3852. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3853. };
  3854. /**
  3855. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3856. */
  3857. Vector4.prototype.divide = function (otherVector) {
  3858. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3859. };
  3860. /**
  3861. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3862. * Returns the current Vector4.
  3863. */
  3864. Vector4.prototype.divideToRef = function (otherVector, result) {
  3865. result.x = this.x / otherVector.x;
  3866. result.y = this.y / otherVector.y;
  3867. result.z = this.z / otherVector.z;
  3868. result.w = this.w / otherVector.w;
  3869. return this;
  3870. };
  3871. /**
  3872. * Divides the current Vector3 coordinates by the given ones.
  3873. * @returns the updated Vector3.
  3874. */
  3875. Vector4.prototype.divideInPlace = function (otherVector) {
  3876. return this.divideToRef(otherVector, this);
  3877. };
  3878. /**
  3879. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3880. * @param other defines the second operand
  3881. * @returns the current updated Vector4
  3882. */
  3883. Vector4.prototype.minimizeInPlace = function (other) {
  3884. if (other.x < this.x)
  3885. this.x = other.x;
  3886. if (other.y < this.y)
  3887. this.y = other.y;
  3888. if (other.z < this.z)
  3889. this.z = other.z;
  3890. if (other.w < this.w)
  3891. this.w = other.w;
  3892. return this;
  3893. };
  3894. /**
  3895. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  3896. * @param other defines the second operand
  3897. * @returns the current updated Vector4
  3898. */
  3899. Vector4.prototype.maximizeInPlace = function (other) {
  3900. if (other.x > this.x)
  3901. this.x = other.x;
  3902. if (other.y > this.y)
  3903. this.y = other.y;
  3904. if (other.z > this.z)
  3905. this.z = other.z;
  3906. if (other.w > this.w)
  3907. this.w = other.w;
  3908. return this;
  3909. };
  3910. // Properties
  3911. /**
  3912. * Returns the Vector4 length (float).
  3913. */
  3914. Vector4.prototype.length = function () {
  3915. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3916. };
  3917. /**
  3918. * Returns the Vector4 squared length (float).
  3919. */
  3920. Vector4.prototype.lengthSquared = function () {
  3921. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3922. };
  3923. // Methods
  3924. /**
  3925. * Normalizes in place the Vector4.
  3926. * Returns the updated Vector4.
  3927. */
  3928. Vector4.prototype.normalize = function () {
  3929. var len = this.length();
  3930. if (len === 0)
  3931. return this;
  3932. var num = 1.0 / len;
  3933. this.x *= num;
  3934. this.y *= num;
  3935. this.z *= num;
  3936. this.w *= num;
  3937. return this;
  3938. };
  3939. /**
  3940. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3941. */
  3942. Vector4.prototype.toVector3 = function () {
  3943. return new Vector3(this.x, this.y, this.z);
  3944. };
  3945. /**
  3946. * Returns a new Vector4 copied from the current one.
  3947. */
  3948. Vector4.prototype.clone = function () {
  3949. return new Vector4(this.x, this.y, this.z, this.w);
  3950. };
  3951. /**
  3952. * Updates the current Vector4 with the given one coordinates.
  3953. * Returns the updated Vector4.
  3954. */
  3955. Vector4.prototype.copyFrom = function (source) {
  3956. this.x = source.x;
  3957. this.y = source.y;
  3958. this.z = source.z;
  3959. this.w = source.w;
  3960. return this;
  3961. };
  3962. /**
  3963. * Updates the current Vector4 coordinates with the given floats.
  3964. * Returns the updated Vector4.
  3965. */
  3966. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3967. this.x = x;
  3968. this.y = y;
  3969. this.z = z;
  3970. this.w = w;
  3971. return this;
  3972. };
  3973. /**
  3974. * Updates the current Vector4 coordinates with the given floats.
  3975. * Returns the updated Vector4.
  3976. */
  3977. Vector4.prototype.set = function (x, y, z, w) {
  3978. return this.copyFromFloats(x, y, z, w);
  3979. };
  3980. // Statics
  3981. /**
  3982. * Returns a new Vector4 set from the starting index of the given array.
  3983. */
  3984. Vector4.FromArray = function (array, offset) {
  3985. if (!offset) {
  3986. offset = 0;
  3987. }
  3988. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3989. };
  3990. /**
  3991. * Updates the given vector "result" from the starting index of the given array.
  3992. */
  3993. Vector4.FromArrayToRef = function (array, offset, result) {
  3994. result.x = array[offset];
  3995. result.y = array[offset + 1];
  3996. result.z = array[offset + 2];
  3997. result.w = array[offset + 3];
  3998. };
  3999. /**
  4000. * Updates the given vector "result" from the starting index of the given Float32Array.
  4001. */
  4002. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4003. Vector4.FromArrayToRef(array, offset, result);
  4004. };
  4005. /**
  4006. * Updates the given vector "result" coordinates from the given floats.
  4007. */
  4008. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4009. result.x = x;
  4010. result.y = y;
  4011. result.z = z;
  4012. result.w = w;
  4013. };
  4014. /**
  4015. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4016. */
  4017. Vector4.Zero = function () {
  4018. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4019. };
  4020. /**
  4021. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4022. */
  4023. Vector4.One = function () {
  4024. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4025. };
  4026. /**
  4027. * Returns a new normalized Vector4 from the given one.
  4028. */
  4029. Vector4.Normalize = function (vector) {
  4030. var result = Vector4.Zero();
  4031. Vector4.NormalizeToRef(vector, result);
  4032. return result;
  4033. };
  4034. /**
  4035. * Updates the given vector "result" from the normalization of the given one.
  4036. */
  4037. Vector4.NormalizeToRef = function (vector, result) {
  4038. result.copyFrom(vector);
  4039. result.normalize();
  4040. };
  4041. Vector4.Minimize = function (left, right) {
  4042. var min = left.clone();
  4043. min.minimizeInPlace(right);
  4044. return min;
  4045. };
  4046. Vector4.Maximize = function (left, right) {
  4047. var max = left.clone();
  4048. max.maximizeInPlace(right);
  4049. return max;
  4050. };
  4051. /**
  4052. * Returns the distance (float) between the vectors "value1" and "value2".
  4053. */
  4054. Vector4.Distance = function (value1, value2) {
  4055. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4056. };
  4057. /**
  4058. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4059. */
  4060. Vector4.DistanceSquared = function (value1, value2) {
  4061. var x = value1.x - value2.x;
  4062. var y = value1.y - value2.y;
  4063. var z = value1.z - value2.z;
  4064. var w = value1.w - value2.w;
  4065. return (x * x) + (y * y) + (z * z) + (w * w);
  4066. };
  4067. /**
  4068. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4069. */
  4070. Vector4.Center = function (value1, value2) {
  4071. var center = value1.add(value2);
  4072. center.scaleInPlace(0.5);
  4073. return center;
  4074. };
  4075. /**
  4076. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4077. * This methods computes transformed normalized direction vectors only.
  4078. */
  4079. Vector4.TransformNormal = function (vector, transformation) {
  4080. var result = Vector4.Zero();
  4081. Vector4.TransformNormalToRef(vector, transformation, result);
  4082. return result;
  4083. };
  4084. /**
  4085. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4086. * This methods computes transformed normalized direction vectors only.
  4087. */
  4088. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4089. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4090. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4091. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4092. result.x = x;
  4093. result.y = y;
  4094. result.z = z;
  4095. result.w = vector.w;
  4096. };
  4097. /**
  4098. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4099. * This methods computes transformed normalized direction vectors only.
  4100. */
  4101. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4102. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4103. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4104. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4105. result.w = w;
  4106. };
  4107. return Vector4;
  4108. }());
  4109. BABYLON.Vector4 = Vector4;
  4110. var Size = /** @class */ (function () {
  4111. /**
  4112. * Creates a Size object from the given width and height (floats).
  4113. */
  4114. function Size(width, height) {
  4115. this.width = width;
  4116. this.height = height;
  4117. }
  4118. // Returns a string with the Size width and height.
  4119. Size.prototype.toString = function () {
  4120. return "{W: " + this.width + ", H: " + this.height + "}";
  4121. };
  4122. /**
  4123. * Returns the string "Size"
  4124. */
  4125. Size.prototype.getClassName = function () {
  4126. return "Size";
  4127. };
  4128. /**
  4129. * Returns the Size hash code.
  4130. */
  4131. Size.prototype.getHashCode = function () {
  4132. var hash = this.width || 0;
  4133. hash = (hash * 397) ^ (this.height || 0);
  4134. return hash;
  4135. };
  4136. /**
  4137. * Updates the current size from the given one.
  4138. * Returns the updated Size.
  4139. */
  4140. Size.prototype.copyFrom = function (src) {
  4141. this.width = src.width;
  4142. this.height = src.height;
  4143. };
  4144. /**
  4145. * Updates in place the current Size from the given floats.
  4146. * Returns the updated Size.
  4147. */
  4148. Size.prototype.copyFromFloats = function (width, height) {
  4149. this.width = width;
  4150. this.height = height;
  4151. return this;
  4152. };
  4153. /**
  4154. * Updates in place the current Size from the given floats.
  4155. * Returns the updated Size.
  4156. */
  4157. Size.prototype.set = function (width, height) {
  4158. return this.copyFromFloats(width, height);
  4159. };
  4160. /**
  4161. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4162. */
  4163. Size.prototype.multiplyByFloats = function (w, h) {
  4164. return new Size(this.width * w, this.height * h);
  4165. };
  4166. /**
  4167. * Returns a new Size copied from the given one.
  4168. */
  4169. Size.prototype.clone = function () {
  4170. return new Size(this.width, this.height);
  4171. };
  4172. /**
  4173. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4174. */
  4175. Size.prototype.equals = function (other) {
  4176. if (!other) {
  4177. return false;
  4178. }
  4179. return (this.width === other.width) && (this.height === other.height);
  4180. };
  4181. Object.defineProperty(Size.prototype, "surface", {
  4182. /**
  4183. * Returns the surface of the Size : width * height (float).
  4184. */
  4185. get: function () {
  4186. return this.width * this.height;
  4187. },
  4188. enumerable: true,
  4189. configurable: true
  4190. });
  4191. /**
  4192. * Returns a new Size set to (0.0, 0.0)
  4193. */
  4194. Size.Zero = function () {
  4195. return new Size(0.0, 0.0);
  4196. };
  4197. /**
  4198. * Returns a new Size set as the addition result of the current Size and the given one.
  4199. */
  4200. Size.prototype.add = function (otherSize) {
  4201. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4202. return r;
  4203. };
  4204. /**
  4205. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4206. */
  4207. Size.prototype.subtract = function (otherSize) {
  4208. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4209. return r;
  4210. };
  4211. /**
  4212. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4213. */
  4214. Size.Lerp = function (start, end, amount) {
  4215. var w = start.width + ((end.width - start.width) * amount);
  4216. var h = start.height + ((end.height - start.height) * amount);
  4217. return new Size(w, h);
  4218. };
  4219. return Size;
  4220. }());
  4221. BABYLON.Size = Size;
  4222. /**
  4223. * Class used to store quaternion data
  4224. * @see https://en.wikipedia.org/wiki/Quaternion
  4225. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4226. */
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the given floats
  4230. * @param x defines the first component (0 by default)
  4231. * @param y defines the second component (0 by default)
  4232. * @param z defines the third component (0 by default)
  4233. * @param w defines the fourth component (1.0 by default)
  4234. */
  4235. function Quaternion(
  4236. /** defines the first component (0 by default) */
  4237. x,
  4238. /** defines the second component (0 by default) */
  4239. y,
  4240. /** defines the third component (0 by default) */
  4241. z,
  4242. /** defines the fourth component (1.0 by default) */
  4243. w) {
  4244. if (x === void 0) { x = 0.0; }
  4245. if (y === void 0) { y = 0.0; }
  4246. if (z === void 0) { z = 0.0; }
  4247. if (w === void 0) { w = 1.0; }
  4248. this.x = x;
  4249. this.y = y;
  4250. this.z = z;
  4251. this.w = w;
  4252. }
  4253. /**
  4254. * Gets a string representation for the current quaternion
  4255. * @returns a string with the Quaternion coordinates
  4256. */
  4257. Quaternion.prototype.toString = function () {
  4258. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4259. };
  4260. /**
  4261. * Gets the class name of the quaternion
  4262. * @returns the string "Quaternion"
  4263. */
  4264. Quaternion.prototype.getClassName = function () {
  4265. return "Quaternion";
  4266. };
  4267. /**
  4268. * Gets a hash code for this quaternion
  4269. * @returns the quaternion hash code
  4270. */
  4271. Quaternion.prototype.getHashCode = function () {
  4272. var hash = this.x || 0;
  4273. hash = (hash * 397) ^ (this.y || 0);
  4274. hash = (hash * 397) ^ (this.z || 0);
  4275. hash = (hash * 397) ^ (this.w || 0);
  4276. return hash;
  4277. };
  4278. /**
  4279. * Copy the quaternion to an array
  4280. * @returns a new array populated with 4 elements from the quaternion coordinates
  4281. */
  4282. Quaternion.prototype.asArray = function () {
  4283. return [this.x, this.y, this.z, this.w];
  4284. };
  4285. /**
  4286. * Check if two quaternions are equals
  4287. * @param otherQuaternion defines the second operand
  4288. * @return true if the current quaternion and the given one coordinates are strictly equals
  4289. */
  4290. Quaternion.prototype.equals = function (otherQuaternion) {
  4291. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4292. };
  4293. /**
  4294. * Clone the current quaternion
  4295. * @returns a new quaternion copied from the current one
  4296. */
  4297. Quaternion.prototype.clone = function () {
  4298. return new Quaternion(this.x, this.y, this.z, this.w);
  4299. };
  4300. /**
  4301. * Copy a quaternion to the current one
  4302. * @param other defines the other quaternion
  4303. * @returns the updated current quaternion
  4304. */
  4305. Quaternion.prototype.copyFrom = function (other) {
  4306. this.x = other.x;
  4307. this.y = other.y;
  4308. this.z = other.z;
  4309. this.w = other.w;
  4310. return this;
  4311. };
  4312. /**
  4313. * Updates the current quaternion with the given float coordinates
  4314. * @param x defines the x coordinate
  4315. * @param y defines the y coordinate
  4316. * @param z defines the z coordinate
  4317. * @param w defines the w coordinate
  4318. * @returns the updated current quaternion
  4319. */
  4320. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4321. this.x = x;
  4322. this.y = y;
  4323. this.z = z;
  4324. this.w = w;
  4325. return this;
  4326. };
  4327. /**
  4328. * Updates the current quaternion from the given float coordinates
  4329. * @param x defines the x coordinate
  4330. * @param y defines the y coordinate
  4331. * @param z defines the z coordinate
  4332. * @param w defines the w coordinate
  4333. * @returns the updated current quaternion
  4334. */
  4335. Quaternion.prototype.set = function (x, y, z, w) {
  4336. return this.copyFromFloats(x, y, z, w);
  4337. };
  4338. /**
  4339. * Adds two quaternions
  4340. * @param other defines the second operand
  4341. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4342. */
  4343. Quaternion.prototype.add = function (other) {
  4344. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4345. };
  4346. /**
  4347. * Add a quaternion to the current one
  4348. * @param other defines the quaternion to add
  4349. * @returns the current quaternion
  4350. */
  4351. Quaternion.prototype.addInPlace = function (other) {
  4352. this.x += other.x;
  4353. this.y += other.y;
  4354. this.z += other.z;
  4355. this.w += other.w;
  4356. return this;
  4357. };
  4358. /**
  4359. * Subtract two quaternions
  4360. * @param other defines the second operand
  4361. * @returns a new quaternion as the subtraction result of the given one from the current one
  4362. */
  4363. Quaternion.prototype.subtract = function (other) {
  4364. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4365. };
  4366. /**
  4367. * Multiplies the current quaternion by a scale factor
  4368. * @param value defines the scale factor
  4369. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4370. */
  4371. Quaternion.prototype.scale = function (value) {
  4372. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4373. };
  4374. /**
  4375. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4376. * @param scale defines the scale factor
  4377. * @param result defines the Quaternion object where to store the result
  4378. * @returns the unmodified current quaternion
  4379. */
  4380. Quaternion.prototype.scaleToRef = function (scale, result) {
  4381. result.x = this.x * scale;
  4382. result.y = this.y * scale;
  4383. result.z = this.z * scale;
  4384. result.w = this.w * scale;
  4385. return this;
  4386. };
  4387. /**
  4388. * Multiplies in place the current quaternion by a scale factor
  4389. * @param value defines the scale factor
  4390. * @returns the current modified quaternion
  4391. */
  4392. Quaternion.prototype.scaleInPlace = function (value) {
  4393. this.x *= value;
  4394. this.y *= value;
  4395. this.z *= value;
  4396. this.w *= value;
  4397. return this;
  4398. };
  4399. /**
  4400. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4401. * @param scale defines the scale factor
  4402. * @param result defines the Quaternion object where to store the result
  4403. * @returns the unmodified current quaternion
  4404. */
  4405. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4406. result.x += this.x * scale;
  4407. result.y += this.y * scale;
  4408. result.z += this.z * scale;
  4409. result.w += this.w * scale;
  4410. return this;
  4411. };
  4412. /**
  4413. * Multiplies two quaternions
  4414. * @param q1 defines the second operand
  4415. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4416. */
  4417. Quaternion.prototype.multiply = function (q1) {
  4418. var result = new Quaternion(0, 0, 0, 1.0);
  4419. this.multiplyToRef(q1, result);
  4420. return result;
  4421. };
  4422. /**
  4423. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4424. * @param q1 defines the second operand
  4425. * @param result defines the target quaternion
  4426. * @returns the current quaternion
  4427. */
  4428. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4429. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4430. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4431. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4432. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4433. result.copyFromFloats(x, y, z, w);
  4434. return this;
  4435. };
  4436. /**
  4437. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4438. * @param q1 defines the second operand
  4439. * @returns the currentupdated quaternion
  4440. */
  4441. Quaternion.prototype.multiplyInPlace = function (q1) {
  4442. this.multiplyToRef(q1, this);
  4443. return this;
  4444. };
  4445. /**
  4446. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4447. * @param ref defines the target quaternion
  4448. * @returns the current quaternion
  4449. */
  4450. Quaternion.prototype.conjugateToRef = function (ref) {
  4451. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4452. return this;
  4453. };
  4454. /**
  4455. * Conjugates in place (1-q) the current quaternion
  4456. * @returns the current updated quaternion
  4457. */
  4458. Quaternion.prototype.conjugateInPlace = function () {
  4459. this.x *= -1;
  4460. this.y *= -1;
  4461. this.z *= -1;
  4462. return this;
  4463. };
  4464. /**
  4465. * Conjugates in place (1-q) the current quaternion
  4466. * @returns a new quaternion
  4467. */
  4468. Quaternion.prototype.conjugate = function () {
  4469. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4470. return result;
  4471. };
  4472. /**
  4473. * Gets length of current quaternion
  4474. * @returns the quaternion length (float)
  4475. */
  4476. Quaternion.prototype.length = function () {
  4477. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4478. };
  4479. /**
  4480. * Normalize in place the current quaternion
  4481. * @returns the current updated quaternion
  4482. */
  4483. Quaternion.prototype.normalize = function () {
  4484. var length = 1.0 / this.length();
  4485. this.x *= length;
  4486. this.y *= length;
  4487. this.z *= length;
  4488. this.w *= length;
  4489. return this;
  4490. };
  4491. /**
  4492. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4493. * @param order is a reserved parameter and is ignore for now
  4494. * @returns a new Vector3 containing the Euler angles
  4495. */
  4496. Quaternion.prototype.toEulerAngles = function (order) {
  4497. if (order === void 0) { order = "YZX"; }
  4498. var result = Vector3.Zero();
  4499. this.toEulerAnglesToRef(result, order);
  4500. return result;
  4501. };
  4502. /**
  4503. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4504. * @param result defines the vector which will be filled with the Euler angles
  4505. * @param order is a reserved parameter and is ignore for now
  4506. * @returns the current unchanged quaternion
  4507. */
  4508. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4509. if (order === void 0) { order = "YZX"; }
  4510. var qz = this.z;
  4511. var qx = this.x;
  4512. var qy = this.y;
  4513. var qw = this.w;
  4514. var sqw = qw * qw;
  4515. var sqz = qz * qz;
  4516. var sqx = qx * qx;
  4517. var sqy = qy * qy;
  4518. var zAxisY = qy * qz - qx * qw;
  4519. var limit = .4999999;
  4520. if (zAxisY < -limit) {
  4521. result.y = 2 * Math.atan2(qy, qw);
  4522. result.x = Math.PI / 2;
  4523. result.z = 0;
  4524. }
  4525. else if (zAxisY > limit) {
  4526. result.y = 2 * Math.atan2(qy, qw);
  4527. result.x = -Math.PI / 2;
  4528. result.z = 0;
  4529. }
  4530. else {
  4531. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4532. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4533. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4534. }
  4535. return this;
  4536. };
  4537. /**
  4538. * Updates the given rotation matrix with the current quaternion values
  4539. * @param result defines the target matrix
  4540. * @returns the current unchanged quaternion
  4541. */
  4542. Quaternion.prototype.toRotationMatrix = function (result) {
  4543. var xx = this.x * this.x;
  4544. var yy = this.y * this.y;
  4545. var zz = this.z * this.z;
  4546. var xy = this.x * this.y;
  4547. var zw = this.z * this.w;
  4548. var zx = this.z * this.x;
  4549. var yw = this.y * this.w;
  4550. var yz = this.y * this.z;
  4551. var xw = this.x * this.w;
  4552. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4553. result.m[1] = 2.0 * (xy + zw);
  4554. result.m[2] = 2.0 * (zx - yw);
  4555. result.m[3] = 0;
  4556. result.m[4] = 2.0 * (xy - zw);
  4557. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4558. result.m[6] = 2.0 * (yz + xw);
  4559. result.m[7] = 0;
  4560. result.m[8] = 2.0 * (zx + yw);
  4561. result.m[9] = 2.0 * (yz - xw);
  4562. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4563. result.m[11] = 0;
  4564. result.m[12] = 0;
  4565. result.m[13] = 0;
  4566. result.m[14] = 0;
  4567. result.m[15] = 1.0;
  4568. result._markAsUpdated();
  4569. return this;
  4570. };
  4571. /**
  4572. * Updates the current quaternion from the given rotation matrix values
  4573. * @param matrix defines the source matrix
  4574. * @returns the current updated quaternion
  4575. */
  4576. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4577. Quaternion.FromRotationMatrixToRef(matrix, this);
  4578. return this;
  4579. };
  4580. // Statics
  4581. /**
  4582. * Creates a new quaternion from a rotation matrix
  4583. * @param matrix defines the source matrix
  4584. * @returns a new quaternion created from the given rotation matrix values
  4585. */
  4586. Quaternion.FromRotationMatrix = function (matrix) {
  4587. var result = new Quaternion();
  4588. Quaternion.FromRotationMatrixToRef(matrix, result);
  4589. return result;
  4590. };
  4591. /**
  4592. * Updates the given quaternion with the given rotation matrix values
  4593. * @param matrix defines the source matrix
  4594. * @param result defines the target quaternion
  4595. */
  4596. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4597. var data = matrix.m;
  4598. var m11 = data[0], m12 = data[4], m13 = data[8];
  4599. var m21 = data[1], m22 = data[5], m23 = data[9];
  4600. var m31 = data[2], m32 = data[6], m33 = data[10];
  4601. var trace = m11 + m22 + m33;
  4602. var s;
  4603. if (trace > 0) {
  4604. s = 0.5 / Math.sqrt(trace + 1.0);
  4605. result.w = 0.25 / s;
  4606. result.x = (m32 - m23) * s;
  4607. result.y = (m13 - m31) * s;
  4608. result.z = (m21 - m12) * s;
  4609. }
  4610. else if (m11 > m22 && m11 > m33) {
  4611. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4612. result.w = (m32 - m23) / s;
  4613. result.x = 0.25 * s;
  4614. result.y = (m12 + m21) / s;
  4615. result.z = (m13 + m31) / s;
  4616. }
  4617. else if (m22 > m33) {
  4618. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4619. result.w = (m13 - m31) / s;
  4620. result.x = (m12 + m21) / s;
  4621. result.y = 0.25 * s;
  4622. result.z = (m23 + m32) / s;
  4623. }
  4624. else {
  4625. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4626. result.w = (m21 - m12) / s;
  4627. result.x = (m13 + m31) / s;
  4628. result.y = (m23 + m32) / s;
  4629. result.z = 0.25 * s;
  4630. }
  4631. };
  4632. /**
  4633. * Creates an empty quaternion
  4634. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4635. */
  4636. Quaternion.Zero = function () {
  4637. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4638. };
  4639. /**
  4640. * Inverse a given quaternion
  4641. * @param q defines the source quaternion
  4642. * @returns a new quaternion as the inverted current quaternion
  4643. */
  4644. Quaternion.Inverse = function (q) {
  4645. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4646. };
  4647. /**
  4648. * Creates an identity quaternion
  4649. * @returns the identity quaternion
  4650. */
  4651. Quaternion.Identity = function () {
  4652. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4653. };
  4654. /**
  4655. * Gets a boolean indicating if the given quaternion is identity
  4656. * @param quaternion defines the quaternion to check
  4657. * @returns true if the quaternion is identity
  4658. */
  4659. Quaternion.IsIdentity = function (quaternion) {
  4660. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4661. };
  4662. /**
  4663. * Creates a quaternion from a rotation around an axis
  4664. * @param axis defines the axis to use
  4665. * @param angle defines the angle to use
  4666. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4667. */
  4668. Quaternion.RotationAxis = function (axis, angle) {
  4669. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4670. };
  4671. /**
  4672. * Creates a rotation around an axis and stores it into the given quaternion
  4673. * @param axis defines the axis to use
  4674. * @param angle defines the angle to use
  4675. * @param result defines the target quaternion
  4676. * @returns the target quaternion
  4677. */
  4678. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4679. var sin = Math.sin(angle / 2);
  4680. axis.normalize();
  4681. result.w = Math.cos(angle / 2);
  4682. result.x = axis.x * sin;
  4683. result.y = axis.y * sin;
  4684. result.z = axis.z * sin;
  4685. return result;
  4686. };
  4687. /**
  4688. * Creates a new quaternion from data stored into an array
  4689. * @param array defines the data source
  4690. * @param offset defines the offset in the source array where the data starts
  4691. * @returns a new quaternion
  4692. */
  4693. Quaternion.FromArray = function (array, offset) {
  4694. if (!offset) {
  4695. offset = 0;
  4696. }
  4697. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4698. };
  4699. /**
  4700. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4701. * @param yaw defines the rotation around Y axis
  4702. * @param pitch defines the rotation around X axis
  4703. * @param roll defines the rotation around Z axis
  4704. * @returns the new quaternion
  4705. */
  4706. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4707. var q = new Quaternion();
  4708. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4709. return q;
  4710. };
  4711. /**
  4712. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4713. * @param yaw defines the rotation around Y axis
  4714. * @param pitch defines the rotation around X axis
  4715. * @param roll defines the rotation around Z axis
  4716. * @param result defines the target quaternion
  4717. */
  4718. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4719. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4720. var halfRoll = roll * 0.5;
  4721. var halfPitch = pitch * 0.5;
  4722. var halfYaw = yaw * 0.5;
  4723. var sinRoll = Math.sin(halfRoll);
  4724. var cosRoll = Math.cos(halfRoll);
  4725. var sinPitch = Math.sin(halfPitch);
  4726. var cosPitch = Math.cos(halfPitch);
  4727. var sinYaw = Math.sin(halfYaw);
  4728. var cosYaw = Math.cos(halfYaw);
  4729. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4730. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4731. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4732. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4733. };
  4734. /**
  4735. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4736. * @param alpha defines the rotation around first axis
  4737. * @param beta defines the rotation around second axis
  4738. * @param gamma defines the rotation around third axis
  4739. * @returns the new quaternion
  4740. */
  4741. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4742. var result = new Quaternion();
  4743. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4748. * @param alpha defines the rotation around first axis
  4749. * @param beta defines the rotation around second axis
  4750. * @param gamma defines the rotation around third axis
  4751. * @param result defines the target quaternion
  4752. */
  4753. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4754. // Produces a quaternion from Euler angles in the z-x-z orientation
  4755. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4756. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4757. var halfBeta = beta * 0.5;
  4758. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4759. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4760. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4761. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4762. };
  4763. /**
  4764. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4765. * @param axis1 defines the first axis
  4766. * @param axis2 defines the second axis
  4767. * @param axis3 defines the third axis
  4768. * @returns the new quaternion
  4769. */
  4770. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4771. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4772. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4773. return quat;
  4774. };
  4775. /**
  4776. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4777. * @param axis1 defines the first axis
  4778. * @param axis2 defines the second axis
  4779. * @param axis3 defines the third axis
  4780. * @param ref defines the target quaternion
  4781. */
  4782. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4783. var rotMat = MathTmp.Matrix[0];
  4784. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4785. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4786. };
  4787. /**
  4788. * Interpolates between two quaternions
  4789. * @param left defines first quaternion
  4790. * @param right defines second quaternion
  4791. * @param amount defines the gradient to use
  4792. * @returns the new interpolated quaternion
  4793. */
  4794. Quaternion.Slerp = function (left, right, amount) {
  4795. var result = Quaternion.Identity();
  4796. Quaternion.SlerpToRef(left, right, amount, result);
  4797. return result;
  4798. };
  4799. /**
  4800. * Interpolates between two quaternions and stores it into a target quaternion
  4801. * @param left defines first quaternion
  4802. * @param right defines second quaternion
  4803. * @param amount defines the gradient to use
  4804. * @param result defines the target quaternion
  4805. */
  4806. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4807. var num2;
  4808. var num3;
  4809. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4810. var flag = false;
  4811. if (num4 < 0) {
  4812. flag = true;
  4813. num4 = -num4;
  4814. }
  4815. if (num4 > 0.999999) {
  4816. num3 = 1 - amount;
  4817. num2 = flag ? -amount : amount;
  4818. }
  4819. else {
  4820. var num5 = Math.acos(num4);
  4821. var num6 = (1.0 / Math.sin(num5));
  4822. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4823. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4824. }
  4825. result.x = (num3 * left.x) + (num2 * right.x);
  4826. result.y = (num3 * left.y) + (num2 * right.y);
  4827. result.z = (num3 * left.z) + (num2 * right.z);
  4828. result.w = (num3 * left.w) + (num2 * right.w);
  4829. };
  4830. /**
  4831. * Interpolate between two quaternions using Hermite interpolation
  4832. * @param value1 defines first quaternion
  4833. * @param tangent1 defines the incoming tangent
  4834. * @param value2 defines second quaternion
  4835. * @param tangent2 defines the outgoing tangent
  4836. * @param amount defines the target quaternion
  4837. * @returns the new interpolated quaternion
  4838. */
  4839. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4840. var squared = amount * amount;
  4841. var cubed = amount * squared;
  4842. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4843. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4844. var part3 = (cubed - (2.0 * squared)) + amount;
  4845. var part4 = cubed - squared;
  4846. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4847. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4848. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4849. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4850. return new Quaternion(x, y, z, w);
  4851. };
  4852. return Quaternion;
  4853. }());
  4854. BABYLON.Quaternion = Quaternion;
  4855. /**
  4856. * Class used to store matrix data (4x4)
  4857. */
  4858. var Matrix = /** @class */ (function () {
  4859. /**
  4860. * Creates an empty matrix (filled with zeros)
  4861. */
  4862. function Matrix() {
  4863. this._isIdentity = false;
  4864. this._isIdentityDirty = true;
  4865. /**
  4866. * Gets or sets the internal data of the matrix
  4867. */
  4868. this.m = new Float32Array(16);
  4869. this._markAsUpdated();
  4870. }
  4871. /** @ignore */
  4872. Matrix.prototype._markAsUpdated = function () {
  4873. this.updateFlag = Matrix._updateFlagSeed++;
  4874. this._isIdentityDirty = true;
  4875. };
  4876. // Properties
  4877. /**
  4878. * Check if the current matrix is indentity
  4879. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4880. * @returns true is the matrix is the identity matrix
  4881. */
  4882. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4883. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4884. if (this._isIdentityDirty) {
  4885. this._isIdentityDirty = false;
  4886. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4887. this._isIdentity = false;
  4888. }
  4889. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4890. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4891. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4892. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4893. this._isIdentity = false;
  4894. }
  4895. else {
  4896. this._isIdentity = true;
  4897. }
  4898. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4899. this._isIdentity = false;
  4900. }
  4901. }
  4902. return this._isIdentity;
  4903. };
  4904. /**
  4905. * Gets the determinant of the matrix
  4906. * @returns the matrix determinant
  4907. */
  4908. Matrix.prototype.determinant = function () {
  4909. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4910. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4911. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4912. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4913. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4914. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4915. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4916. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4917. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4918. };
  4919. // Methods
  4920. /**
  4921. * Returns the matrix as a Float32Array
  4922. * @returns the matrix underlying array
  4923. */
  4924. Matrix.prototype.toArray = function () {
  4925. return this.m;
  4926. };
  4927. /**
  4928. * Returns the matrix as a Float32Array
  4929. * @returns the matrix underlying array.
  4930. */
  4931. Matrix.prototype.asArray = function () {
  4932. return this.toArray();
  4933. };
  4934. /**
  4935. * Inverts the current matrix in place
  4936. * @returns the current inverted matrix
  4937. */
  4938. Matrix.prototype.invert = function () {
  4939. this.invertToRef(this);
  4940. return this;
  4941. };
  4942. /**
  4943. * Sets all the matrix elements to zero
  4944. * @returns the current matrix
  4945. */
  4946. Matrix.prototype.reset = function () {
  4947. for (var index = 0; index < 16; index++) {
  4948. this.m[index] = 0.0;
  4949. }
  4950. this._markAsUpdated();
  4951. return this;
  4952. };
  4953. /**
  4954. * Adds the current matrix with a second one
  4955. * @param other defines the matrix to add
  4956. * @returns a new matrix as the addition of the current matrix and the given one
  4957. */
  4958. Matrix.prototype.add = function (other) {
  4959. var result = new Matrix();
  4960. this.addToRef(other, result);
  4961. return result;
  4962. };
  4963. /**
  4964. * Sets the given matrix "result" to the addition of the current matrix and the given one
  4965. * @param other defines the matrix to add
  4966. * @param result defines the target matrix
  4967. * @returns the current matrix
  4968. */
  4969. Matrix.prototype.addToRef = function (other, result) {
  4970. for (var index = 0; index < 16; index++) {
  4971. result.m[index] = this.m[index] + other.m[index];
  4972. }
  4973. result._markAsUpdated();
  4974. return this;
  4975. };
  4976. /**
  4977. * Adds in place the given matrix to the current matrix
  4978. * @param other defines the second operand
  4979. * @returns the current updated matrix
  4980. */
  4981. Matrix.prototype.addToSelf = function (other) {
  4982. for (var index = 0; index < 16; index++) {
  4983. this.m[index] += other.m[index];
  4984. }
  4985. this._markAsUpdated();
  4986. return this;
  4987. };
  4988. /**
  4989. * Sets the given matrix to the current inverted Matrix
  4990. * @param other defines the target matrix
  4991. * @returns the unmodified current matrix
  4992. */
  4993. Matrix.prototype.invertToRef = function (other) {
  4994. var l1 = this.m[0];
  4995. var l2 = this.m[1];
  4996. var l3 = this.m[2];
  4997. var l4 = this.m[3];
  4998. var l5 = this.m[4];
  4999. var l6 = this.m[5];
  5000. var l7 = this.m[6];
  5001. var l8 = this.m[7];
  5002. var l9 = this.m[8];
  5003. var l10 = this.m[9];
  5004. var l11 = this.m[10];
  5005. var l12 = this.m[11];
  5006. var l13 = this.m[12];
  5007. var l14 = this.m[13];
  5008. var l15 = this.m[14];
  5009. var l16 = this.m[15];
  5010. var l17 = (l11 * l16) - (l12 * l15);
  5011. var l18 = (l10 * l16) - (l12 * l14);
  5012. var l19 = (l10 * l15) - (l11 * l14);
  5013. var l20 = (l9 * l16) - (l12 * l13);
  5014. var l21 = (l9 * l15) - (l11 * l13);
  5015. var l22 = (l9 * l14) - (l10 * l13);
  5016. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5017. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5018. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5019. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5020. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5021. var l28 = (l7 * l16) - (l8 * l15);
  5022. var l29 = (l6 * l16) - (l8 * l14);
  5023. var l30 = (l6 * l15) - (l7 * l14);
  5024. var l31 = (l5 * l16) - (l8 * l13);
  5025. var l32 = (l5 * l15) - (l7 * l13);
  5026. var l33 = (l5 * l14) - (l6 * l13);
  5027. var l34 = (l7 * l12) - (l8 * l11);
  5028. var l35 = (l6 * l12) - (l8 * l10);
  5029. var l36 = (l6 * l11) - (l7 * l10);
  5030. var l37 = (l5 * l12) - (l8 * l9);
  5031. var l38 = (l5 * l11) - (l7 * l9);
  5032. var l39 = (l5 * l10) - (l6 * l9);
  5033. other.m[0] = l23 * l27;
  5034. other.m[4] = l24 * l27;
  5035. other.m[8] = l25 * l27;
  5036. other.m[12] = l26 * l27;
  5037. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5038. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5039. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5040. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5041. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5042. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5043. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5044. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5045. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5046. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5047. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5048. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5049. other._markAsUpdated();
  5050. return this;
  5051. };
  5052. /**
  5053. * Inserts the translation vector (using 3 floats) in the current matrix
  5054. * @param x defines the 1st component of the translation
  5055. * @param y defines the 2nd component of the translation
  5056. * @param z defines the 3rd component of the translation
  5057. * @returns the current updated matrix
  5058. */
  5059. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5060. this.m[12] = x;
  5061. this.m[13] = y;
  5062. this.m[14] = z;
  5063. this._markAsUpdated();
  5064. return this;
  5065. };
  5066. /**
  5067. * Inserts the translation vector in the current matrix
  5068. * @param vector3 defines the translation to insert
  5069. * @returns the current updated matrix
  5070. */
  5071. Matrix.prototype.setTranslation = function (vector3) {
  5072. this.m[12] = vector3.x;
  5073. this.m[13] = vector3.y;
  5074. this.m[14] = vector3.z;
  5075. this._markAsUpdated();
  5076. return this;
  5077. };
  5078. /**
  5079. * Gets the translation value of the current matrix
  5080. * @returns a new Vector3 as the extracted translation from the matrix
  5081. */
  5082. Matrix.prototype.getTranslation = function () {
  5083. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5084. };
  5085. /**
  5086. * Fill a Vector3 with the extracted translation from the matrix
  5087. * @param result defines the Vector3 where to store the translation
  5088. * @returns the current matrix
  5089. */
  5090. Matrix.prototype.getTranslationToRef = function (result) {
  5091. result.x = this.m[12];
  5092. result.y = this.m[13];
  5093. result.z = this.m[14];
  5094. return this;
  5095. };
  5096. /**
  5097. * Remove rotation and scaling part from the matrix
  5098. * @returns the updated matrix
  5099. */
  5100. Matrix.prototype.removeRotationAndScaling = function () {
  5101. this.setRowFromFloats(0, 1, 0, 0, 0);
  5102. this.setRowFromFloats(1, 0, 1, 0, 0);
  5103. this.setRowFromFloats(2, 0, 0, 1, 0);
  5104. return this;
  5105. };
  5106. /**
  5107. * Multiply two matrices
  5108. * @param other defines the second operand
  5109. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5110. */
  5111. Matrix.prototype.multiply = function (other) {
  5112. var result = new Matrix();
  5113. this.multiplyToRef(other, result);
  5114. return result;
  5115. };
  5116. /**
  5117. * Copy the current matrix from the given one
  5118. * @param other defines the source matrix
  5119. * @returns the current updated matrix
  5120. */
  5121. Matrix.prototype.copyFrom = function (other) {
  5122. for (var index = 0; index < 16; index++) {
  5123. this.m[index] = other.m[index];
  5124. }
  5125. this._markAsUpdated();
  5126. return this;
  5127. };
  5128. /**
  5129. * Populates the given array from the starting index with the current matrix values
  5130. * @param array defines the target array
  5131. * @param offset defines the offset in the target array where to start storing values
  5132. * @returns the current matrix
  5133. */
  5134. Matrix.prototype.copyToArray = function (array, offset) {
  5135. if (offset === void 0) { offset = 0; }
  5136. for (var index = 0; index < 16; index++) {
  5137. array[offset + index] = this.m[index];
  5138. }
  5139. return this;
  5140. };
  5141. /**
  5142. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5143. * @param other defines the second operand
  5144. * @param result defines the matrix where to store the multiplication
  5145. * @returns the current matrix
  5146. */
  5147. Matrix.prototype.multiplyToRef = function (other, result) {
  5148. this.multiplyToArray(other, result.m, 0);
  5149. result._markAsUpdated();
  5150. return this;
  5151. };
  5152. /**
  5153. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5154. * @param other defines the second operand
  5155. * @param result defines the array where to store the multiplication
  5156. * @param offset defines the offset in the target array where to start storing values
  5157. * @returns the current matrix
  5158. */
  5159. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5160. var tm0 = this.m[0];
  5161. var tm1 = this.m[1];
  5162. var tm2 = this.m[2];
  5163. var tm3 = this.m[3];
  5164. var tm4 = this.m[4];
  5165. var tm5 = this.m[5];
  5166. var tm6 = this.m[6];
  5167. var tm7 = this.m[7];
  5168. var tm8 = this.m[8];
  5169. var tm9 = this.m[9];
  5170. var tm10 = this.m[10];
  5171. var tm11 = this.m[11];
  5172. var tm12 = this.m[12];
  5173. var tm13 = this.m[13];
  5174. var tm14 = this.m[14];
  5175. var tm15 = this.m[15];
  5176. var om0 = other.m[0];
  5177. var om1 = other.m[1];
  5178. var om2 = other.m[2];
  5179. var om3 = other.m[3];
  5180. var om4 = other.m[4];
  5181. var om5 = other.m[5];
  5182. var om6 = other.m[6];
  5183. var om7 = other.m[7];
  5184. var om8 = other.m[8];
  5185. var om9 = other.m[9];
  5186. var om10 = other.m[10];
  5187. var om11 = other.m[11];
  5188. var om12 = other.m[12];
  5189. var om13 = other.m[13];
  5190. var om14 = other.m[14];
  5191. var om15 = other.m[15];
  5192. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5193. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5194. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5195. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5196. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5197. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5198. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5199. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5200. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5201. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5202. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5203. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5204. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5205. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5206. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5207. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5208. return this;
  5209. };
  5210. /**
  5211. * Check equality between this matrix and a second one
  5212. * @param value defines the second matrix to compare
  5213. * @returns true is the current matrix and the given one values are strictly equal
  5214. */
  5215. Matrix.prototype.equals = function (value) {
  5216. return value &&
  5217. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5218. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5219. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5220. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5221. };
  5222. /**
  5223. * Clone the current matrix
  5224. * @returns a new matrix from the current matrix
  5225. */
  5226. Matrix.prototype.clone = function () {
  5227. 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]);
  5228. };
  5229. /**
  5230. * Returns the name of the current matrix class
  5231. * @returns the string "Matrix"
  5232. */
  5233. Matrix.prototype.getClassName = function () {
  5234. return "Matrix";
  5235. };
  5236. /**
  5237. * Gets the hash code of the current matrix
  5238. * @returns the hash code
  5239. */
  5240. Matrix.prototype.getHashCode = function () {
  5241. var hash = this.m[0] || 0;
  5242. for (var i = 1; i < 16; i++) {
  5243. hash = (hash * 397) ^ (this.m[i] || 0);
  5244. }
  5245. return hash;
  5246. };
  5247. /**
  5248. * Decomposes the current Matrix into a translation, rotation and scaling components
  5249. * @param scale defines the scale vector3 given as a reference to update
  5250. * @param rotation defines the rotation quaternion given as a reference to update
  5251. * @param translation defines the translation vector3 given as a reference to update
  5252. * @returns true if operation was successful
  5253. */
  5254. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5255. if (translation) {
  5256. translation.x = this.m[12];
  5257. translation.y = this.m[13];
  5258. translation.z = this.m[14];
  5259. }
  5260. scale = scale || MathTmp.Vector3[0];
  5261. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5262. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5263. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5264. if (this.determinant() <= 0) {
  5265. scale.y *= -1;
  5266. }
  5267. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5268. if (rotation) {
  5269. rotation.x = 0;
  5270. rotation.y = 0;
  5271. rotation.z = 0;
  5272. rotation.w = 1;
  5273. }
  5274. return false;
  5275. }
  5276. if (rotation) {
  5277. 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]);
  5278. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5279. }
  5280. return true;
  5281. };
  5282. /**
  5283. * Gets specific row of the matrix
  5284. * @param index defines the number of the row to get
  5285. * @returns the index-th row of the current matrix as a new Vector4
  5286. */
  5287. Matrix.prototype.getRow = function (index) {
  5288. if (index < 0 || index > 3) {
  5289. return null;
  5290. }
  5291. var i = index * 4;
  5292. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5293. };
  5294. /**
  5295. * Sets the index-th row of the current matrix to the vector4 values
  5296. * @param index defines the number of the row to set
  5297. * @param row defines the target vector4
  5298. * @returns the updated current matrix
  5299. */
  5300. Matrix.prototype.setRow = function (index, row) {
  5301. if (index < 0 || index > 3) {
  5302. return this;
  5303. }
  5304. var i = index * 4;
  5305. this.m[i + 0] = row.x;
  5306. this.m[i + 1] = row.y;
  5307. this.m[i + 2] = row.z;
  5308. this.m[i + 3] = row.w;
  5309. this._markAsUpdated();
  5310. return this;
  5311. };
  5312. /**
  5313. * Compute the transpose of the matrix
  5314. * @returns the new transposed matrix
  5315. */
  5316. Matrix.prototype.transpose = function () {
  5317. return Matrix.Transpose(this);
  5318. };
  5319. /**
  5320. * Compute the transpose of the matrix and store it in a given matrix
  5321. * @param result defines the target matrix
  5322. * @returns the current matrix
  5323. */
  5324. Matrix.prototype.transposeToRef = function (result) {
  5325. Matrix.TransposeToRef(this, result);
  5326. return this;
  5327. };
  5328. /**
  5329. * Sets the index-th row of the current matrix with the given 4 x float values
  5330. * @param index defines the row index
  5331. * @param x defines the x component to set
  5332. * @param y defines the y component to set
  5333. * @param z defines the z component to set
  5334. * @param w defines the w component to set
  5335. * @returns the updated current matrix
  5336. */
  5337. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5338. if (index < 0 || index > 3) {
  5339. return this;
  5340. }
  5341. var i = index * 4;
  5342. this.m[i + 0] = x;
  5343. this.m[i + 1] = y;
  5344. this.m[i + 2] = z;
  5345. this.m[i + 3] = w;
  5346. this._markAsUpdated();
  5347. return this;
  5348. };
  5349. /**
  5350. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5351. * @param scale defines the scale factor
  5352. * @returns a new matrix
  5353. */
  5354. Matrix.prototype.scale = function (scale) {
  5355. var result = new Matrix();
  5356. this.scaleToRef(scale, result);
  5357. return result;
  5358. };
  5359. /**
  5360. * Scale the current matrix values by a factor to a given result matrix
  5361. * @param scale defines the scale factor
  5362. * @param result defines the matrix to store the result
  5363. * @returns the current matrix
  5364. */
  5365. Matrix.prototype.scaleToRef = function (scale, result) {
  5366. for (var index = 0; index < 16; index++) {
  5367. result.m[index] = this.m[index] * scale;
  5368. }
  5369. result._markAsUpdated();
  5370. return this;
  5371. };
  5372. /**
  5373. * Scale the current matrix values by a factor and add the result to a given matrix
  5374. * @param scale defines the scale factor
  5375. * @param result defines the Matrix to store the result
  5376. * @returns the current matrix
  5377. */
  5378. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5379. for (var index = 0; index < 16; index++) {
  5380. result.m[index] += this.m[index] * scale;
  5381. }
  5382. result._markAsUpdated();
  5383. return this;
  5384. };
  5385. /**
  5386. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5387. * @param ref matrix to store the result
  5388. */
  5389. Matrix.prototype.toNormalMatrix = function (ref) {
  5390. this.invertToRef(ref);
  5391. ref.transpose();
  5392. var m = ref.m;
  5393. 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);
  5394. };
  5395. /**
  5396. * Gets only rotation part of the current matrix
  5397. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5398. */
  5399. Matrix.prototype.getRotationMatrix = function () {
  5400. var result = Matrix.Identity();
  5401. this.getRotationMatrixToRef(result);
  5402. return result;
  5403. };
  5404. /**
  5405. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5406. * @param result defines the target matrix to store data to
  5407. * @returns the current matrix
  5408. */
  5409. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5410. var m = this.m;
  5411. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5412. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5413. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5414. if (this.determinant() <= 0) {
  5415. sy *= -1;
  5416. }
  5417. if (sx === 0 || sy === 0 || sz === 0) {
  5418. Matrix.IdentityToRef(result);
  5419. }
  5420. else {
  5421. 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);
  5422. }
  5423. return this;
  5424. };
  5425. // Statics
  5426. /**
  5427. * Creates a matrix from an array
  5428. * @param array defines the source array
  5429. * @param offset defines an offset in the source array
  5430. * @returns a new Matrix set from the starting index of the given array
  5431. */
  5432. Matrix.FromArray = function (array, offset) {
  5433. var result = new Matrix();
  5434. if (!offset) {
  5435. offset = 0;
  5436. }
  5437. Matrix.FromArrayToRef(array, offset, result);
  5438. return result;
  5439. };
  5440. /**
  5441. * Copy the content of an array into a given matrix
  5442. * @param array defines the source array
  5443. * @param offset defines an offset in the source array
  5444. * @param result defines the target matrix
  5445. */
  5446. Matrix.FromArrayToRef = function (array, offset, result) {
  5447. for (var index = 0; index < 16; index++) {
  5448. result.m[index] = array[index + offset];
  5449. }
  5450. result._markAsUpdated();
  5451. };
  5452. /**
  5453. * Stores an array into a matrix after having multiplied each component by a given factor
  5454. * @param array defines the source array
  5455. * @param offset defines the offset in the source array
  5456. * @param scale defines the scaling factor
  5457. * @param result defines the target matrix
  5458. */
  5459. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5460. for (var index = 0; index < 16; index++) {
  5461. result.m[index] = array[index + offset] * scale;
  5462. }
  5463. result._markAsUpdated();
  5464. };
  5465. /**
  5466. * Stores a list of values (16) inside a given matrix
  5467. * @param initialM11 defines 1st value of 1st row
  5468. * @param initialM12 defines 2nd value of 1st row
  5469. * @param initialM13 defines 3rd value of 1st row
  5470. * @param initialM14 defines 4th value of 1st row
  5471. * @param initialM21 defines 1st value of 2nd row
  5472. * @param initialM22 defines 2nd value of 2nd row
  5473. * @param initialM23 defines 3rd value of 2nd row
  5474. * @param initialM24 defines 4th value of 2nd row
  5475. * @param initialM31 defines 1st value of 3rd row
  5476. * @param initialM32 defines 2nd value of 3rd row
  5477. * @param initialM33 defines 3rd value of 3rd row
  5478. * @param initialM34 defines 4th value of 3rd row
  5479. * @param initialM41 defines 1st value of 4th row
  5480. * @param initialM42 defines 2nd value of 4th row
  5481. * @param initialM43 defines 3rd value of 4th row
  5482. * @param initialM44 defines 4th value of 4th row
  5483. * @param result defines the target matrix
  5484. */
  5485. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5486. result.m[0] = initialM11;
  5487. result.m[1] = initialM12;
  5488. result.m[2] = initialM13;
  5489. result.m[3] = initialM14;
  5490. result.m[4] = initialM21;
  5491. result.m[5] = initialM22;
  5492. result.m[6] = initialM23;
  5493. result.m[7] = initialM24;
  5494. result.m[8] = initialM31;
  5495. result.m[9] = initialM32;
  5496. result.m[10] = initialM33;
  5497. result.m[11] = initialM34;
  5498. result.m[12] = initialM41;
  5499. result.m[13] = initialM42;
  5500. result.m[14] = initialM43;
  5501. result.m[15] = initialM44;
  5502. result._markAsUpdated();
  5503. };
  5504. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5505. /**
  5506. * Gets an identity matrix that must not be updated
  5507. */
  5508. get: function () {
  5509. return Matrix._identityReadOnly;
  5510. },
  5511. enumerable: true,
  5512. configurable: true
  5513. });
  5514. /**
  5515. * Creates new matrix from a list of values (16)
  5516. * @param initialM11 defines 1st value of 1st row
  5517. * @param initialM12 defines 2nd value of 1st row
  5518. * @param initialM13 defines 3rd value of 1st row
  5519. * @param initialM14 defines 4th value of 1st row
  5520. * @param initialM21 defines 1st value of 2nd row
  5521. * @param initialM22 defines 2nd value of 2nd row
  5522. * @param initialM23 defines 3rd value of 2nd row
  5523. * @param initialM24 defines 4th value of 2nd row
  5524. * @param initialM31 defines 1st value of 3rd row
  5525. * @param initialM32 defines 2nd value of 3rd row
  5526. * @param initialM33 defines 3rd value of 3rd row
  5527. * @param initialM34 defines 4th value of 3rd row
  5528. * @param initialM41 defines 1st value of 4th row
  5529. * @param initialM42 defines 2nd value of 4th row
  5530. * @param initialM43 defines 3rd value of 4th row
  5531. * @param initialM44 defines 4th value of 4th row
  5532. * @returns the new matrix
  5533. */
  5534. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5535. var result = new Matrix();
  5536. result.m[0] = initialM11;
  5537. result.m[1] = initialM12;
  5538. result.m[2] = initialM13;
  5539. result.m[3] = initialM14;
  5540. result.m[4] = initialM21;
  5541. result.m[5] = initialM22;
  5542. result.m[6] = initialM23;
  5543. result.m[7] = initialM24;
  5544. result.m[8] = initialM31;
  5545. result.m[9] = initialM32;
  5546. result.m[10] = initialM33;
  5547. result.m[11] = initialM34;
  5548. result.m[12] = initialM41;
  5549. result.m[13] = initialM42;
  5550. result.m[14] = initialM43;
  5551. result.m[15] = initialM44;
  5552. return result;
  5553. };
  5554. /**
  5555. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5556. * @param scale defines the scale vector3
  5557. * @param rotation defines the rotation quaternion
  5558. * @param translation defines the translation vector3
  5559. * @returns a new matrix
  5560. */
  5561. Matrix.Compose = function (scale, rotation, translation) {
  5562. var result = Matrix.Identity();
  5563. Matrix.ComposeToRef(scale, rotation, translation, result);
  5564. return result;
  5565. };
  5566. /**
  5567. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5568. * @param scale defines the scale vector3
  5569. * @param rotation defines the rotation quaternion
  5570. * @param translation defines the translation vector3
  5571. * @param result defines the target matrix
  5572. */
  5573. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5574. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5575. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5576. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5577. result.setTranslation(translation);
  5578. };
  5579. /**
  5580. * Creates a new identity matrix
  5581. * @returns a new identity matrix
  5582. */
  5583. Matrix.Identity = function () {
  5584. 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);
  5585. };
  5586. /**
  5587. * Creates a new identity matrix and stores the result in a given matrix
  5588. * @param result defines the target matrix
  5589. */
  5590. Matrix.IdentityToRef = function (result) {
  5591. 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);
  5592. };
  5593. /**
  5594. * Creates a new zero matrix
  5595. * @returns a new zero matrix
  5596. */
  5597. Matrix.Zero = function () {
  5598. 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);
  5599. };
  5600. /**
  5601. * Creates a new rotation matrix for "angle" radians around the X axis
  5602. * @param angle defines the angle (in radians) to use
  5603. * @return the new matrix
  5604. */
  5605. Matrix.RotationX = function (angle) {
  5606. var result = new Matrix();
  5607. Matrix.RotationXToRef(angle, result);
  5608. return result;
  5609. };
  5610. /**
  5611. * Creates a new matrix as the invert of a given matrix
  5612. * @param source defines the source matrix
  5613. * @returns the new matrix
  5614. */
  5615. Matrix.Invert = function (source) {
  5616. var result = new Matrix();
  5617. source.invertToRef(result);
  5618. return result;
  5619. };
  5620. /**
  5621. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5622. * @param angle defines the angle (in radians) to use
  5623. * @param result defines the target matrix
  5624. */
  5625. Matrix.RotationXToRef = function (angle, result) {
  5626. var s = Math.sin(angle);
  5627. var c = Math.cos(angle);
  5628. result.m[0] = 1.0;
  5629. result.m[15] = 1.0;
  5630. result.m[5] = c;
  5631. result.m[10] = c;
  5632. result.m[9] = -s;
  5633. result.m[6] = s;
  5634. result.m[1] = 0.0;
  5635. result.m[2] = 0.0;
  5636. result.m[3] = 0.0;
  5637. result.m[4] = 0.0;
  5638. result.m[7] = 0.0;
  5639. result.m[8] = 0.0;
  5640. result.m[11] = 0.0;
  5641. result.m[12] = 0.0;
  5642. result.m[13] = 0.0;
  5643. result.m[14] = 0.0;
  5644. result._markAsUpdated();
  5645. };
  5646. /**
  5647. * Creates a new rotation matrix for "angle" radians around the Y axis
  5648. * @param angle defines the angle (in radians) to use
  5649. * @return the new matrix
  5650. */
  5651. Matrix.RotationY = function (angle) {
  5652. var result = new Matrix();
  5653. Matrix.RotationYToRef(angle, result);
  5654. return result;
  5655. };
  5656. /**
  5657. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5658. * @param angle defines the angle (in radians) to use
  5659. * @param result defines the target matrix
  5660. */
  5661. Matrix.RotationYToRef = function (angle, result) {
  5662. var s = Math.sin(angle);
  5663. var c = Math.cos(angle);
  5664. result.m[5] = 1.0;
  5665. result.m[15] = 1.0;
  5666. result.m[0] = c;
  5667. result.m[2] = -s;
  5668. result.m[8] = s;
  5669. result.m[10] = c;
  5670. result.m[1] = 0.0;
  5671. result.m[3] = 0.0;
  5672. result.m[4] = 0.0;
  5673. result.m[6] = 0.0;
  5674. result.m[7] = 0.0;
  5675. result.m[9] = 0.0;
  5676. result.m[11] = 0.0;
  5677. result.m[12] = 0.0;
  5678. result.m[13] = 0.0;
  5679. result.m[14] = 0.0;
  5680. result._markAsUpdated();
  5681. };
  5682. /**
  5683. * Creates a new rotation matrix for "angle" radians around the Z axis
  5684. * @param angle defines the angle (in radians) to use
  5685. * @return the new matrix
  5686. */
  5687. Matrix.RotationZ = function (angle) {
  5688. var result = new Matrix();
  5689. Matrix.RotationZToRef(angle, result);
  5690. return result;
  5691. };
  5692. /**
  5693. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5694. * @param angle defines the angle (in radians) to use
  5695. * @param result defines the target matrix
  5696. */
  5697. Matrix.RotationZToRef = function (angle, result) {
  5698. var s = Math.sin(angle);
  5699. var c = Math.cos(angle);
  5700. result.m[10] = 1.0;
  5701. result.m[15] = 1.0;
  5702. result.m[0] = c;
  5703. result.m[1] = s;
  5704. result.m[4] = -s;
  5705. result.m[5] = c;
  5706. result.m[2] = 0.0;
  5707. result.m[3] = 0.0;
  5708. result.m[6] = 0.0;
  5709. result.m[7] = 0.0;
  5710. result.m[8] = 0.0;
  5711. result.m[9] = 0.0;
  5712. result.m[11] = 0.0;
  5713. result.m[12] = 0.0;
  5714. result.m[13] = 0.0;
  5715. result.m[14] = 0.0;
  5716. result._markAsUpdated();
  5717. };
  5718. /**
  5719. * Creates a new rotation matrix for "angle" radians around the given axis
  5720. * @param axis defines the axis to use
  5721. * @param angle defines the angle (in radians) to use
  5722. * @return the new matrix
  5723. */
  5724. Matrix.RotationAxis = function (axis, angle) {
  5725. var result = Matrix.Zero();
  5726. Matrix.RotationAxisToRef(axis, angle, result);
  5727. return result;
  5728. };
  5729. /**
  5730. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5731. * @param axis defines the axis to use
  5732. * @param angle defines the angle (in radians) to use
  5733. * @param result defines the target matrix
  5734. */
  5735. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5736. var s = Math.sin(-angle);
  5737. var c = Math.cos(-angle);
  5738. var c1 = 1 - c;
  5739. axis.normalize();
  5740. result.m[0] = (axis.x * axis.x) * c1 + c;
  5741. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5742. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5743. result.m[3] = 0.0;
  5744. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5745. result.m[5] = (axis.y * axis.y) * c1 + c;
  5746. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5747. result.m[7] = 0.0;
  5748. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5749. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5750. result.m[10] = (axis.z * axis.z) * c1 + c;
  5751. result.m[11] = 0.0;
  5752. result.m[15] = 1.0;
  5753. result._markAsUpdated();
  5754. };
  5755. /**
  5756. * Creates a rotation matrix
  5757. * @param yaw defines the yaw angle in radians (Y axis)
  5758. * @param pitch defines the pitch angle in radians (X axis)
  5759. * @param roll defines the roll angle in radians (X axis)
  5760. * @returns the new rotation matrix
  5761. */
  5762. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5763. var result = new Matrix();
  5764. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a rotation matrix and stores it in a given matrix
  5769. * @param yaw defines the yaw angle in radians (Y axis)
  5770. * @param pitch defines the pitch angle in radians (X axis)
  5771. * @param roll defines the roll angle in radians (X axis)
  5772. * @param result defines the target matrix
  5773. */
  5774. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5775. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5776. this._tempQuaternion.toRotationMatrix(result);
  5777. };
  5778. /**
  5779. * Creates a scaling matrix
  5780. * @param x defines the scale factor on X axis
  5781. * @param y defines the scale factor on Y axis
  5782. * @param z defines the scale factor on Z axis
  5783. * @returns the new matrix
  5784. */
  5785. Matrix.Scaling = function (x, y, z) {
  5786. var result = Matrix.Zero();
  5787. Matrix.ScalingToRef(x, y, z, result);
  5788. return result;
  5789. };
  5790. /**
  5791. * Creates a scaling matrix and stores it in a given matrix
  5792. * @param x defines the scale factor on X axis
  5793. * @param y defines the scale factor on Y axis
  5794. * @param z defines the scale factor on Z axis
  5795. * @param result defines the target matrix
  5796. */
  5797. Matrix.ScalingToRef = function (x, y, z, result) {
  5798. result.m[0] = x;
  5799. result.m[1] = 0.0;
  5800. result.m[2] = 0.0;
  5801. result.m[3] = 0.0;
  5802. result.m[4] = 0.0;
  5803. result.m[5] = y;
  5804. result.m[6] = 0.0;
  5805. result.m[7] = 0.0;
  5806. result.m[8] = 0.0;
  5807. result.m[9] = 0.0;
  5808. result.m[10] = z;
  5809. result.m[11] = 0.0;
  5810. result.m[12] = 0.0;
  5811. result.m[13] = 0.0;
  5812. result.m[14] = 0.0;
  5813. result.m[15] = 1.0;
  5814. result._markAsUpdated();
  5815. };
  5816. /**
  5817. * Creates a translation matrix
  5818. * @param x defines the translation on X axis
  5819. * @param y defines the translation on Y axis
  5820. * @param z defines the translationon Z axis
  5821. * @returns the new matrix
  5822. */
  5823. Matrix.Translation = function (x, y, z) {
  5824. var result = Matrix.Identity();
  5825. Matrix.TranslationToRef(x, y, z, result);
  5826. return result;
  5827. };
  5828. /**
  5829. * Creates a translation matrix and stores it in a given matrix
  5830. * @param x defines the translation on X axis
  5831. * @param y defines the translation on Y axis
  5832. * @param z defines the translationon Z axis
  5833. * @param result defines the target matrix
  5834. */
  5835. Matrix.TranslationToRef = function (x, y, z, result) {
  5836. 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);
  5837. };
  5838. /**
  5839. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5840. * @param startValue defines the start value
  5841. * @param endValue defines the end value
  5842. * @param gradient defines the gradient factor
  5843. * @returns the new matrix
  5844. */
  5845. Matrix.Lerp = function (startValue, endValue, gradient) {
  5846. var result = Matrix.Zero();
  5847. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5852. * @param startValue defines the start value
  5853. * @param endValue defines the end value
  5854. * @param gradient defines the gradient factor
  5855. * @param result defines the Matrix object where to store data
  5856. */
  5857. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5858. for (var index = 0; index < 16; index++) {
  5859. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5860. }
  5861. result._markAsUpdated();
  5862. };
  5863. /**
  5864. * Builds a new matrix whose values are computed by:
  5865. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5866. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5867. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5868. * @param startValue defines the first matrix
  5869. * @param endValue defines the second matrix
  5870. * @param gradient defines the gradient between the two matrices
  5871. * @returns the new matrix
  5872. */
  5873. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5874. var result = Matrix.Zero();
  5875. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5876. return result;
  5877. };
  5878. /**
  5879. * Update a matrix to values which are computed by:
  5880. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5881. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5882. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5883. * @param startValue defines the first matrix
  5884. * @param endValue defines the second matrix
  5885. * @param gradient defines the gradient between the two matrices
  5886. * @param result defines the target matrix
  5887. */
  5888. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5889. var startScale = MathTmp.Vector3[0];
  5890. var startRotation = MathTmp.Quaternion[0];
  5891. var startTranslation = MathTmp.Vector3[1];
  5892. startValue.decompose(startScale, startRotation, startTranslation);
  5893. var endScale = MathTmp.Vector3[2];
  5894. var endRotation = MathTmp.Quaternion[1];
  5895. var endTranslation = MathTmp.Vector3[3];
  5896. endValue.decompose(endScale, endRotation, endTranslation);
  5897. var resultScale = MathTmp.Vector3[4];
  5898. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  5899. var resultRotation = MathTmp.Quaternion[2];
  5900. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  5901. var resultTranslation = MathTmp.Vector3[5];
  5902. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  5903. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  5904. };
  5905. /**
  5906. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  5907. * This function works in left handed mode
  5908. * @param eye defines the final position of the entity
  5909. * @param target defines where the entity should look at
  5910. * @param up defines the up vector for the entity
  5911. * @returns the new matrix
  5912. */
  5913. Matrix.LookAtLH = function (eye, target, up) {
  5914. var result = Matrix.Zero();
  5915. Matrix.LookAtLHToRef(eye, target, up, result);
  5916. return result;
  5917. };
  5918. /**
  5919. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  5920. * This function works in left handed mode
  5921. * @param eye defines the final position of the entity
  5922. * @param target defines where the entity should look at
  5923. * @param up defines the up vector for the entity
  5924. * @param result defines the target matrix
  5925. */
  5926. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5927. // Z axis
  5928. target.subtractToRef(eye, this._zAxis);
  5929. this._zAxis.normalize();
  5930. // X axis
  5931. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5932. if (this._xAxis.lengthSquared() === 0) {
  5933. this._xAxis.x = 1.0;
  5934. }
  5935. else {
  5936. this._xAxis.normalize();
  5937. }
  5938. // Y axis
  5939. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5940. this._yAxis.normalize();
  5941. // Eye angles
  5942. var ex = -Vector3.Dot(this._xAxis, eye);
  5943. var ey = -Vector3.Dot(this._yAxis, eye);
  5944. var ez = -Vector3.Dot(this._zAxis, eye);
  5945. 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);
  5946. };
  5947. /**
  5948. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  5949. * This function works in right handed mode
  5950. * @param eye defines the final position of the entity
  5951. * @param target defines where the entity should look at
  5952. * @param up defines the up vector for the entity
  5953. * @returns the new matrix
  5954. */
  5955. Matrix.LookAtRH = function (eye, target, up) {
  5956. var result = Matrix.Zero();
  5957. Matrix.LookAtRHToRef(eye, target, up, result);
  5958. return result;
  5959. };
  5960. /**
  5961. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  5962. * This function works in right handed mode
  5963. * @param eye defines the final position of the entity
  5964. * @param target defines where the entity should look at
  5965. * @param up defines the up vector for the entity
  5966. * @param result defines the target matrix
  5967. */
  5968. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5969. // Z axis
  5970. eye.subtractToRef(target, this._zAxis);
  5971. this._zAxis.normalize();
  5972. // X axis
  5973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5974. if (this._xAxis.lengthSquared() === 0) {
  5975. this._xAxis.x = 1.0;
  5976. }
  5977. else {
  5978. this._xAxis.normalize();
  5979. }
  5980. // Y axis
  5981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5982. this._yAxis.normalize();
  5983. // Eye angles
  5984. var ex = -Vector3.Dot(this._xAxis, eye);
  5985. var ey = -Vector3.Dot(this._yAxis, eye);
  5986. var ez = -Vector3.Dot(this._zAxis, eye);
  5987. 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);
  5988. };
  5989. /**
  5990. * Create a left-handed orthographic projection matrix
  5991. * @param width defines the viewport width
  5992. * @param height defines the viewport height
  5993. * @param znear defines the near clip plane
  5994. * @param zfar defines the far clip plane
  5995. * @returns a new matrix as a left-handed orthographic projection matrix
  5996. */
  5997. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5998. var matrix = Matrix.Zero();
  5999. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6000. return matrix;
  6001. };
  6002. /**
  6003. * Store a left-handed orthographic projection to a given matrix
  6004. * @param width defines the viewport width
  6005. * @param height defines the viewport height
  6006. * @param znear defines the near clip plane
  6007. * @param zfar defines the far clip plane
  6008. * @param result defines the target matrix
  6009. */
  6010. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6011. var n = znear;
  6012. var f = zfar;
  6013. var a = 2.0 / width;
  6014. var b = 2.0 / height;
  6015. var c = 2.0 / (f - n);
  6016. var d = -(f + n) / (f - n);
  6017. 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);
  6018. };
  6019. /**
  6020. * Create a left-handed orthographic projection matrix
  6021. * @param left defines the viewport left coordinate
  6022. * @param right defines the viewport right coordinate
  6023. * @param bottom defines the viewport bottom coordinate
  6024. * @param top defines the viewport top coordinate
  6025. * @param znear defines the near clip plane
  6026. * @param zfar defines the far clip plane
  6027. * @returns a new matrix as a left-handed orthographic projection matrix
  6028. */
  6029. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6030. var matrix = Matrix.Zero();
  6031. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6032. return matrix;
  6033. };
  6034. /**
  6035. * Stores a left-handed orthographic projection into a given matrix
  6036. * @param left defines the viewport left coordinate
  6037. * @param right defines the viewport right coordinate
  6038. * @param bottom defines the viewport bottom coordinate
  6039. * @param top defines the viewport top coordinate
  6040. * @param znear defines the near clip plane
  6041. * @param zfar defines the far clip plane
  6042. * @param result defines the target matrix
  6043. */
  6044. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6045. var n = znear;
  6046. var f = zfar;
  6047. var a = 2.0 / (right - left);
  6048. var b = 2.0 / (top - bottom);
  6049. var c = 2.0 / (f - n);
  6050. var d = -(f + n) / (f - n);
  6051. var i0 = (left + right) / (left - right);
  6052. var i1 = (top + bottom) / (bottom - top);
  6053. 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);
  6054. };
  6055. /**
  6056. * Creates a right-handed orthographic projection matrix
  6057. * @param left defines the viewport left coordinate
  6058. * @param right defines the viewport right coordinate
  6059. * @param bottom defines the viewport bottom coordinate
  6060. * @param top defines the viewport top coordinate
  6061. * @param znear defines the near clip plane
  6062. * @param zfar defines the far clip plane
  6063. * @returns a new matrix as a right-handed orthographic projection matrix
  6064. */
  6065. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6066. var matrix = Matrix.Zero();
  6067. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6068. return matrix;
  6069. };
  6070. /**
  6071. * Stores a right-handed orthographic projection into a given matrix
  6072. * @param left defines the viewport left coordinate
  6073. * @param right defines the viewport right coordinate
  6074. * @param bottom defines the viewport bottom coordinate
  6075. * @param top defines the viewport top coordinate
  6076. * @param znear defines the near clip plane
  6077. * @param zfar defines the far clip plane
  6078. * @param result defines the target matrix
  6079. */
  6080. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6081. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6082. result.m[10] *= -1.0;
  6083. };
  6084. /**
  6085. * Creates a left-handed perspective projection matrix
  6086. * @param width defines the viewport width
  6087. * @param height defines the viewport height
  6088. * @param znear defines the near clip plane
  6089. * @param zfar defines the far clip plane
  6090. * @returns a new matrix as a left-handed perspective projection matrix
  6091. */
  6092. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6093. var matrix = Matrix.Zero();
  6094. var n = znear;
  6095. var f = zfar;
  6096. var a = 2.0 * n / width;
  6097. var b = 2.0 * n / height;
  6098. var c = (f + n) / (f - n);
  6099. var d = -2.0 * f * n / (f - n);
  6100. 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);
  6101. return matrix;
  6102. };
  6103. /**
  6104. * Creates a left-handed perspective projection matrix
  6105. * @param fov defines the horizontal field of view
  6106. * @param aspect defines the aspect ratio
  6107. * @param znear defines the near clip plane
  6108. * @param zfar defines the far clip plane
  6109. * @returns a new matrix as a left-handed perspective projection matrix
  6110. */
  6111. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6112. var matrix = Matrix.Zero();
  6113. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6114. return matrix;
  6115. };
  6116. /**
  6117. * Stores a left-handed perspective projection into a given matrix
  6118. * @param fov defines the horizontal field of view
  6119. * @param aspect defines the aspect ratio
  6120. * @param znear defines the near clip plane
  6121. * @param zfar defines the far clip plane
  6122. * @param result defines the target matrix
  6123. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6124. */
  6125. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6126. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6127. var n = znear;
  6128. var f = zfar;
  6129. var t = 1.0 / (Math.tan(fov * 0.5));
  6130. var a = isVerticalFovFixed ? (t / aspect) : t;
  6131. var b = isVerticalFovFixed ? t : (t * aspect);
  6132. var c = (f + n) / (f - n);
  6133. var d = -2.0 * f * n / (f - n);
  6134. 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);
  6135. };
  6136. /**
  6137. * Creates a right-handed perspective projection matrix
  6138. * @param fov defines the horizontal field of view
  6139. * @param aspect defines the aspect ratio
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a right-handed perspective projection matrix
  6143. */
  6144. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Stores a right-handed perspective projection into a given matrix
  6151. * @param fov defines the horizontal field of view
  6152. * @param aspect defines the aspect ratio
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6157. */
  6158. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6159. //alternatively this could be expressed as:
  6160. // m = PerspectiveFovLHToRef
  6161. // m[10] *= -1.0;
  6162. // m[11] *= -1.0;
  6163. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6164. var n = znear;
  6165. var f = zfar;
  6166. var t = 1.0 / (Math.tan(fov * 0.5));
  6167. var a = isVerticalFovFixed ? (t / aspect) : t;
  6168. var b = isVerticalFovFixed ? t : (t * aspect);
  6169. var c = -(f + n) / (f - n);
  6170. var d = -2 * f * n / (f - n);
  6171. 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);
  6172. };
  6173. /**
  6174. * Stores a perspective projection for WebVR info a given matrix
  6175. * @param fov defines the field of view
  6176. * @param znear defines the near clip plane
  6177. * @param zfar defines the far clip plane
  6178. * @param result defines the target matrix
  6179. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6180. */
  6181. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6182. if (rightHanded === void 0) { rightHanded = false; }
  6183. var rightHandedFactor = rightHanded ? -1 : 1;
  6184. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6185. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6186. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6187. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6188. var xScale = 2.0 / (leftTan + rightTan);
  6189. var yScale = 2.0 / (upTan + downTan);
  6190. result.m[0] = xScale;
  6191. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6192. result.m[5] = yScale;
  6193. result.m[6] = result.m[7] = 0.0;
  6194. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6195. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6196. result.m[10] = -zfar / (znear - zfar);
  6197. result.m[11] = 1.0 * rightHandedFactor;
  6198. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6199. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6200. result._markAsUpdated();
  6201. };
  6202. /**
  6203. * Computes a complete transformation matrix
  6204. * @param viewport defines the viewport to use
  6205. * @param world defines the world matrix
  6206. * @param view defines the view matrix
  6207. * @param projection defines the projection matrix
  6208. * @param zmin defines the near clip plane
  6209. * @param zmax defines the far clip plane
  6210. * @returns the transformation matrix
  6211. */
  6212. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6213. var cw = viewport.width;
  6214. var ch = viewport.height;
  6215. var cx = viewport.x;
  6216. var cy = viewport.y;
  6217. 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);
  6218. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6219. };
  6220. /**
  6221. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6222. * @param matrix defines the matrix to use
  6223. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6224. */
  6225. Matrix.GetAsMatrix2x2 = function (matrix) {
  6226. return new Float32Array([
  6227. matrix.m[0], matrix.m[1],
  6228. matrix.m[4], matrix.m[5]
  6229. ]);
  6230. };
  6231. /**
  6232. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6233. * @param matrix defines the matrix to use
  6234. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6235. */
  6236. Matrix.GetAsMatrix3x3 = function (matrix) {
  6237. return new Float32Array([
  6238. matrix.m[0], matrix.m[1], matrix.m[2],
  6239. matrix.m[4], matrix.m[5], matrix.m[6],
  6240. matrix.m[8], matrix.m[9], matrix.m[10]
  6241. ]);
  6242. };
  6243. /**
  6244. * Compute the transpose of a given matrix
  6245. * @param matrix defines the matrix to transpose
  6246. * @returns the new matrix
  6247. */
  6248. Matrix.Transpose = function (matrix) {
  6249. var result = new Matrix();
  6250. Matrix.TransposeToRef(matrix, result);
  6251. return result;
  6252. };
  6253. /**
  6254. * Compute the transpose of a matrix and store it in a target matrix
  6255. * @param matrix defines the matrix to transpose
  6256. * @param result defines the target matrix
  6257. */
  6258. Matrix.TransposeToRef = function (matrix, result) {
  6259. result.m[0] = matrix.m[0];
  6260. result.m[1] = matrix.m[4];
  6261. result.m[2] = matrix.m[8];
  6262. result.m[3] = matrix.m[12];
  6263. result.m[4] = matrix.m[1];
  6264. result.m[5] = matrix.m[5];
  6265. result.m[6] = matrix.m[9];
  6266. result.m[7] = matrix.m[13];
  6267. result.m[8] = matrix.m[2];
  6268. result.m[9] = matrix.m[6];
  6269. result.m[10] = matrix.m[10];
  6270. result.m[11] = matrix.m[14];
  6271. result.m[12] = matrix.m[3];
  6272. result.m[13] = matrix.m[7];
  6273. result.m[14] = matrix.m[11];
  6274. result.m[15] = matrix.m[15];
  6275. };
  6276. /**
  6277. * Computes a reflection matrix from a plane
  6278. * @param plane defines the reflection plane
  6279. * @returns a new matrix
  6280. */
  6281. Matrix.Reflection = function (plane) {
  6282. var matrix = new Matrix();
  6283. Matrix.ReflectionToRef(plane, matrix);
  6284. return matrix;
  6285. };
  6286. /**
  6287. * Computes a reflection matrix from a plane
  6288. * @param plane defines the reflection plane
  6289. * @param result defines the target matrix
  6290. */
  6291. Matrix.ReflectionToRef = function (plane, result) {
  6292. plane.normalize();
  6293. var x = plane.normal.x;
  6294. var y = plane.normal.y;
  6295. var z = plane.normal.z;
  6296. var temp = -2 * x;
  6297. var temp2 = -2 * y;
  6298. var temp3 = -2 * z;
  6299. result.m[0] = (temp * x) + 1;
  6300. result.m[1] = temp2 * x;
  6301. result.m[2] = temp3 * x;
  6302. result.m[3] = 0.0;
  6303. result.m[4] = temp * y;
  6304. result.m[5] = (temp2 * y) + 1;
  6305. result.m[6] = temp3 * y;
  6306. result.m[7] = 0.0;
  6307. result.m[8] = temp * z;
  6308. result.m[9] = temp2 * z;
  6309. result.m[10] = (temp3 * z) + 1;
  6310. result.m[11] = 0.0;
  6311. result.m[12] = temp * plane.d;
  6312. result.m[13] = temp2 * plane.d;
  6313. result.m[14] = temp3 * plane.d;
  6314. result.m[15] = 1.0;
  6315. result._markAsUpdated();
  6316. };
  6317. /**
  6318. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6319. * @param xaxis defines the value of the 1st axis
  6320. * @param yaxis defines the value of the 2nd axis
  6321. * @param zaxis defines the value of the 3rd axis
  6322. * @param result defines the target matrix
  6323. */
  6324. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6325. result.m[0] = xaxis.x;
  6326. result.m[1] = xaxis.y;
  6327. result.m[2] = xaxis.z;
  6328. result.m[3] = 0.0;
  6329. result.m[4] = yaxis.x;
  6330. result.m[5] = yaxis.y;
  6331. result.m[6] = yaxis.z;
  6332. result.m[7] = 0.0;
  6333. result.m[8] = zaxis.x;
  6334. result.m[9] = zaxis.y;
  6335. result.m[10] = zaxis.z;
  6336. result.m[11] = 0.0;
  6337. result.m[12] = 0.0;
  6338. result.m[13] = 0.0;
  6339. result.m[14] = 0.0;
  6340. result.m[15] = 1.0;
  6341. result._markAsUpdated();
  6342. };
  6343. /**
  6344. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6345. * @param quat defines the quaternion to use
  6346. * @param result defines the target matrix
  6347. */
  6348. Matrix.FromQuaternionToRef = function (quat, result) {
  6349. var xx = quat.x * quat.x;
  6350. var yy = quat.y * quat.y;
  6351. var zz = quat.z * quat.z;
  6352. var xy = quat.x * quat.y;
  6353. var zw = quat.z * quat.w;
  6354. var zx = quat.z * quat.x;
  6355. var yw = quat.y * quat.w;
  6356. var yz = quat.y * quat.z;
  6357. var xw = quat.x * quat.w;
  6358. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6359. result.m[1] = 2.0 * (xy + zw);
  6360. result.m[2] = 2.0 * (zx - yw);
  6361. result.m[3] = 0.0;
  6362. result.m[4] = 2.0 * (xy - zw);
  6363. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6364. result.m[6] = 2.0 * (yz + xw);
  6365. result.m[7] = 0.0;
  6366. result.m[8] = 2.0 * (zx + yw);
  6367. result.m[9] = 2.0 * (yz - xw);
  6368. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6369. result.m[11] = 0.0;
  6370. result.m[12] = 0.0;
  6371. result.m[13] = 0.0;
  6372. result.m[14] = 0.0;
  6373. result.m[15] = 1.0;
  6374. result._markAsUpdated();
  6375. };
  6376. Matrix._tempQuaternion = new Quaternion();
  6377. Matrix._xAxis = Vector3.Zero();
  6378. Matrix._yAxis = Vector3.Zero();
  6379. Matrix._zAxis = Vector3.Zero();
  6380. Matrix._updateFlagSeed = 0;
  6381. Matrix._identityReadOnly = Matrix.Identity();
  6382. return Matrix;
  6383. }());
  6384. BABYLON.Matrix = Matrix;
  6385. var Plane = /** @class */ (function () {
  6386. /**
  6387. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6388. */
  6389. function Plane(a, b, c, d) {
  6390. this.normal = new Vector3(a, b, c);
  6391. this.d = d;
  6392. }
  6393. /**
  6394. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6395. */
  6396. Plane.prototype.asArray = function () {
  6397. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6398. };
  6399. // Methods
  6400. /**
  6401. * Returns a new plane copied from the current Plane.
  6402. */
  6403. Plane.prototype.clone = function () {
  6404. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6405. };
  6406. /**
  6407. * Returns the string "Plane".
  6408. */
  6409. Plane.prototype.getClassName = function () {
  6410. return "Plane";
  6411. };
  6412. /**
  6413. * Returns the Plane hash code.
  6414. */
  6415. Plane.prototype.getHashCode = function () {
  6416. var hash = this.normal.getHashCode();
  6417. hash = (hash * 397) ^ (this.d || 0);
  6418. return hash;
  6419. };
  6420. /**
  6421. * Normalize the current Plane in place.
  6422. * Returns the updated Plane.
  6423. */
  6424. Plane.prototype.normalize = function () {
  6425. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6426. var magnitude = 0.0;
  6427. if (norm !== 0) {
  6428. magnitude = 1.0 / norm;
  6429. }
  6430. this.normal.x *= magnitude;
  6431. this.normal.y *= magnitude;
  6432. this.normal.z *= magnitude;
  6433. this.d *= magnitude;
  6434. return this;
  6435. };
  6436. /**
  6437. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6438. */
  6439. Plane.prototype.transform = function (transformation) {
  6440. var transposedMatrix = Matrix.Transpose(transformation);
  6441. var x = this.normal.x;
  6442. var y = this.normal.y;
  6443. var z = this.normal.z;
  6444. var d = this.d;
  6445. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6446. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6447. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6448. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6449. return new Plane(normalX, normalY, normalZ, finalD);
  6450. };
  6451. /**
  6452. * Returns the dot product (float) of the point coordinates and the plane normal.
  6453. */
  6454. Plane.prototype.dotCoordinate = function (point) {
  6455. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6456. };
  6457. /**
  6458. * Updates the current Plane from the plane defined by the three given points.
  6459. * Returns the updated Plane.
  6460. */
  6461. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6462. var x1 = point2.x - point1.x;
  6463. var y1 = point2.y - point1.y;
  6464. var z1 = point2.z - point1.z;
  6465. var x2 = point3.x - point1.x;
  6466. var y2 = point3.y - point1.y;
  6467. var z2 = point3.z - point1.z;
  6468. var yz = (y1 * z2) - (z1 * y2);
  6469. var xz = (z1 * x2) - (x1 * z2);
  6470. var xy = (x1 * y2) - (y1 * x2);
  6471. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6472. var invPyth;
  6473. if (pyth !== 0) {
  6474. invPyth = 1.0 / pyth;
  6475. }
  6476. else {
  6477. invPyth = 0.0;
  6478. }
  6479. this.normal.x = yz * invPyth;
  6480. this.normal.y = xz * invPyth;
  6481. this.normal.z = xy * invPyth;
  6482. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6483. return this;
  6484. };
  6485. /**
  6486. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6487. */
  6488. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6489. var dot = Vector3.Dot(this.normal, direction);
  6490. return (dot <= epsilon);
  6491. };
  6492. /**
  6493. * Returns the signed distance (float) from the given point to the Plane.
  6494. */
  6495. Plane.prototype.signedDistanceTo = function (point) {
  6496. return Vector3.Dot(point, this.normal) + this.d;
  6497. };
  6498. // Statics
  6499. /**
  6500. * Returns a new Plane from the given array.
  6501. */
  6502. Plane.FromArray = function (array) {
  6503. return new Plane(array[0], array[1], array[2], array[3]);
  6504. };
  6505. /**
  6506. * Returns a new Plane defined by the three given points.
  6507. */
  6508. Plane.FromPoints = function (point1, point2, point3) {
  6509. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6510. result.copyFromPoints(point1, point2, point3);
  6511. return result;
  6512. };
  6513. /**
  6514. * Returns a new Plane the normal vector to this plane at the given origin point.
  6515. * Note : the vector "normal" is updated because normalized.
  6516. */
  6517. Plane.FromPositionAndNormal = function (origin, normal) {
  6518. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6519. normal.normalize();
  6520. result.normal = normal;
  6521. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6522. return result;
  6523. };
  6524. /**
  6525. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6526. */
  6527. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6528. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6529. return Vector3.Dot(point, normal) + d;
  6530. };
  6531. return Plane;
  6532. }());
  6533. BABYLON.Plane = Plane;
  6534. var Viewport = /** @class */ (function () {
  6535. /**
  6536. * Creates a Viewport object located at (x, y) and sized (width, height).
  6537. */
  6538. function Viewport(x, y, width, height) {
  6539. this.x = x;
  6540. this.y = y;
  6541. this.width = width;
  6542. this.height = height;
  6543. }
  6544. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6545. if (renderWidthOrEngine.getRenderWidth) {
  6546. var engine = renderWidthOrEngine;
  6547. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6548. }
  6549. var renderWidth = renderWidthOrEngine;
  6550. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6551. };
  6552. /**
  6553. * Returns a new Viewport copied from the current one.
  6554. */
  6555. Viewport.prototype.clone = function () {
  6556. return new Viewport(this.x, this.y, this.width, this.height);
  6557. };
  6558. return Viewport;
  6559. }());
  6560. BABYLON.Viewport = Viewport;
  6561. var Frustum = /** @class */ (function () {
  6562. function Frustum() {
  6563. }
  6564. /**
  6565. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6566. */
  6567. Frustum.GetPlanes = function (transform) {
  6568. var frustumPlanes = [];
  6569. for (var index = 0; index < 6; index++) {
  6570. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6571. }
  6572. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6573. return frustumPlanes;
  6574. };
  6575. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6576. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6577. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6578. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6579. frustumPlane.d = transform.m[15] + transform.m[14];
  6580. frustumPlane.normalize();
  6581. };
  6582. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6583. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6584. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6585. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6586. frustumPlane.d = transform.m[15] - transform.m[14];
  6587. frustumPlane.normalize();
  6588. };
  6589. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6590. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6591. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6592. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6593. frustumPlane.d = transform.m[15] + transform.m[12];
  6594. frustumPlane.normalize();
  6595. };
  6596. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6597. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6598. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6599. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6600. frustumPlane.d = transform.m[15] - transform.m[12];
  6601. frustumPlane.normalize();
  6602. };
  6603. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6604. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6605. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6606. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6607. frustumPlane.d = transform.m[15] - transform.m[13];
  6608. frustumPlane.normalize();
  6609. };
  6610. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6611. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6612. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6613. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6614. frustumPlane.d = transform.m[15] + transform.m[13];
  6615. frustumPlane.normalize();
  6616. };
  6617. /**
  6618. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6619. */
  6620. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6621. // Near
  6622. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6623. // Far
  6624. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6625. // Left
  6626. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6627. // Right
  6628. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6629. // Top
  6630. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6631. // Bottom
  6632. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6633. };
  6634. return Frustum;
  6635. }());
  6636. BABYLON.Frustum = Frustum;
  6637. /** Defines supported spaces */
  6638. var Space;
  6639. (function (Space) {
  6640. /** Local (object) space */
  6641. Space[Space["LOCAL"] = 0] = "LOCAL";
  6642. /** World space */
  6643. Space[Space["WORLD"] = 1] = "WORLD";
  6644. /** Bone space */
  6645. Space[Space["BONE"] = 2] = "BONE";
  6646. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6647. /** Defines the 3 main axes */
  6648. var Axis = /** @class */ (function () {
  6649. function Axis() {
  6650. }
  6651. /** X axis */
  6652. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6653. /** Y axis */
  6654. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6655. /** Z axis */
  6656. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6657. return Axis;
  6658. }());
  6659. BABYLON.Axis = Axis;
  6660. ;
  6661. var BezierCurve = /** @class */ (function () {
  6662. function BezierCurve() {
  6663. }
  6664. /**
  6665. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6666. */
  6667. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6668. // Extract X (which is equal to time here)
  6669. var f0 = 1 - 3 * x2 + 3 * x1;
  6670. var f1 = 3 * x2 - 6 * x1;
  6671. var f2 = 3 * x1;
  6672. var refinedT = t;
  6673. for (var i = 0; i < 5; i++) {
  6674. var refinedT2 = refinedT * refinedT;
  6675. var refinedT3 = refinedT2 * refinedT;
  6676. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6677. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6678. refinedT -= (x - t) * slope;
  6679. refinedT = Math.min(1, Math.max(0, refinedT));
  6680. }
  6681. // Resolve cubic bezier for the given x
  6682. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6683. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6684. Math.pow(refinedT, 3);
  6685. };
  6686. return BezierCurve;
  6687. }());
  6688. BABYLON.BezierCurve = BezierCurve;
  6689. /**
  6690. * Defines potential orientation for back face culling
  6691. */
  6692. var Orientation;
  6693. (function (Orientation) {
  6694. /**
  6695. * Clockwise
  6696. */
  6697. Orientation[Orientation["CW"] = 0] = "CW";
  6698. /** Counter clockwise */
  6699. Orientation[Orientation["CCW"] = 1] = "CCW";
  6700. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6701. var Angle = /** @class */ (function () {
  6702. /**
  6703. * Creates an Angle object of "radians" radians (float).
  6704. */
  6705. function Angle(radians) {
  6706. var _this = this;
  6707. /**
  6708. * Returns the Angle value in degrees (float).
  6709. */
  6710. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6711. /**
  6712. * Returns the Angle value in radians (float).
  6713. */
  6714. this.radians = function () { return _this._radians; };
  6715. this._radians = radians;
  6716. if (this._radians < 0.0)
  6717. this._radians += (2.0 * Math.PI);
  6718. }
  6719. /**
  6720. * Returns a new Angle object valued with the angle value in radians between the two given vectors.
  6721. */
  6722. Angle.BetweenTwoPoints = function (a, b) {
  6723. var delta = b.subtract(a);
  6724. var theta = Math.atan2(delta.y, delta.x);
  6725. return new Angle(theta);
  6726. };
  6727. /**
  6728. * Returns a new Angle object from the given float in radians.
  6729. */
  6730. Angle.FromRadians = function (radians) {
  6731. return new Angle(radians);
  6732. };
  6733. /**
  6734. * Returns a new Angle object from the given float in degrees.
  6735. */
  6736. Angle.FromDegrees = function (degrees) {
  6737. return new Angle(degrees * Math.PI / 180.0);
  6738. };
  6739. return Angle;
  6740. }());
  6741. BABYLON.Angle = Angle;
  6742. var Arc2 = /** @class */ (function () {
  6743. /**
  6744. * Creates an Arc object from the three given points : start, middle and end.
  6745. */
  6746. function Arc2(startPoint, midPoint, endPoint) {
  6747. this.startPoint = startPoint;
  6748. this.midPoint = midPoint;
  6749. this.endPoint = endPoint;
  6750. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6751. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6752. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6753. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6754. 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);
  6755. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6756. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6757. var a1 = this.startAngle.degrees();
  6758. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6759. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6760. // angles correction
  6761. if (a2 - a1 > +180.0)
  6762. a2 -= 360.0;
  6763. if (a2 - a1 < -180.0)
  6764. a2 += 360.0;
  6765. if (a3 - a2 > +180.0)
  6766. a3 -= 360.0;
  6767. if (a3 - a2 < -180.0)
  6768. a3 += 360.0;
  6769. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6770. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6771. }
  6772. return Arc2;
  6773. }());
  6774. BABYLON.Arc2 = Arc2;
  6775. var Path2 = /** @class */ (function () {
  6776. /**
  6777. * Creates a Path2 object from the starting 2D coordinates x and y.
  6778. */
  6779. function Path2(x, y) {
  6780. this._points = new Array();
  6781. this._length = 0.0;
  6782. this.closed = false;
  6783. this._points.push(new Vector2(x, y));
  6784. }
  6785. /**
  6786. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6787. * Returns the updated Path2.
  6788. */
  6789. Path2.prototype.addLineTo = function (x, y) {
  6790. if (this.closed) {
  6791. return this;
  6792. }
  6793. var newPoint = new Vector2(x, y);
  6794. var previousPoint = this._points[this._points.length - 1];
  6795. this._points.push(newPoint);
  6796. this._length += newPoint.subtract(previousPoint).length();
  6797. return this;
  6798. };
  6799. /**
  6800. * 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.
  6801. * Returns the updated Path2.
  6802. */
  6803. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6804. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6805. if (this.closed) {
  6806. return this;
  6807. }
  6808. var startPoint = this._points[this._points.length - 1];
  6809. var midPoint = new Vector2(midX, midY);
  6810. var endPoint = new Vector2(endX, endY);
  6811. var arc = new Arc2(startPoint, midPoint, endPoint);
  6812. var increment = arc.angle.radians() / numberOfSegments;
  6813. if (arc.orientation === Orientation.CW)
  6814. increment *= -1;
  6815. var currentAngle = arc.startAngle.radians() + increment;
  6816. for (var i = 0; i < numberOfSegments; i++) {
  6817. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6818. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6819. this.addLineTo(x, y);
  6820. currentAngle += increment;
  6821. }
  6822. return this;
  6823. };
  6824. /**
  6825. * Closes the Path2.
  6826. * Returns the Path2.
  6827. */
  6828. Path2.prototype.close = function () {
  6829. this.closed = true;
  6830. return this;
  6831. };
  6832. /**
  6833. * Returns the Path2 total length (float).
  6834. */
  6835. Path2.prototype.length = function () {
  6836. var result = this._length;
  6837. if (!this.closed) {
  6838. var lastPoint = this._points[this._points.length - 1];
  6839. var firstPoint = this._points[0];
  6840. result += (firstPoint.subtract(lastPoint).length());
  6841. }
  6842. return result;
  6843. };
  6844. /**
  6845. * Returns the Path2 internal array of points.
  6846. */
  6847. Path2.prototype.getPoints = function () {
  6848. return this._points;
  6849. };
  6850. /**
  6851. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6852. */
  6853. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6854. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6855. return Vector2.Zero();
  6856. }
  6857. var lengthPosition = normalizedLengthPosition * this.length();
  6858. var previousOffset = 0;
  6859. for (var i = 0; i < this._points.length; i++) {
  6860. var j = (i + 1) % this._points.length;
  6861. var a = this._points[i];
  6862. var b = this._points[j];
  6863. var bToA = b.subtract(a);
  6864. var nextOffset = (bToA.length() + previousOffset);
  6865. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6866. var dir = bToA.normalize();
  6867. var localOffset = lengthPosition - previousOffset;
  6868. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6869. }
  6870. previousOffset = nextOffset;
  6871. }
  6872. return Vector2.Zero();
  6873. };
  6874. /**
  6875. * Returns a new Path2 starting at the coordinates (x, y).
  6876. */
  6877. Path2.StartingAt = function (x, y) {
  6878. return new Path2(x, y);
  6879. };
  6880. return Path2;
  6881. }());
  6882. BABYLON.Path2 = Path2;
  6883. var Path3D = /** @class */ (function () {
  6884. /**
  6885. * new Path3D(path, normal, raw)
  6886. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6887. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6888. * path : an array of Vector3, the curve axis of the Path3D
  6889. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6890. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6891. */
  6892. function Path3D(path, firstNormal, raw) {
  6893. if (firstNormal === void 0) { firstNormal = null; }
  6894. this.path = path;
  6895. this._curve = new Array();
  6896. this._distances = new Array();
  6897. this._tangents = new Array();
  6898. this._normals = new Array();
  6899. this._binormals = new Array();
  6900. for (var p = 0; p < path.length; p++) {
  6901. this._curve[p] = path[p].clone(); // hard copy
  6902. }
  6903. this._raw = raw || false;
  6904. this._compute(firstNormal);
  6905. }
  6906. /**
  6907. * Returns the Path3D array of successive Vector3 designing its curve.
  6908. */
  6909. Path3D.prototype.getCurve = function () {
  6910. return this._curve;
  6911. };
  6912. /**
  6913. * Returns an array populated with tangent vectors on each Path3D curve point.
  6914. */
  6915. Path3D.prototype.getTangents = function () {
  6916. return this._tangents;
  6917. };
  6918. /**
  6919. * Returns an array populated with normal vectors on each Path3D curve point.
  6920. */
  6921. Path3D.prototype.getNormals = function () {
  6922. return this._normals;
  6923. };
  6924. /**
  6925. * Returns an array populated with binormal vectors on each Path3D curve point.
  6926. */
  6927. Path3D.prototype.getBinormals = function () {
  6928. return this._binormals;
  6929. };
  6930. /**
  6931. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6932. */
  6933. Path3D.prototype.getDistances = function () {
  6934. return this._distances;
  6935. };
  6936. /**
  6937. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6938. * Returns the same object updated.
  6939. */
  6940. Path3D.prototype.update = function (path, firstNormal) {
  6941. if (firstNormal === void 0) { firstNormal = null; }
  6942. for (var p = 0; p < path.length; p++) {
  6943. this._curve[p].x = path[p].x;
  6944. this._curve[p].y = path[p].y;
  6945. this._curve[p].z = path[p].z;
  6946. }
  6947. this._compute(firstNormal);
  6948. return this;
  6949. };
  6950. // private function compute() : computes tangents, normals and binormals
  6951. Path3D.prototype._compute = function (firstNormal) {
  6952. var l = this._curve.length;
  6953. // first and last tangents
  6954. this._tangents[0] = this._getFirstNonNullVector(0);
  6955. if (!this._raw) {
  6956. this._tangents[0].normalize();
  6957. }
  6958. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6959. if (!this._raw) {
  6960. this._tangents[l - 1].normalize();
  6961. }
  6962. // normals and binormals at first point : arbitrary vector with _normalVector()
  6963. var tg0 = this._tangents[0];
  6964. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6965. this._normals[0] = pp0;
  6966. if (!this._raw) {
  6967. this._normals[0].normalize();
  6968. }
  6969. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6970. if (!this._raw) {
  6971. this._binormals[0].normalize();
  6972. }
  6973. this._distances[0] = 0.0;
  6974. // normals and binormals : next points
  6975. var prev; // previous vector (segment)
  6976. var cur; // current vector (segment)
  6977. var curTang; // current tangent
  6978. // previous normal
  6979. var prevBinor; // previous binormal
  6980. for (var i = 1; i < l; i++) {
  6981. // tangents
  6982. prev = this._getLastNonNullVector(i);
  6983. if (i < l - 1) {
  6984. cur = this._getFirstNonNullVector(i);
  6985. this._tangents[i] = prev.add(cur);
  6986. this._tangents[i].normalize();
  6987. }
  6988. this._distances[i] = this._distances[i - 1] + prev.length();
  6989. // normals and binormals
  6990. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6991. curTang = this._tangents[i];
  6992. prevBinor = this._binormals[i - 1];
  6993. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6994. if (!this._raw) {
  6995. this._normals[i].normalize();
  6996. }
  6997. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6998. if (!this._raw) {
  6999. this._binormals[i].normalize();
  7000. }
  7001. }
  7002. };
  7003. // private function getFirstNonNullVector(index)
  7004. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7005. Path3D.prototype._getFirstNonNullVector = function (index) {
  7006. var i = 1;
  7007. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7008. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7009. i++;
  7010. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7011. }
  7012. return nNVector;
  7013. };
  7014. // private function getLastNonNullVector(index)
  7015. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7016. Path3D.prototype._getLastNonNullVector = function (index) {
  7017. var i = 1;
  7018. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7019. while (nLVector.length() === 0 && index > i + 1) {
  7020. i++;
  7021. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7022. }
  7023. return nLVector;
  7024. };
  7025. // private function normalVector(v0, vt, va) :
  7026. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7027. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7028. Path3D.prototype._normalVector = function (v0, vt, va) {
  7029. var normal0;
  7030. var tgl = vt.length();
  7031. if (tgl === 0.0) {
  7032. tgl = 1.0;
  7033. }
  7034. if (va === undefined || va === null) {
  7035. var point;
  7036. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7037. point = new Vector3(0.0, -1.0, 0.0);
  7038. }
  7039. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7040. point = new Vector3(1.0, 0.0, 0.0);
  7041. }
  7042. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7043. point = new Vector3(0.0, 0.0, 1.0);
  7044. }
  7045. else {
  7046. point = Vector3.Zero();
  7047. }
  7048. normal0 = Vector3.Cross(vt, point);
  7049. }
  7050. else {
  7051. normal0 = Vector3.Cross(vt, va);
  7052. Vector3.CrossToRef(normal0, vt, normal0);
  7053. }
  7054. normal0.normalize();
  7055. return normal0;
  7056. };
  7057. return Path3D;
  7058. }());
  7059. BABYLON.Path3D = Path3D;
  7060. var Curve3 = /** @class */ (function () {
  7061. /**
  7062. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7063. * A Curve3 is designed from a series of successive Vector3.
  7064. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7065. */
  7066. function Curve3(points) {
  7067. this._length = 0.0;
  7068. this._points = points;
  7069. this._length = this._computeLength(points);
  7070. }
  7071. /**
  7072. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7073. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7074. * @param v1 (Vector3) the control point
  7075. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7076. * @param nbPoints (integer) the wanted number of points in the curve
  7077. */
  7078. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7079. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7080. var bez = new Array();
  7081. var equation = function (t, val0, val1, val2) {
  7082. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7083. return res;
  7084. };
  7085. for (var i = 0; i <= nbPoints; i++) {
  7086. 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)));
  7087. }
  7088. return new Curve3(bez);
  7089. };
  7090. /**
  7091. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7092. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7093. * @param v1 (Vector3) the first control point
  7094. * @param v2 (Vector3) the second control point
  7095. * @param v3 (Vector3) the end point of the Cubic Bezier
  7096. * @param nbPoints (integer) the wanted number of points in the curve
  7097. */
  7098. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7099. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7100. var bez = new Array();
  7101. var equation = function (t, val0, val1, val2, val3) {
  7102. 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;
  7103. return res;
  7104. };
  7105. for (var i = 0; i <= nbPoints; i++) {
  7106. 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)));
  7107. }
  7108. return new Curve3(bez);
  7109. };
  7110. /**
  7111. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7112. * @param p1 (Vector3) the origin point of the Hermite Spline
  7113. * @param t1 (Vector3) the tangent vector at the origin point
  7114. * @param p2 (Vector3) the end point of the Hermite Spline
  7115. * @param t2 (Vector3) the tangent vector at the end point
  7116. * @param nbPoints (integer) the wanted number of points in the curve
  7117. */
  7118. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7119. var hermite = new Array();
  7120. var step = 1.0 / nbPoints;
  7121. for (var i = 0; i <= nbPoints; i++) {
  7122. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7123. }
  7124. return new Curve3(hermite);
  7125. };
  7126. /**
  7127. * Returns a Curve3 object along a CatmullRom Spline curve :
  7128. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7129. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7130. */
  7131. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7132. var totalPoints = new Array();
  7133. totalPoints.push(points[0].clone());
  7134. Array.prototype.push.apply(totalPoints, points);
  7135. totalPoints.push(points[points.length - 1].clone());
  7136. var catmullRom = new Array();
  7137. var step = 1.0 / nbPoints;
  7138. var amount = 0.0;
  7139. for (var i = 0; i < totalPoints.length - 3; i++) {
  7140. amount = 0;
  7141. for (var c = 0; c < nbPoints; c++) {
  7142. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7143. amount += step;
  7144. }
  7145. }
  7146. i--;
  7147. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7148. return new Curve3(catmullRom);
  7149. };
  7150. /**
  7151. * Returns the Curve3 stored array of successive Vector3
  7152. */
  7153. Curve3.prototype.getPoints = function () {
  7154. return this._points;
  7155. };
  7156. /**
  7157. * Returns the computed length (float) of the curve.
  7158. */
  7159. Curve3.prototype.length = function () {
  7160. return this._length;
  7161. };
  7162. /**
  7163. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7164. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7165. * curveA and curveB keep unchanged.
  7166. */
  7167. Curve3.prototype.continue = function (curve) {
  7168. var lastPoint = this._points[this._points.length - 1];
  7169. var continuedPoints = this._points.slice();
  7170. var curvePoints = curve.getPoints();
  7171. for (var i = 1; i < curvePoints.length; i++) {
  7172. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7173. }
  7174. var continuedCurve = new Curve3(continuedPoints);
  7175. return continuedCurve;
  7176. };
  7177. Curve3.prototype._computeLength = function (path) {
  7178. var l = 0;
  7179. for (var i = 1; i < path.length; i++) {
  7180. l += (path[i].subtract(path[i - 1])).length();
  7181. }
  7182. return l;
  7183. };
  7184. return Curve3;
  7185. }());
  7186. BABYLON.Curve3 = Curve3;
  7187. // Vertex formats
  7188. var PositionNormalVertex = /** @class */ (function () {
  7189. function PositionNormalVertex(position, normal) {
  7190. if (position === void 0) { position = Vector3.Zero(); }
  7191. if (normal === void 0) { normal = Vector3.Up(); }
  7192. this.position = position;
  7193. this.normal = normal;
  7194. }
  7195. PositionNormalVertex.prototype.clone = function () {
  7196. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7197. };
  7198. return PositionNormalVertex;
  7199. }());
  7200. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7201. var PositionNormalTextureVertex = /** @class */ (function () {
  7202. function PositionNormalTextureVertex(position, normal, uv) {
  7203. if (position === void 0) { position = Vector3.Zero(); }
  7204. if (normal === void 0) { normal = Vector3.Up(); }
  7205. if (uv === void 0) { uv = Vector2.Zero(); }
  7206. this.position = position;
  7207. this.normal = normal;
  7208. this.uv = uv;
  7209. }
  7210. PositionNormalTextureVertex.prototype.clone = function () {
  7211. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7212. };
  7213. return PositionNormalTextureVertex;
  7214. }());
  7215. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7216. // Temporary pre-allocated objects for engine internal use
  7217. // usage in any internal function :
  7218. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7219. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7220. var Tmp = /** @class */ (function () {
  7221. function Tmp() {
  7222. }
  7223. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7224. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7225. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7226. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7227. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7228. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7229. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7230. Matrix.Zero(), Matrix.Zero(),
  7231. Matrix.Zero(), Matrix.Zero(),
  7232. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7233. return Tmp;
  7234. }());
  7235. BABYLON.Tmp = Tmp;
  7236. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7237. var MathTmp = /** @class */ (function () {
  7238. function MathTmp() {
  7239. }
  7240. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7241. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7242. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7243. return MathTmp;
  7244. }());
  7245. })(BABYLON || (BABYLON = {}));
  7246. //# sourceMappingURL=babylon.math.js.map
  7247. var BABYLON;
  7248. (function (BABYLON) {
  7249. var Scalar = /** @class */ (function () {
  7250. function Scalar() {
  7251. }
  7252. /**
  7253. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7254. */
  7255. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7256. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7257. var num = a - b;
  7258. return -epsilon <= num && num <= epsilon;
  7259. };
  7260. /**
  7261. * Returns a string : the upper case translation of the number i to hexadecimal.
  7262. */
  7263. Scalar.ToHex = function (i) {
  7264. var str = i.toString(16);
  7265. if (i <= 15) {
  7266. return ("0" + str).toUpperCase();
  7267. }
  7268. return str.toUpperCase();
  7269. };
  7270. /**
  7271. * Returns -1 if value is negative and +1 is value is positive.
  7272. * Returns the value itself if it's equal to zero.
  7273. */
  7274. Scalar.Sign = function (value) {
  7275. value = +value; // convert to a number
  7276. if (value === 0 || isNaN(value))
  7277. return value;
  7278. return value > 0 ? 1 : -1;
  7279. };
  7280. /**
  7281. * Returns the value itself if it's between min and max.
  7282. * Returns min if the value is lower than min.
  7283. * Returns max if the value is greater than max.
  7284. */
  7285. Scalar.Clamp = function (value, min, max) {
  7286. if (min === void 0) { min = 0; }
  7287. if (max === void 0) { max = 1; }
  7288. return Math.min(max, Math.max(min, value));
  7289. };
  7290. /**
  7291. * Returns the log2 of value.
  7292. */
  7293. Scalar.Log2 = function (value) {
  7294. return Math.log(value) * Math.LOG2E;
  7295. };
  7296. /**
  7297. * Loops the value, so that it is never larger than length and never smaller than 0.
  7298. *
  7299. * This is similar to the modulo operator but it works with floating point numbers.
  7300. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7301. * With t = 5 and length = 2.5, the result would be 0.0.
  7302. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7303. */
  7304. Scalar.Repeat = function (value, length) {
  7305. return value - Math.floor(value / length) * length;
  7306. };
  7307. /**
  7308. * Normalize the value between 0.0 and 1.0 using min and max values
  7309. */
  7310. Scalar.Normalize = function (value, min, max) {
  7311. return (value - min) / (max - min);
  7312. };
  7313. /**
  7314. * Denormalize the value from 0.0 and 1.0 using min and max values
  7315. */
  7316. Scalar.Denormalize = function (normalized, min, max) {
  7317. return (normalized * (max - min) + min);
  7318. };
  7319. /**
  7320. * Calculates the shortest difference between two given angles given in degrees.
  7321. */
  7322. Scalar.DeltaAngle = function (current, target) {
  7323. var num = Scalar.Repeat(target - current, 360.0);
  7324. if (num > 180.0) {
  7325. num -= 360.0;
  7326. }
  7327. return num;
  7328. };
  7329. /**
  7330. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7331. *
  7332. * The returned value will move back and forth between 0 and length
  7333. */
  7334. Scalar.PingPong = function (tx, length) {
  7335. var t = Scalar.Repeat(tx, length * 2.0);
  7336. return length - Math.abs(t - length);
  7337. };
  7338. /**
  7339. * Interpolates between min and max with smoothing at the limits.
  7340. *
  7341. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7342. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7343. */
  7344. Scalar.SmoothStep = function (from, to, tx) {
  7345. var t = Scalar.Clamp(tx);
  7346. t = -2.0 * t * t * t + 3.0 * t * t;
  7347. return to * t + from * (1.0 - t);
  7348. };
  7349. /**
  7350. * Moves a value current towards target.
  7351. *
  7352. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7353. * Negative values of maxDelta pushes the value away from target.
  7354. */
  7355. Scalar.MoveTowards = function (current, target, maxDelta) {
  7356. var result = 0;
  7357. if (Math.abs(target - current) <= maxDelta) {
  7358. result = target;
  7359. }
  7360. else {
  7361. result = current + Scalar.Sign(target - current) * maxDelta;
  7362. }
  7363. return result;
  7364. };
  7365. /**
  7366. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7367. *
  7368. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7369. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7370. */
  7371. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7372. var num = Scalar.DeltaAngle(current, target);
  7373. var result = 0;
  7374. if (-maxDelta < num && num < maxDelta) {
  7375. result = target;
  7376. }
  7377. else {
  7378. target = current + num;
  7379. result = Scalar.MoveTowards(current, target, maxDelta);
  7380. }
  7381. return result;
  7382. };
  7383. /**
  7384. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7385. */
  7386. Scalar.Lerp = function (start, end, amount) {
  7387. return start + ((end - start) * amount);
  7388. };
  7389. /**
  7390. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7391. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7392. */
  7393. Scalar.LerpAngle = function (start, end, amount) {
  7394. var num = Scalar.Repeat(end - start, 360.0);
  7395. if (num > 180.0) {
  7396. num -= 360.0;
  7397. }
  7398. return start + num * Scalar.Clamp(amount);
  7399. };
  7400. /**
  7401. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7402. */
  7403. Scalar.InverseLerp = function (a, b, value) {
  7404. var result = 0;
  7405. if (a != b) {
  7406. result = Scalar.Clamp((value - a) / (b - a));
  7407. }
  7408. else {
  7409. result = 0.0;
  7410. }
  7411. return result;
  7412. };
  7413. /**
  7414. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7415. */
  7416. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7417. var squared = amount * amount;
  7418. var cubed = amount * squared;
  7419. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7420. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7421. var part3 = (cubed - (2.0 * squared)) + amount;
  7422. var part4 = cubed - squared;
  7423. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7424. };
  7425. /**
  7426. * Returns a random float number between and min and max values
  7427. */
  7428. Scalar.RandomRange = function (min, max) {
  7429. if (min === max)
  7430. return min;
  7431. return ((Math.random() * (max - min)) + min);
  7432. };
  7433. /**
  7434. * This function returns percentage of a number in a given range.
  7435. *
  7436. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7437. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7438. */
  7439. Scalar.RangeToPercent = function (number, min, max) {
  7440. return ((number - min) / (max - min));
  7441. };
  7442. /**
  7443. * This function returns number that corresponds to the percentage in a given range.
  7444. *
  7445. * PercentToRange(0.34,0,100) will return 34.
  7446. */
  7447. Scalar.PercentToRange = function (percent, min, max) {
  7448. return ((max - min) * percent + min);
  7449. };
  7450. /**
  7451. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7452. * @param angle The angle to normalize in radian.
  7453. * @return The converted angle.
  7454. */
  7455. Scalar.NormalizeRadians = function (angle) {
  7456. // More precise but slower version kept for reference.
  7457. // angle = angle % Tools.TwoPi;
  7458. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7459. //if (angle > Math.PI) {
  7460. // angle -= Tools.TwoPi;
  7461. //}
  7462. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7463. return angle;
  7464. };
  7465. /**
  7466. * Two pi constants convenient for computation.
  7467. */
  7468. Scalar.TwoPi = Math.PI * 2;
  7469. return Scalar;
  7470. }());
  7471. BABYLON.Scalar = Scalar;
  7472. })(BABYLON || (BABYLON = {}));
  7473. //# sourceMappingURL=babylon.math.scalar.js.map
  7474. //# sourceMappingURL=babylon.mixins.js.map
  7475. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7476. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7477. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7478. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7479. //# sourceMappingURL=babylon.webgl2.js.map
  7480. var BABYLON;
  7481. (function (BABYLON) {
  7482. var __decoratorInitialStore = {};
  7483. var __mergedStore = {};
  7484. var _copySource = function (creationFunction, source, instanciate) {
  7485. var destination = creationFunction();
  7486. // Tags
  7487. if (BABYLON.Tags) {
  7488. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7489. }
  7490. var classStore = getMergedStore(destination);
  7491. // Properties
  7492. for (var property in classStore) {
  7493. var propertyDescriptor = classStore[property];
  7494. var sourceProperty = source[property];
  7495. var propertyType = propertyDescriptor.type;
  7496. if (sourceProperty !== undefined && sourceProperty !== null) {
  7497. switch (propertyType) {
  7498. case 0: // Value
  7499. case 6: // Mesh reference
  7500. case 11: // Camera reference
  7501. destination[property] = sourceProperty;
  7502. break;
  7503. case 1: // Texture
  7504. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7505. break;
  7506. case 2: // Color3
  7507. case 3: // FresnelParameters
  7508. case 4: // Vector2
  7509. case 5: // Vector3
  7510. case 7: // Color Curves
  7511. case 10: // Quaternion
  7512. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7513. break;
  7514. }
  7515. }
  7516. }
  7517. return destination;
  7518. };
  7519. function getDirectStore(target) {
  7520. var classKey = target.getClassName();
  7521. if (!__decoratorInitialStore[classKey]) {
  7522. __decoratorInitialStore[classKey] = {};
  7523. }
  7524. return __decoratorInitialStore[classKey];
  7525. }
  7526. /**
  7527. * Return the list of properties flagged as serializable
  7528. * @param target: host object
  7529. */
  7530. function getMergedStore(target) {
  7531. var classKey = target.getClassName();
  7532. if (__mergedStore[classKey]) {
  7533. return __mergedStore[classKey];
  7534. }
  7535. __mergedStore[classKey] = {};
  7536. var store = __mergedStore[classKey];
  7537. var currentTarget = target;
  7538. var currentKey = classKey;
  7539. while (currentKey) {
  7540. var initialStore = __decoratorInitialStore[currentKey];
  7541. for (var property in initialStore) {
  7542. store[property] = initialStore[property];
  7543. }
  7544. var parent_1 = void 0;
  7545. var done = false;
  7546. do {
  7547. parent_1 = Object.getPrototypeOf(currentTarget);
  7548. if (!parent_1.getClassName) {
  7549. done = true;
  7550. break;
  7551. }
  7552. if (parent_1.getClassName() !== currentKey) {
  7553. break;
  7554. }
  7555. currentTarget = parent_1;
  7556. } while (parent_1);
  7557. if (done) {
  7558. break;
  7559. }
  7560. currentKey = parent_1.getClassName();
  7561. currentTarget = parent_1;
  7562. }
  7563. return store;
  7564. }
  7565. function generateSerializableMember(type, sourceName) {
  7566. return function (target, propertyKey) {
  7567. var classStore = getDirectStore(target);
  7568. if (!classStore[propertyKey]) {
  7569. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7570. }
  7571. };
  7572. }
  7573. function generateExpandMember(setCallback, targetKey) {
  7574. if (targetKey === void 0) { targetKey = null; }
  7575. return function (target, propertyKey) {
  7576. var key = targetKey || ("_" + propertyKey);
  7577. Object.defineProperty(target, propertyKey, {
  7578. get: function () {
  7579. return this[key];
  7580. },
  7581. set: function (value) {
  7582. if (this[key] === value) {
  7583. return;
  7584. }
  7585. this[key] = value;
  7586. target[setCallback].apply(this);
  7587. },
  7588. enumerable: true,
  7589. configurable: true
  7590. });
  7591. };
  7592. }
  7593. function expandToProperty(callback, targetKey) {
  7594. if (targetKey === void 0) { targetKey = null; }
  7595. return generateExpandMember(callback, targetKey);
  7596. }
  7597. BABYLON.expandToProperty = expandToProperty;
  7598. function serialize(sourceName) {
  7599. return generateSerializableMember(0, sourceName); // value member
  7600. }
  7601. BABYLON.serialize = serialize;
  7602. function serializeAsTexture(sourceName) {
  7603. return generateSerializableMember(1, sourceName); // texture member
  7604. }
  7605. BABYLON.serializeAsTexture = serializeAsTexture;
  7606. function serializeAsColor3(sourceName) {
  7607. return generateSerializableMember(2, sourceName); // color3 member
  7608. }
  7609. BABYLON.serializeAsColor3 = serializeAsColor3;
  7610. function serializeAsFresnelParameters(sourceName) {
  7611. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7612. }
  7613. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7614. function serializeAsVector2(sourceName) {
  7615. return generateSerializableMember(4, sourceName); // vector2 member
  7616. }
  7617. BABYLON.serializeAsVector2 = serializeAsVector2;
  7618. function serializeAsVector3(sourceName) {
  7619. return generateSerializableMember(5, sourceName); // vector3 member
  7620. }
  7621. BABYLON.serializeAsVector3 = serializeAsVector3;
  7622. function serializeAsMeshReference(sourceName) {
  7623. return generateSerializableMember(6, sourceName); // mesh reference member
  7624. }
  7625. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7626. function serializeAsColorCurves(sourceName) {
  7627. return generateSerializableMember(7, sourceName); // color curves
  7628. }
  7629. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7630. function serializeAsColor4(sourceName) {
  7631. return generateSerializableMember(8, sourceName); // color 4
  7632. }
  7633. BABYLON.serializeAsColor4 = serializeAsColor4;
  7634. function serializeAsImageProcessingConfiguration(sourceName) {
  7635. return generateSerializableMember(9, sourceName); // image processing
  7636. }
  7637. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7638. function serializeAsQuaternion(sourceName) {
  7639. return generateSerializableMember(10, sourceName); // quaternion member
  7640. }
  7641. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7642. /**
  7643. * Decorator used to define property that can be serialized as reference to a camera
  7644. * @param sourceName defines the name of the property to decorate
  7645. */
  7646. function serializeAsCameraReference(sourceName) {
  7647. return generateSerializableMember(11, sourceName); // camera reference member
  7648. }
  7649. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7650. var SerializationHelper = /** @class */ (function () {
  7651. function SerializationHelper() {
  7652. }
  7653. SerializationHelper.Serialize = function (entity, serializationObject) {
  7654. if (!serializationObject) {
  7655. serializationObject = {};
  7656. }
  7657. // Tags
  7658. if (BABYLON.Tags) {
  7659. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7660. }
  7661. var serializedProperties = getMergedStore(entity);
  7662. // Properties
  7663. for (var property in serializedProperties) {
  7664. var propertyDescriptor = serializedProperties[property];
  7665. var targetPropertyName = propertyDescriptor.sourceName || property;
  7666. var propertyType = propertyDescriptor.type;
  7667. var sourceProperty = entity[property];
  7668. if (sourceProperty !== undefined && sourceProperty !== null) {
  7669. switch (propertyType) {
  7670. case 0: // Value
  7671. serializationObject[targetPropertyName] = sourceProperty;
  7672. break;
  7673. case 1: // Texture
  7674. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7675. break;
  7676. case 2: // Color3
  7677. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7678. break;
  7679. case 3: // FresnelParameters
  7680. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7681. break;
  7682. case 4: // Vector2
  7683. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7684. break;
  7685. case 5: // Vector3
  7686. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7687. break;
  7688. case 6: // Mesh reference
  7689. serializationObject[targetPropertyName] = sourceProperty.id;
  7690. break;
  7691. case 7: // Color Curves
  7692. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7693. break;
  7694. case 8: // Color 4
  7695. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7696. break;
  7697. case 9: // Image Processing
  7698. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7699. break;
  7700. case 10: // Quaternion
  7701. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7702. break;
  7703. case 11: // Camera reference
  7704. serializationObject[targetPropertyName] = sourceProperty.id;
  7705. break;
  7706. }
  7707. }
  7708. }
  7709. return serializationObject;
  7710. };
  7711. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7712. if (rootUrl === void 0) { rootUrl = null; }
  7713. var destination = creationFunction();
  7714. if (!rootUrl) {
  7715. rootUrl = "";
  7716. }
  7717. // Tags
  7718. if (BABYLON.Tags) {
  7719. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7720. }
  7721. var classStore = getMergedStore(destination);
  7722. // Properties
  7723. for (var property in classStore) {
  7724. var propertyDescriptor = classStore[property];
  7725. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7726. var propertyType = propertyDescriptor.type;
  7727. if (sourceProperty !== undefined && sourceProperty !== null) {
  7728. var dest = destination;
  7729. switch (propertyType) {
  7730. case 0: // Value
  7731. dest[property] = sourceProperty;
  7732. break;
  7733. case 1: // Texture
  7734. if (scene) {
  7735. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7736. }
  7737. break;
  7738. case 2: // Color3
  7739. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7740. break;
  7741. case 3: // FresnelParameters
  7742. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7743. break;
  7744. case 4: // Vector2
  7745. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7746. break;
  7747. case 5: // Vector3
  7748. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7749. break;
  7750. case 6: // Mesh reference
  7751. if (scene) {
  7752. dest[property] = scene.getLastMeshByID(sourceProperty);
  7753. }
  7754. break;
  7755. case 7: // Color Curves
  7756. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7757. break;
  7758. case 8: // Color 4
  7759. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7760. break;
  7761. case 9: // Image Processing
  7762. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7763. break;
  7764. case 10: // Quaternion
  7765. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7766. break;
  7767. case 11: // Camera reference
  7768. if (scene) {
  7769. dest[property] = scene.getCameraByID(sourceProperty);
  7770. }
  7771. break;
  7772. }
  7773. }
  7774. }
  7775. return destination;
  7776. };
  7777. SerializationHelper.Clone = function (creationFunction, source) {
  7778. return _copySource(creationFunction, source, false);
  7779. };
  7780. SerializationHelper.Instanciate = function (creationFunction, source) {
  7781. return _copySource(creationFunction, source, true);
  7782. };
  7783. return SerializationHelper;
  7784. }());
  7785. BABYLON.SerializationHelper = SerializationHelper;
  7786. })(BABYLON || (BABYLON = {}));
  7787. //# sourceMappingURL=babylon.decorators.js.map
  7788. var BABYLON;
  7789. (function (BABYLON) {
  7790. /**
  7791. * Wrapper class for promise with external resolve and reject.
  7792. */
  7793. var Deferred = /** @class */ (function () {
  7794. /**
  7795. * Constructor for this deferred object.
  7796. */
  7797. function Deferred() {
  7798. var _this = this;
  7799. this.promise = new Promise(function (resolve, reject) {
  7800. _this._resolve = resolve;
  7801. _this._reject = reject;
  7802. });
  7803. }
  7804. Object.defineProperty(Deferred.prototype, "resolve", {
  7805. /**
  7806. * The resolve method of the promise associated with this deferred object.
  7807. */
  7808. get: function () {
  7809. return this._resolve;
  7810. },
  7811. enumerable: true,
  7812. configurable: true
  7813. });
  7814. Object.defineProperty(Deferred.prototype, "reject", {
  7815. /**
  7816. * The reject method of the promise associated with this deferred object.
  7817. */
  7818. get: function () {
  7819. return this._reject;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. return Deferred;
  7825. }());
  7826. BABYLON.Deferred = Deferred;
  7827. })(BABYLON || (BABYLON = {}));
  7828. //# sourceMappingURL=babylon.deferred.js.map
  7829. var BABYLON;
  7830. (function (BABYLON) {
  7831. /**
  7832. * A class serves as a medium between the observable and its observers
  7833. */
  7834. var EventState = /** @class */ (function () {
  7835. /**
  7836. * Create a new EventState
  7837. * @param mask defines the mask associated with this state
  7838. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7839. * @param target defines the original target of the state
  7840. * @param currentTarget defines the current target of the state
  7841. */
  7842. function EventState(mask, skipNextObservers, target, currentTarget) {
  7843. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7844. this.initalize(mask, skipNextObservers, target, currentTarget);
  7845. }
  7846. /**
  7847. * Initialize the current event state
  7848. * @param mask defines the mask associated with this state
  7849. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7850. * @param target defines the original target of the state
  7851. * @param currentTarget defines the current target of the state
  7852. * @returns the current event state
  7853. */
  7854. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7855. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7856. this.mask = mask;
  7857. this.skipNextObservers = skipNextObservers;
  7858. this.target = target;
  7859. this.currentTarget = currentTarget;
  7860. return this;
  7861. };
  7862. return EventState;
  7863. }());
  7864. BABYLON.EventState = EventState;
  7865. /**
  7866. * Represent an Observer registered to a given Observable object.
  7867. */
  7868. var Observer = /** @class */ (function () {
  7869. /**
  7870. * Creates a new observer
  7871. * @param callback defines the callback to call when the observer is notified
  7872. * @param mask defines the mask of the observer (used to filter notifications)
  7873. * @param scope defines the current scope used to restore the JS context
  7874. */
  7875. function Observer(
  7876. /**
  7877. * Defines the callback to call when the observer is notified
  7878. */
  7879. callback,
  7880. /**
  7881. * Defines the mask of the observer (used to filter notifications)
  7882. */
  7883. mask,
  7884. /**
  7885. * Defines the current scope used to restore the JS context
  7886. */
  7887. scope) {
  7888. if (scope === void 0) { scope = null; }
  7889. this.callback = callback;
  7890. this.mask = mask;
  7891. this.scope = scope;
  7892. /** @ignore */
  7893. this._willBeUnregistered = false;
  7894. /**
  7895. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7896. */
  7897. this.unregisterOnNextCall = false;
  7898. }
  7899. return Observer;
  7900. }());
  7901. BABYLON.Observer = Observer;
  7902. /**
  7903. * Represent a list of observers registered to multiple Observables object.
  7904. */
  7905. var MultiObserver = /** @class */ (function () {
  7906. function MultiObserver() {
  7907. }
  7908. /**
  7909. * Release associated resources
  7910. */
  7911. MultiObserver.prototype.dispose = function () {
  7912. if (this._observers && this._observables) {
  7913. for (var index = 0; index < this._observers.length; index++) {
  7914. this._observables[index].remove(this._observers[index]);
  7915. }
  7916. }
  7917. this._observers = null;
  7918. this._observables = null;
  7919. };
  7920. /**
  7921. * Raise a callback when one of the observable will notify
  7922. * @param observables defines a list of observables to watch
  7923. * @param callback defines the callback to call on notification
  7924. * @param mask defines the mask used to filter notifications
  7925. * @param scope defines the current scope used to restore the JS context
  7926. * @returns the new MultiObserver
  7927. */
  7928. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7929. if (mask === void 0) { mask = -1; }
  7930. if (scope === void 0) { scope = null; }
  7931. var result = new MultiObserver();
  7932. result._observers = new Array();
  7933. result._observables = observables;
  7934. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7935. var observable = observables_1[_i];
  7936. var observer = observable.add(callback, mask, false, scope);
  7937. if (observer) {
  7938. result._observers.push(observer);
  7939. }
  7940. }
  7941. return result;
  7942. };
  7943. return MultiObserver;
  7944. }());
  7945. BABYLON.MultiObserver = MultiObserver;
  7946. /**
  7947. * The Observable class is a simple implementation of the Observable pattern.
  7948. *
  7949. * 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.
  7950. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7951. * 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).
  7952. * 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.
  7953. */
  7954. var Observable = /** @class */ (function () {
  7955. /**
  7956. * Creates a new observable
  7957. * @param onObserverAdded defines a callback to call when a new observer is added
  7958. */
  7959. function Observable(onObserverAdded) {
  7960. this._observers = new Array();
  7961. this._eventState = new EventState(0);
  7962. if (onObserverAdded) {
  7963. this._onObserverAdded = onObserverAdded;
  7964. }
  7965. }
  7966. /**
  7967. * Create a new Observer with the specified callback
  7968. * @param callback the callback that will be executed for that Observer
  7969. * @param mask the mask used to filter observers
  7970. * @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.
  7971. * @param scope optional scope for the callback to be called from
  7972. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7973. * @returns the new observer created for the callback
  7974. */
  7975. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7976. if (mask === void 0) { mask = -1; }
  7977. if (insertFirst === void 0) { insertFirst = false; }
  7978. if (scope === void 0) { scope = null; }
  7979. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7980. if (!callback) {
  7981. return null;
  7982. }
  7983. var observer = new Observer(callback, mask, scope);
  7984. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7985. if (insertFirst) {
  7986. this._observers.unshift(observer);
  7987. }
  7988. else {
  7989. this._observers.push(observer);
  7990. }
  7991. if (this._onObserverAdded) {
  7992. this._onObserverAdded(observer);
  7993. }
  7994. return observer;
  7995. };
  7996. /**
  7997. * Remove an Observer from the Observable object
  7998. * @param observer the instance of the Observer to remove
  7999. * @returns false if it doesn't belong to this Observable
  8000. */
  8001. Observable.prototype.remove = function (observer) {
  8002. if (!observer) {
  8003. return false;
  8004. }
  8005. var index = this._observers.indexOf(observer);
  8006. if (index !== -1) {
  8007. this._observers.splice(index, 1);
  8008. return true;
  8009. }
  8010. return false;
  8011. };
  8012. /**
  8013. * Remove a callback from the Observable object
  8014. * @param callback the callback to remove
  8015. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8016. * @returns false if it doesn't belong to this Observable
  8017. */
  8018. Observable.prototype.removeCallback = function (callback, scope) {
  8019. for (var index = 0; index < this._observers.length; index++) {
  8020. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8021. this._observers.splice(index, 1);
  8022. return true;
  8023. }
  8024. }
  8025. return false;
  8026. };
  8027. Observable.prototype._deferUnregister = function (observer) {
  8028. var _this = this;
  8029. observer.unregisterOnNextCall = false;
  8030. observer._willBeUnregistered = true;
  8031. BABYLON.Tools.SetImmediate(function () {
  8032. _this.remove(observer);
  8033. });
  8034. };
  8035. /**
  8036. * Notify all Observers by calling their respective callback with the given data
  8037. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8038. * @param eventData defines the data to send to all observers
  8039. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8040. * @param target defines the original target of the state
  8041. * @param currentTarget defines the current target of the state
  8042. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8043. */
  8044. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8045. if (mask === void 0) { mask = -1; }
  8046. if (!this._observers.length) {
  8047. return true;
  8048. }
  8049. var state = this._eventState;
  8050. state.mask = mask;
  8051. state.target = target;
  8052. state.currentTarget = currentTarget;
  8053. state.skipNextObservers = false;
  8054. state.lastReturnValue = eventData;
  8055. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8056. var obs = _a[_i];
  8057. if (obs._willBeUnregistered) {
  8058. continue;
  8059. }
  8060. if (obs.mask & mask) {
  8061. if (obs.scope) {
  8062. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8063. }
  8064. else {
  8065. state.lastReturnValue = obs.callback(eventData, state);
  8066. }
  8067. if (obs.unregisterOnNextCall) {
  8068. this._deferUnregister(obs);
  8069. }
  8070. }
  8071. if (state.skipNextObservers) {
  8072. return false;
  8073. }
  8074. }
  8075. return true;
  8076. };
  8077. /**
  8078. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8079. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8080. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8081. * and it is crucial that all callbacks will be executed.
  8082. * The order of the callbacks is kept, callbacks are not executed parallel.
  8083. *
  8084. * @param eventData The data to be sent to each callback
  8085. * @param mask is used to filter observers defaults to -1
  8086. * @param target defines the callback target (see EventState)
  8087. * @param currentTarget defines he current object in the bubbling phase
  8088. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8089. */
  8090. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8091. var _this = this;
  8092. if (mask === void 0) { mask = -1; }
  8093. // create an empty promise
  8094. var p = Promise.resolve(eventData);
  8095. // no observers? return this promise.
  8096. if (!this._observers.length) {
  8097. return p;
  8098. }
  8099. var state = this._eventState;
  8100. state.mask = mask;
  8101. state.target = target;
  8102. state.currentTarget = currentTarget;
  8103. state.skipNextObservers = false;
  8104. // execute one callback after another (not using Promise.all, the order is important)
  8105. this._observers.forEach(function (obs) {
  8106. if (state.skipNextObservers) {
  8107. return;
  8108. }
  8109. if (obs._willBeUnregistered) {
  8110. return;
  8111. }
  8112. if (obs.mask & mask) {
  8113. if (obs.scope) {
  8114. p = p.then(function (lastReturnedValue) {
  8115. state.lastReturnValue = lastReturnedValue;
  8116. return obs.callback.apply(obs.scope, [eventData, state]);
  8117. });
  8118. }
  8119. else {
  8120. p = p.then(function (lastReturnedValue) {
  8121. state.lastReturnValue = lastReturnedValue;
  8122. return obs.callback(eventData, state);
  8123. });
  8124. }
  8125. if (obs.unregisterOnNextCall) {
  8126. _this._deferUnregister(obs);
  8127. }
  8128. }
  8129. });
  8130. // return the eventData
  8131. return p.then(function () { return eventData; });
  8132. };
  8133. /**
  8134. * Notify a specific observer
  8135. * @param observer defines the observer to notify
  8136. * @param eventData defines the data to be sent to each callback
  8137. * @param mask is used to filter observers defaults to -1
  8138. */
  8139. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8140. if (mask === void 0) { mask = -1; }
  8141. var state = this._eventState;
  8142. state.mask = mask;
  8143. state.skipNextObservers = false;
  8144. observer.callback(eventData, state);
  8145. };
  8146. /**
  8147. * Gets a boolean indicating if the observable has at least one observer
  8148. * @returns true is the Observable has at least one Observer registered
  8149. */
  8150. Observable.prototype.hasObservers = function () {
  8151. return this._observers.length > 0;
  8152. };
  8153. /**
  8154. * Clear the list of observers
  8155. */
  8156. Observable.prototype.clear = function () {
  8157. this._observers = new Array();
  8158. this._onObserverAdded = null;
  8159. };
  8160. /**
  8161. * Clone the current observable
  8162. * @returns a new observable
  8163. */
  8164. Observable.prototype.clone = function () {
  8165. var result = new Observable();
  8166. result._observers = this._observers.slice(0);
  8167. return result;
  8168. };
  8169. /**
  8170. * Does this observable handles observer registered with a given mask
  8171. * @param mask defines the mask to be tested
  8172. * @return whether or not one observer registered with the given mask is handeled
  8173. **/
  8174. Observable.prototype.hasSpecificMask = function (mask) {
  8175. if (mask === void 0) { mask = -1; }
  8176. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8177. var obs = _a[_i];
  8178. if (obs.mask & mask || obs.mask === mask) {
  8179. return true;
  8180. }
  8181. }
  8182. return false;
  8183. };
  8184. return Observable;
  8185. }());
  8186. BABYLON.Observable = Observable;
  8187. })(BABYLON || (BABYLON = {}));
  8188. //# sourceMappingURL=babylon.observable.js.map
  8189. var BABYLON;
  8190. (function (BABYLON) {
  8191. var SmartArray = /** @class */ (function () {
  8192. function SmartArray(capacity) {
  8193. this.length = 0;
  8194. this.data = new Array(capacity);
  8195. this._id = SmartArray._GlobalId++;
  8196. }
  8197. SmartArray.prototype.push = function (value) {
  8198. this.data[this.length++] = value;
  8199. if (this.length > this.data.length) {
  8200. this.data.length *= 2;
  8201. }
  8202. };
  8203. SmartArray.prototype.forEach = function (func) {
  8204. for (var index = 0; index < this.length; index++) {
  8205. func(this.data[index]);
  8206. }
  8207. };
  8208. SmartArray.prototype.sort = function (compareFn) {
  8209. this.data.sort(compareFn);
  8210. };
  8211. SmartArray.prototype.reset = function () {
  8212. this.length = 0;
  8213. };
  8214. SmartArray.prototype.dispose = function () {
  8215. this.reset();
  8216. if (this.data) {
  8217. this.data.length = 0;
  8218. this.data = [];
  8219. }
  8220. };
  8221. SmartArray.prototype.concat = function (array) {
  8222. if (array.length === 0) {
  8223. return;
  8224. }
  8225. if (this.length + array.length > this.data.length) {
  8226. this.data.length = (this.length + array.length) * 2;
  8227. }
  8228. for (var index = 0; index < array.length; index++) {
  8229. this.data[this.length++] = (array.data || array)[index];
  8230. }
  8231. };
  8232. SmartArray.prototype.indexOf = function (value) {
  8233. var position = this.data.indexOf(value);
  8234. if (position >= this.length) {
  8235. return -1;
  8236. }
  8237. return position;
  8238. };
  8239. SmartArray.prototype.contains = function (value) {
  8240. return this.data.indexOf(value) !== -1;
  8241. };
  8242. // Statics
  8243. SmartArray._GlobalId = 0;
  8244. return SmartArray;
  8245. }());
  8246. BABYLON.SmartArray = SmartArray;
  8247. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8248. __extends(SmartArrayNoDuplicate, _super);
  8249. function SmartArrayNoDuplicate() {
  8250. var _this = _super !== null && _super.apply(this, arguments) || this;
  8251. _this._duplicateId = 0;
  8252. return _this;
  8253. }
  8254. SmartArrayNoDuplicate.prototype.push = function (value) {
  8255. _super.prototype.push.call(this, value);
  8256. if (!value.__smartArrayFlags) {
  8257. value.__smartArrayFlags = {};
  8258. }
  8259. value.__smartArrayFlags[this._id] = this._duplicateId;
  8260. };
  8261. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8262. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8263. return false;
  8264. }
  8265. this.push(value);
  8266. return true;
  8267. };
  8268. SmartArrayNoDuplicate.prototype.reset = function () {
  8269. _super.prototype.reset.call(this);
  8270. this._duplicateId++;
  8271. };
  8272. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8273. if (array.length === 0) {
  8274. return;
  8275. }
  8276. if (this.length + array.length > this.data.length) {
  8277. this.data.length = (this.length + array.length) * 2;
  8278. }
  8279. for (var index = 0; index < array.length; index++) {
  8280. var item = (array.data || array)[index];
  8281. this.pushNoDuplicate(item);
  8282. }
  8283. };
  8284. return SmartArrayNoDuplicate;
  8285. }(SmartArray));
  8286. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8287. })(BABYLON || (BABYLON = {}));
  8288. //# sourceMappingURL=babylon.smartArray.js.map
  8289. var BABYLON;
  8290. (function (BABYLON) {
  8291. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8292. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8293. var LoadFileError = /** @class */ (function (_super) {
  8294. __extends(LoadFileError, _super);
  8295. function LoadFileError(message, request) {
  8296. var _this = _super.call(this, message) || this;
  8297. _this.request = request;
  8298. _this.name = "LoadFileError";
  8299. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8300. return _this;
  8301. }
  8302. // Polyfill for Object.setPrototypeOf if necessary.
  8303. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8304. return LoadFileError;
  8305. }(Error));
  8306. BABYLON.LoadFileError = LoadFileError;
  8307. var RetryStrategy = /** @class */ (function () {
  8308. function RetryStrategy() {
  8309. }
  8310. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8311. if (maxRetries === void 0) { maxRetries = 3; }
  8312. if (baseInterval === void 0) { baseInterval = 500; }
  8313. return function (url, request, retryIndex) {
  8314. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8315. return -1;
  8316. }
  8317. return Math.pow(2, retryIndex) * baseInterval;
  8318. };
  8319. };
  8320. return RetryStrategy;
  8321. }());
  8322. BABYLON.RetryStrategy = RetryStrategy;
  8323. // Screenshots
  8324. var screenshotCanvas;
  8325. var cloneValue = function (source, destinationObject) {
  8326. if (!source)
  8327. return null;
  8328. if (source instanceof BABYLON.Mesh) {
  8329. return null;
  8330. }
  8331. if (source instanceof BABYLON.SubMesh) {
  8332. return source.clone(destinationObject);
  8333. }
  8334. else if (source.clone) {
  8335. return source.clone();
  8336. }
  8337. return null;
  8338. };
  8339. var Tools = /** @class */ (function () {
  8340. function Tools() {
  8341. }
  8342. /**
  8343. * Interpolates between a and b via alpha
  8344. * @param a The lower value (returned when alpha = 0)
  8345. * @param b The upper value (returned when alpha = 1)
  8346. * @param alpha The interpolation-factor
  8347. * @return The mixed value
  8348. */
  8349. Tools.Mix = function (a, b, alpha) {
  8350. return a * (1 - alpha) + b * alpha;
  8351. };
  8352. Tools.Instantiate = function (className) {
  8353. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8354. return Tools.RegisteredExternalClasses[className];
  8355. }
  8356. var arr = className.split(".");
  8357. var fn = (window || this);
  8358. for (var i = 0, len = arr.length; i < len; i++) {
  8359. fn = fn[arr[i]];
  8360. }
  8361. if (typeof fn !== "function") {
  8362. return null;
  8363. }
  8364. return fn;
  8365. };
  8366. /**
  8367. * Provides a slice function that will work even on IE
  8368. * @param data defines the array to slice
  8369. * @param start defines the start of the data (optional)
  8370. * @param end defines the end of the data (optional)
  8371. * @returns the new sliced array
  8372. */
  8373. Tools.Slice = function (data, start, end) {
  8374. if (data.slice) {
  8375. return data.slice(start, end);
  8376. }
  8377. return Array.prototype.slice.call(data, start, end);
  8378. };
  8379. Tools.SetImmediate = function (action) {
  8380. if (window.setImmediate) {
  8381. window.setImmediate(action);
  8382. }
  8383. else {
  8384. setTimeout(action, 1);
  8385. }
  8386. };
  8387. Tools.IsExponentOfTwo = function (value) {
  8388. var count = 1;
  8389. do {
  8390. count *= 2;
  8391. } while (count < value);
  8392. return count === value;
  8393. };
  8394. /**
  8395. * Find the next highest power of two.
  8396. * @param x Number to start search from.
  8397. * @return Next highest power of two.
  8398. */
  8399. Tools.CeilingPOT = function (x) {
  8400. x--;
  8401. x |= x >> 1;
  8402. x |= x >> 2;
  8403. x |= x >> 4;
  8404. x |= x >> 8;
  8405. x |= x >> 16;
  8406. x++;
  8407. return x;
  8408. };
  8409. /**
  8410. * Find the next lowest power of two.
  8411. * @param x Number to start search from.
  8412. * @return Next lowest power of two.
  8413. */
  8414. Tools.FloorPOT = function (x) {
  8415. x = x | (x >> 1);
  8416. x = x | (x >> 2);
  8417. x = x | (x >> 4);
  8418. x = x | (x >> 8);
  8419. x = x | (x >> 16);
  8420. return x - (x >> 1);
  8421. };
  8422. /**
  8423. * Find the nearest power of two.
  8424. * @param x Number to start search from.
  8425. * @return Next nearest power of two.
  8426. */
  8427. Tools.NearestPOT = function (x) {
  8428. var c = Tools.CeilingPOT(x);
  8429. var f = Tools.FloorPOT(x);
  8430. return (c - x) > (x - f) ? f : c;
  8431. };
  8432. Tools.GetExponentOfTwo = function (value, max, mode) {
  8433. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8434. var pot;
  8435. switch (mode) {
  8436. case BABYLON.Engine.SCALEMODE_FLOOR:
  8437. pot = Tools.FloorPOT(value);
  8438. break;
  8439. case BABYLON.Engine.SCALEMODE_NEAREST:
  8440. pot = Tools.NearestPOT(value);
  8441. break;
  8442. case BABYLON.Engine.SCALEMODE_CEILING:
  8443. default:
  8444. pot = Tools.CeilingPOT(value);
  8445. break;
  8446. }
  8447. return Math.min(pot, max);
  8448. };
  8449. Tools.GetFilename = function (path) {
  8450. var index = path.lastIndexOf("/");
  8451. if (index < 0)
  8452. return path;
  8453. return path.substring(index + 1);
  8454. };
  8455. /**
  8456. * Extracts the "folder" part of a path (everything before the filename).
  8457. * @param uri The URI to extract the info from
  8458. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8459. * @returns The "folder" part of the path
  8460. */
  8461. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8462. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8463. var index = uri.lastIndexOf("/");
  8464. if (index < 0) {
  8465. if (returnUnchangedIfNoSlash) {
  8466. return uri;
  8467. }
  8468. return "";
  8469. }
  8470. return uri.substring(0, index + 1);
  8471. };
  8472. Tools.GetDOMTextContent = function (element) {
  8473. var result = "";
  8474. var child = element.firstChild;
  8475. while (child) {
  8476. if (child.nodeType === 3) {
  8477. result += child.textContent;
  8478. }
  8479. child = child.nextSibling;
  8480. }
  8481. return result;
  8482. };
  8483. Tools.ToDegrees = function (angle) {
  8484. return angle * 180 / Math.PI;
  8485. };
  8486. Tools.ToRadians = function (angle) {
  8487. return angle * Math.PI / 180;
  8488. };
  8489. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8490. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8491. var output = "";
  8492. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8493. var i = 0;
  8494. var bytes = new Uint8Array(buffer);
  8495. while (i < bytes.length) {
  8496. chr1 = bytes[i++];
  8497. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8498. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8499. enc1 = chr1 >> 2;
  8500. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8501. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8502. enc4 = chr3 & 63;
  8503. if (isNaN(chr2)) {
  8504. enc3 = enc4 = 64;
  8505. }
  8506. else if (isNaN(chr3)) {
  8507. enc4 = 64;
  8508. }
  8509. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8510. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8511. }
  8512. return "data:image/png;base64," + output;
  8513. };
  8514. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8515. if (bias === void 0) { bias = null; }
  8516. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8517. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8518. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8519. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8520. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8521. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8522. }
  8523. if (bias) {
  8524. minimum.x -= minimum.x * bias.x + bias.y;
  8525. minimum.y -= minimum.y * bias.x + bias.y;
  8526. minimum.z -= minimum.z * bias.x + bias.y;
  8527. maximum.x += maximum.x * bias.x + bias.y;
  8528. maximum.y += maximum.y * bias.x + bias.y;
  8529. maximum.z += maximum.z * bias.x + bias.y;
  8530. }
  8531. return {
  8532. minimum: minimum,
  8533. maximum: maximum
  8534. };
  8535. };
  8536. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8537. if (bias === void 0) { bias = null; }
  8538. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8539. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8540. if (!stride) {
  8541. stride = 3;
  8542. }
  8543. for (var index = start; index < start + count; index++) {
  8544. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8545. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8546. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8547. }
  8548. if (bias) {
  8549. minimum.x -= minimum.x * bias.x + bias.y;
  8550. minimum.y -= minimum.y * bias.x + bias.y;
  8551. minimum.z -= minimum.z * bias.x + bias.y;
  8552. maximum.x += maximum.x * bias.x + bias.y;
  8553. maximum.y += maximum.y * bias.x + bias.y;
  8554. maximum.z += maximum.z * bias.x + bias.y;
  8555. }
  8556. return {
  8557. minimum: minimum,
  8558. maximum: maximum
  8559. };
  8560. };
  8561. Tools.Vector2ArrayFeeder = function (array) {
  8562. return function (index) {
  8563. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8564. var length = isFloatArray ? array.length / 2 : array.length;
  8565. if (index >= length) {
  8566. return null;
  8567. }
  8568. if (isFloatArray) {
  8569. var fa = array;
  8570. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8571. }
  8572. var a = array;
  8573. return a[index];
  8574. };
  8575. };
  8576. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8577. if (bias === void 0) { bias = null; }
  8578. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8579. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8580. var i = 0;
  8581. var cur = feeder(i++);
  8582. while (cur) {
  8583. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8584. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8585. cur = feeder(i++);
  8586. }
  8587. if (bias) {
  8588. minimum.x -= minimum.x * bias.x + bias.y;
  8589. minimum.y -= minimum.y * bias.x + bias.y;
  8590. maximum.x += maximum.x * bias.x + bias.y;
  8591. maximum.y += maximum.y * bias.x + bias.y;
  8592. }
  8593. return {
  8594. minimum: minimum,
  8595. maximum: maximum
  8596. };
  8597. };
  8598. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8599. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8600. return null;
  8601. return Array.isArray(obj) ? obj : [obj];
  8602. };
  8603. // Misc.
  8604. Tools.GetPointerPrefix = function () {
  8605. var eventPrefix = "pointer";
  8606. // Check if pointer events are supported
  8607. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8608. eventPrefix = "mouse";
  8609. }
  8610. return eventPrefix;
  8611. };
  8612. /**
  8613. * @param func - the function to be called
  8614. * @param requester - the object that will request the next frame. Falls back to window.
  8615. */
  8616. Tools.QueueNewFrame = function (func, requester) {
  8617. if (!Tools.IsWindowObjectExist()) {
  8618. return setTimeout(func, 16);
  8619. }
  8620. if (!requester) {
  8621. requester = window;
  8622. }
  8623. if (requester.requestAnimationFrame) {
  8624. return requester.requestAnimationFrame(func);
  8625. }
  8626. else if (requester.msRequestAnimationFrame) {
  8627. return requester.msRequestAnimationFrame(func);
  8628. }
  8629. else if (requester.webkitRequestAnimationFrame) {
  8630. return requester.webkitRequestAnimationFrame(func);
  8631. }
  8632. else if (requester.mozRequestAnimationFrame) {
  8633. return requester.mozRequestAnimationFrame(func);
  8634. }
  8635. else if (requester.oRequestAnimationFrame) {
  8636. return requester.oRequestAnimationFrame(func);
  8637. }
  8638. else {
  8639. return window.setTimeout(func, 16);
  8640. }
  8641. };
  8642. Tools.RequestFullscreen = function (element) {
  8643. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8644. if (!requestFunction)
  8645. return;
  8646. requestFunction.call(element);
  8647. };
  8648. Tools.ExitFullscreen = function () {
  8649. if (document.exitFullscreen) {
  8650. document.exitFullscreen();
  8651. }
  8652. else if (document.mozCancelFullScreen) {
  8653. document.mozCancelFullScreen();
  8654. }
  8655. else if (document.webkitCancelFullScreen) {
  8656. document.webkitCancelFullScreen();
  8657. }
  8658. else if (document.msCancelFullScreen) {
  8659. document.msCancelFullScreen();
  8660. }
  8661. };
  8662. Tools.SetCorsBehavior = function (url, element) {
  8663. if (url && url.indexOf("data:") === 0) {
  8664. return;
  8665. }
  8666. if (Tools.CorsBehavior) {
  8667. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8668. element.crossOrigin = Tools.CorsBehavior;
  8669. }
  8670. else {
  8671. var result = Tools.CorsBehavior(url);
  8672. if (result) {
  8673. element.crossOrigin = result;
  8674. }
  8675. }
  8676. }
  8677. };
  8678. // External files
  8679. Tools.CleanUrl = function (url) {
  8680. url = url.replace(/#/mg, "%23");
  8681. return url;
  8682. };
  8683. Tools.LoadImage = function (url, onLoad, onError, database) {
  8684. if (url instanceof ArrayBuffer) {
  8685. url = Tools.EncodeArrayBufferTobase64(url);
  8686. }
  8687. url = Tools.CleanUrl(url);
  8688. url = Tools.PreprocessUrl(url);
  8689. var img = new Image();
  8690. Tools.SetCorsBehavior(url, img);
  8691. var loadHandler = function () {
  8692. img.removeEventListener("load", loadHandler);
  8693. img.removeEventListener("error", errorHandler);
  8694. onLoad(img);
  8695. };
  8696. var errorHandler = function (err) {
  8697. img.removeEventListener("load", loadHandler);
  8698. img.removeEventListener("error", errorHandler);
  8699. Tools.Error("Error while trying to load image: " + url);
  8700. if (onError) {
  8701. onError("Error while trying to load image: " + url, err);
  8702. }
  8703. };
  8704. img.addEventListener("load", loadHandler);
  8705. img.addEventListener("error", errorHandler);
  8706. var noIndexedDB = function () {
  8707. img.src = url;
  8708. };
  8709. var loadFromIndexedDB = function () {
  8710. if (database) {
  8711. database.loadImageFromDB(url, img);
  8712. }
  8713. };
  8714. //ANY database to do!
  8715. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8716. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8717. }
  8718. else {
  8719. if (url.indexOf("file:") !== -1) {
  8720. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8721. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8722. try {
  8723. var blobURL;
  8724. try {
  8725. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8726. }
  8727. catch (ex) {
  8728. // Chrome doesn't support oneTimeOnly parameter
  8729. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8730. }
  8731. img.src = blobURL;
  8732. }
  8733. catch (e) {
  8734. img.src = "";
  8735. }
  8736. return img;
  8737. }
  8738. }
  8739. noIndexedDB();
  8740. }
  8741. return img;
  8742. };
  8743. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8744. url = Tools.CleanUrl(url);
  8745. url = Tools.PreprocessUrl(url);
  8746. // If file and file input are set
  8747. if (url.indexOf("file:") !== -1) {
  8748. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8749. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8750. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8751. }
  8752. }
  8753. var loadUrl = Tools.BaseUrl + url;
  8754. var aborted = false;
  8755. var fileRequest = {
  8756. onCompleteObservable: new BABYLON.Observable(),
  8757. abort: function () { return aborted = true; },
  8758. };
  8759. var requestFile = function () {
  8760. var request = new XMLHttpRequest();
  8761. var retryHandle = null;
  8762. fileRequest.abort = function () {
  8763. aborted = true;
  8764. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8765. request.abort();
  8766. }
  8767. if (retryHandle !== null) {
  8768. clearTimeout(retryHandle);
  8769. retryHandle = null;
  8770. }
  8771. };
  8772. var retryLoop = function (retryIndex) {
  8773. request.open('GET', loadUrl, true);
  8774. if (useArrayBuffer) {
  8775. request.responseType = "arraybuffer";
  8776. }
  8777. if (onProgress) {
  8778. request.addEventListener("progress", onProgress);
  8779. }
  8780. var onLoadEnd = function () {
  8781. request.removeEventListener("loadend", onLoadEnd);
  8782. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8783. fileRequest.onCompleteObservable.clear();
  8784. };
  8785. request.addEventListener("loadend", onLoadEnd);
  8786. var onReadyStateChange = function () {
  8787. if (aborted) {
  8788. return;
  8789. }
  8790. // In case of undefined state in some browsers.
  8791. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8792. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8793. request.removeEventListener("readystatechange", onReadyStateChange);
  8794. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8795. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8796. return;
  8797. }
  8798. var retryStrategy = Tools.DefaultRetryStrategy;
  8799. if (retryStrategy) {
  8800. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8801. if (waitTime !== -1) {
  8802. // Prevent the request from completing for retry.
  8803. request.removeEventListener("loadend", onLoadEnd);
  8804. request = new XMLHttpRequest();
  8805. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8806. return;
  8807. }
  8808. }
  8809. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8810. if (onError) {
  8811. onError(request, e);
  8812. }
  8813. else {
  8814. throw e;
  8815. }
  8816. }
  8817. };
  8818. request.addEventListener("readystatechange", onReadyStateChange);
  8819. request.send();
  8820. };
  8821. retryLoop(0);
  8822. };
  8823. // Caching all files
  8824. if (database && database.enableSceneOffline) {
  8825. var noIndexedDB_1 = function () {
  8826. if (!aborted) {
  8827. requestFile();
  8828. }
  8829. };
  8830. var loadFromIndexedDB = function () {
  8831. // TODO: database needs to support aborting and should return a IFileRequest
  8832. if (aborted) {
  8833. return;
  8834. }
  8835. if (database) {
  8836. database.loadFileFromDB(url, function (data) {
  8837. if (!aborted) {
  8838. onSuccess(data);
  8839. }
  8840. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8841. }, onProgress ? function (event) {
  8842. if (!aborted) {
  8843. onProgress(event);
  8844. }
  8845. } : undefined, noIndexedDB_1, useArrayBuffer);
  8846. }
  8847. };
  8848. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8849. }
  8850. else {
  8851. requestFile();
  8852. }
  8853. return fileRequest;
  8854. };
  8855. /**
  8856. * Load a script (identified by an url). When the url returns, the
  8857. * content of this file is added into a new script element, attached to the DOM (body element)
  8858. */
  8859. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8860. var head = document.getElementsByTagName('head')[0];
  8861. var script = document.createElement('script');
  8862. script.type = 'text/javascript';
  8863. script.src = scriptUrl;
  8864. script.onload = function () {
  8865. if (onSuccess) {
  8866. onSuccess();
  8867. }
  8868. };
  8869. script.onerror = function (e) {
  8870. if (onError) {
  8871. onError("Unable to load script '" + scriptUrl + "'", e);
  8872. }
  8873. };
  8874. head.appendChild(script);
  8875. };
  8876. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8877. var reader = new FileReader();
  8878. var request = {
  8879. onCompleteObservable: new BABYLON.Observable(),
  8880. abort: function () { return reader.abort(); },
  8881. };
  8882. reader.onloadend = function (e) {
  8883. request.onCompleteObservable.notifyObservers(request);
  8884. };
  8885. reader.onload = function (e) {
  8886. //target doesn't have result from ts 1.3
  8887. callback(e.target['result']);
  8888. };
  8889. reader.onprogress = progressCallback;
  8890. reader.readAsDataURL(fileToLoad);
  8891. return request;
  8892. };
  8893. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8894. var reader = new FileReader();
  8895. var request = {
  8896. onCompleteObservable: new BABYLON.Observable(),
  8897. abort: function () { return reader.abort(); },
  8898. };
  8899. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8900. reader.onerror = function (e) {
  8901. Tools.Log("Error while reading file: " + fileToLoad.name);
  8902. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8903. };
  8904. reader.onload = function (e) {
  8905. //target doesn't have result from ts 1.3
  8906. callback(e.target['result']);
  8907. };
  8908. if (progressCallBack) {
  8909. reader.onprogress = progressCallBack;
  8910. }
  8911. if (!useArrayBuffer) {
  8912. // Asynchronous read
  8913. reader.readAsText(fileToLoad);
  8914. }
  8915. else {
  8916. reader.readAsArrayBuffer(fileToLoad);
  8917. }
  8918. return request;
  8919. };
  8920. //returns a downloadable url to a file content.
  8921. Tools.FileAsURL = function (content) {
  8922. var fileBlob = new Blob([content]);
  8923. var url = window.URL || window.webkitURL;
  8924. var link = url.createObjectURL(fileBlob);
  8925. return link;
  8926. };
  8927. // Misc.
  8928. Tools.Format = function (value, decimals) {
  8929. if (decimals === void 0) { decimals = 2; }
  8930. return value.toFixed(decimals);
  8931. };
  8932. Tools.CheckExtends = function (v, min, max) {
  8933. if (v.x < min.x)
  8934. min.x = v.x;
  8935. if (v.y < min.y)
  8936. min.y = v.y;
  8937. if (v.z < min.z)
  8938. min.z = v.z;
  8939. if (v.x > max.x)
  8940. max.x = v.x;
  8941. if (v.y > max.y)
  8942. max.y = v.y;
  8943. if (v.z > max.z)
  8944. max.z = v.z;
  8945. };
  8946. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8947. for (var prop in source) {
  8948. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8949. continue;
  8950. }
  8951. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8952. continue;
  8953. }
  8954. var sourceValue = source[prop];
  8955. var typeOfSourceValue = typeof sourceValue;
  8956. if (typeOfSourceValue === "function") {
  8957. continue;
  8958. }
  8959. try {
  8960. if (typeOfSourceValue === "object") {
  8961. if (sourceValue instanceof Array) {
  8962. destination[prop] = [];
  8963. if (sourceValue.length > 0) {
  8964. if (typeof sourceValue[0] == "object") {
  8965. for (var index = 0; index < sourceValue.length; index++) {
  8966. var clonedValue = cloneValue(sourceValue[index], destination);
  8967. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  8968. destination[prop].push(clonedValue);
  8969. }
  8970. }
  8971. }
  8972. else {
  8973. destination[prop] = sourceValue.slice(0);
  8974. }
  8975. }
  8976. }
  8977. else {
  8978. destination[prop] = cloneValue(sourceValue, destination);
  8979. }
  8980. }
  8981. else {
  8982. destination[prop] = sourceValue;
  8983. }
  8984. }
  8985. catch (e) {
  8986. // Just ignore error (it could be because of a read-only property)
  8987. }
  8988. }
  8989. };
  8990. Tools.IsEmpty = function (obj) {
  8991. for (var i in obj) {
  8992. if (obj.hasOwnProperty(i)) {
  8993. return false;
  8994. }
  8995. }
  8996. return true;
  8997. };
  8998. Tools.RegisterTopRootEvents = function (events) {
  8999. for (var index = 0; index < events.length; index++) {
  9000. var event = events[index];
  9001. window.addEventListener(event.name, event.handler, false);
  9002. try {
  9003. if (window.parent) {
  9004. window.parent.addEventListener(event.name, event.handler, false);
  9005. }
  9006. }
  9007. catch (e) {
  9008. // Silently fails...
  9009. }
  9010. }
  9011. };
  9012. Tools.UnregisterTopRootEvents = function (events) {
  9013. for (var index = 0; index < events.length; index++) {
  9014. var event = events[index];
  9015. window.removeEventListener(event.name, event.handler);
  9016. try {
  9017. if (window.parent) {
  9018. window.parent.removeEventListener(event.name, event.handler);
  9019. }
  9020. }
  9021. catch (e) {
  9022. // Silently fails...
  9023. }
  9024. }
  9025. };
  9026. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9027. if (mimeType === void 0) { mimeType = "image/png"; }
  9028. // Read the contents of the framebuffer
  9029. var numberOfChannelsByLine = width * 4;
  9030. var halfHeight = height / 2;
  9031. //Reading datas from WebGL
  9032. var data = engine.readPixels(0, 0, width, height);
  9033. //To flip image on Y axis.
  9034. for (var i = 0; i < halfHeight; i++) {
  9035. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9036. var currentCell = j + i * numberOfChannelsByLine;
  9037. var targetLine = height - i - 1;
  9038. var targetCell = j + targetLine * numberOfChannelsByLine;
  9039. var temp = data[currentCell];
  9040. data[currentCell] = data[targetCell];
  9041. data[targetCell] = temp;
  9042. }
  9043. }
  9044. // Create a 2D canvas to store the result
  9045. if (!screenshotCanvas) {
  9046. screenshotCanvas = document.createElement('canvas');
  9047. }
  9048. screenshotCanvas.width = width;
  9049. screenshotCanvas.height = height;
  9050. var context = screenshotCanvas.getContext('2d');
  9051. if (context) {
  9052. // Copy the pixels to a 2D canvas
  9053. var imageData = context.createImageData(width, height);
  9054. var castData = (imageData.data);
  9055. castData.set(data);
  9056. context.putImageData(imageData, 0, 0);
  9057. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9058. }
  9059. };
  9060. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9061. if (mimeType === void 0) { mimeType = "image/png"; }
  9062. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9063. if (successCallback) {
  9064. successCallback(base64Image);
  9065. }
  9066. else {
  9067. // We need HTMLCanvasElement.toBlob for HD screenshots
  9068. if (!screenshotCanvas.toBlob) {
  9069. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9070. screenshotCanvas.toBlob = function (callback, type, quality) {
  9071. var _this = this;
  9072. setTimeout(function () {
  9073. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9074. for (var i = 0; i < len; i++) {
  9075. arr[i] = binStr.charCodeAt(i);
  9076. }
  9077. callback(new Blob([arr], { type: type || 'image/png' }));
  9078. });
  9079. };
  9080. }
  9081. screenshotCanvas.toBlob(function (blob) {
  9082. var url = URL.createObjectURL(blob);
  9083. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9084. if (("download" in document.createElement("a"))) {
  9085. var a = window.document.createElement("a");
  9086. a.href = url;
  9087. if (fileName) {
  9088. a.setAttribute("download", fileName);
  9089. }
  9090. else {
  9091. var date = new Date();
  9092. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9093. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9094. }
  9095. window.document.body.appendChild(a);
  9096. a.addEventListener("click", function () {
  9097. if (a.parentElement) {
  9098. a.parentElement.removeChild(a);
  9099. }
  9100. });
  9101. a.click();
  9102. }
  9103. else {
  9104. var newWindow = window.open("");
  9105. if (!newWindow)
  9106. return;
  9107. var img = newWindow.document.createElement("img");
  9108. img.onload = function () {
  9109. // no longer need to read the blob so it's revoked
  9110. URL.revokeObjectURL(url);
  9111. };
  9112. img.src = url;
  9113. newWindow.document.body.appendChild(img);
  9114. }
  9115. });
  9116. }
  9117. };
  9118. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9119. if (mimeType === void 0) { mimeType = "image/png"; }
  9120. var width;
  9121. var height;
  9122. // If a precision value is specified
  9123. if (size.precision) {
  9124. width = Math.round(engine.getRenderWidth() * size.precision);
  9125. height = Math.round(width / engine.getAspectRatio(camera));
  9126. }
  9127. else if (size.width && size.height) {
  9128. width = size.width;
  9129. height = size.height;
  9130. }
  9131. //If passing only width, computing height to keep display canvas ratio.
  9132. else if (size.width && !size.height) {
  9133. width = size.width;
  9134. height = Math.round(width / engine.getAspectRatio(camera));
  9135. }
  9136. //If passing only height, computing width to keep display canvas ratio.
  9137. else if (size.height && !size.width) {
  9138. height = size.height;
  9139. width = Math.round(height * engine.getAspectRatio(camera));
  9140. }
  9141. //Assuming here that "size" parameter is a number
  9142. else if (!isNaN(size)) {
  9143. height = size;
  9144. width = size;
  9145. }
  9146. else {
  9147. Tools.Error("Invalid 'size' parameter !");
  9148. return;
  9149. }
  9150. if (!screenshotCanvas) {
  9151. screenshotCanvas = document.createElement('canvas');
  9152. }
  9153. screenshotCanvas.width = width;
  9154. screenshotCanvas.height = height;
  9155. var renderContext = screenshotCanvas.getContext("2d");
  9156. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9157. var newWidth = width;
  9158. var newHeight = newWidth / ratio;
  9159. if (newHeight > height) {
  9160. newHeight = height;
  9161. newWidth = newHeight * ratio;
  9162. }
  9163. var offsetX = Math.max(0, width - newWidth) / 2;
  9164. var offsetY = Math.max(0, height - newHeight) / 2;
  9165. var renderingCanvas = engine.getRenderingCanvas();
  9166. if (renderContext && renderingCanvas) {
  9167. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9168. }
  9169. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9170. };
  9171. /**
  9172. * Generates an image screenshot from the specified camera.
  9173. *
  9174. * @param engine The engine to use for rendering
  9175. * @param camera The camera to use for rendering
  9176. * @param size This parameter can be set to a single number or to an object with the
  9177. * following (optional) properties: precision, width, height. If a single number is passed,
  9178. * it will be used for both width and height. If an object is passed, the screenshot size
  9179. * will be derived from the parameters. The precision property is a multiplier allowing
  9180. * rendering at a higher or lower resolution.
  9181. * @param successCallback The callback receives a single parameter which contains the
  9182. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9183. * src parameter of an <img> to display it.
  9184. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9185. * Check your browser for supported MIME types.
  9186. * @param samples Texture samples (default: 1)
  9187. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9188. * @param fileName A name for for the downloaded file.
  9189. * @constructor
  9190. */
  9191. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9192. if (mimeType === void 0) { mimeType = "image/png"; }
  9193. if (samples === void 0) { samples = 1; }
  9194. if (antialiasing === void 0) { antialiasing = false; }
  9195. var width;
  9196. var height;
  9197. //If a precision value is specified
  9198. if (size.precision) {
  9199. width = Math.round(engine.getRenderWidth() * size.precision);
  9200. height = Math.round(width / engine.getAspectRatio(camera));
  9201. size = { width: width, height: height };
  9202. }
  9203. else if (size.width && size.height) {
  9204. width = size.width;
  9205. height = size.height;
  9206. }
  9207. //If passing only width, computing height to keep display canvas ratio.
  9208. else if (size.width && !size.height) {
  9209. width = size.width;
  9210. height = Math.round(width / engine.getAspectRatio(camera));
  9211. size = { width: width, height: height };
  9212. }
  9213. //If passing only height, computing width to keep display canvas ratio.
  9214. else if (size.height && !size.width) {
  9215. height = size.height;
  9216. width = Math.round(height * engine.getAspectRatio(camera));
  9217. size = { width: width, height: height };
  9218. }
  9219. //Assuming here that "size" parameter is a number
  9220. else if (!isNaN(size)) {
  9221. height = size;
  9222. width = size;
  9223. }
  9224. else {
  9225. Tools.Error("Invalid 'size' parameter !");
  9226. return;
  9227. }
  9228. var scene = camera.getScene();
  9229. var previousCamera = null;
  9230. if (scene.activeCamera !== camera) {
  9231. previousCamera = scene.activeCamera;
  9232. scene.activeCamera = camera;
  9233. }
  9234. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9235. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9236. texture.renderList = null;
  9237. texture.samples = samples;
  9238. if (antialiasing) {
  9239. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9240. }
  9241. texture.onAfterRenderObservable.add(function () {
  9242. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9243. });
  9244. scene.incrementRenderId();
  9245. scene.resetCachedMaterial();
  9246. texture.render(true);
  9247. texture.dispose();
  9248. if (previousCamera) {
  9249. scene.activeCamera = previousCamera;
  9250. }
  9251. camera.getProjectionMatrix(true); // Force cache refresh;
  9252. };
  9253. // XHR response validator for local file scenario
  9254. Tools.ValidateXHRData = function (xhr, dataType) {
  9255. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9256. if (dataType === void 0) { dataType = 7; }
  9257. try {
  9258. if (dataType & 1) {
  9259. if (xhr.responseText && xhr.responseText.length > 0) {
  9260. return true;
  9261. }
  9262. else if (dataType === 1) {
  9263. return false;
  9264. }
  9265. }
  9266. if (dataType & 2) {
  9267. // Check header width and height since there is no "TGA" magic number
  9268. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9269. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9270. return true;
  9271. }
  9272. else if (dataType === 2) {
  9273. return false;
  9274. }
  9275. }
  9276. if (dataType & 4) {
  9277. // Check for the "DDS" magic number
  9278. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9279. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9280. return true;
  9281. }
  9282. else {
  9283. return false;
  9284. }
  9285. }
  9286. }
  9287. catch (e) {
  9288. // Global protection
  9289. }
  9290. return false;
  9291. };
  9292. /**
  9293. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9294. * Be aware Math.random() could cause collisions, but:
  9295. * "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"
  9296. */
  9297. Tools.RandomId = function () {
  9298. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9299. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9300. return v.toString(16);
  9301. });
  9302. };
  9303. /**
  9304. * Test if the given uri is a base64 string.
  9305. * @param uri The uri to test
  9306. * @return True if the uri is a base64 string or false otherwise.
  9307. */
  9308. Tools.IsBase64 = function (uri) {
  9309. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9310. };
  9311. /**
  9312. * Decode the given base64 uri.
  9313. * @param uri The uri to decode
  9314. * @return The decoded base64 data.
  9315. */
  9316. Tools.DecodeBase64 = function (uri) {
  9317. var decodedString = atob(uri.split(",")[1]);
  9318. var bufferLength = decodedString.length;
  9319. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9320. for (var i = 0; i < bufferLength; i++) {
  9321. bufferView[i] = decodedString.charCodeAt(i);
  9322. }
  9323. return bufferView.buffer;
  9324. };
  9325. Object.defineProperty(Tools, "NoneLogLevel", {
  9326. get: function () {
  9327. return Tools._NoneLogLevel;
  9328. },
  9329. enumerable: true,
  9330. configurable: true
  9331. });
  9332. Object.defineProperty(Tools, "MessageLogLevel", {
  9333. get: function () {
  9334. return Tools._MessageLogLevel;
  9335. },
  9336. enumerable: true,
  9337. configurable: true
  9338. });
  9339. Object.defineProperty(Tools, "WarningLogLevel", {
  9340. get: function () {
  9341. return Tools._WarningLogLevel;
  9342. },
  9343. enumerable: true,
  9344. configurable: true
  9345. });
  9346. Object.defineProperty(Tools, "ErrorLogLevel", {
  9347. get: function () {
  9348. return Tools._ErrorLogLevel;
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Object.defineProperty(Tools, "AllLogLevel", {
  9354. get: function () {
  9355. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9356. },
  9357. enumerable: true,
  9358. configurable: true
  9359. });
  9360. Tools._AddLogEntry = function (entry) {
  9361. Tools._LogCache = entry + Tools._LogCache;
  9362. if (Tools.OnNewCacheEntry) {
  9363. Tools.OnNewCacheEntry(entry);
  9364. }
  9365. };
  9366. Tools._FormatMessage = function (message) {
  9367. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9368. var date = new Date();
  9369. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9370. };
  9371. Tools._LogDisabled = function (message) {
  9372. // nothing to do
  9373. };
  9374. Tools._LogEnabled = function (message) {
  9375. var formattedMessage = Tools._FormatMessage(message);
  9376. console.log("BJS - " + formattedMessage);
  9377. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9378. Tools._AddLogEntry(entry);
  9379. };
  9380. Tools._WarnDisabled = function (message) {
  9381. // nothing to do
  9382. };
  9383. Tools._WarnEnabled = function (message) {
  9384. var formattedMessage = Tools._FormatMessage(message);
  9385. console.warn("BJS - " + formattedMessage);
  9386. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9387. Tools._AddLogEntry(entry);
  9388. };
  9389. Tools._ErrorDisabled = function (message) {
  9390. // nothing to do
  9391. };
  9392. Tools._ErrorEnabled = function (message) {
  9393. Tools.errorsCount++;
  9394. var formattedMessage = Tools._FormatMessage(message);
  9395. console.error("BJS - " + formattedMessage);
  9396. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9397. Tools._AddLogEntry(entry);
  9398. };
  9399. Object.defineProperty(Tools, "LogCache", {
  9400. get: function () {
  9401. return Tools._LogCache;
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. Tools.ClearLogCache = function () {
  9407. Tools._LogCache = "";
  9408. Tools.errorsCount = 0;
  9409. };
  9410. Object.defineProperty(Tools, "LogLevels", {
  9411. set: function (level) {
  9412. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9413. Tools.Log = Tools._LogEnabled;
  9414. }
  9415. else {
  9416. Tools.Log = Tools._LogDisabled;
  9417. }
  9418. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9419. Tools.Warn = Tools._WarnEnabled;
  9420. }
  9421. else {
  9422. Tools.Warn = Tools._WarnDisabled;
  9423. }
  9424. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9425. Tools.Error = Tools._ErrorEnabled;
  9426. }
  9427. else {
  9428. Tools.Error = Tools._ErrorDisabled;
  9429. }
  9430. },
  9431. enumerable: true,
  9432. configurable: true
  9433. });
  9434. Tools.IsWindowObjectExist = function () {
  9435. return (typeof window) !== "undefined";
  9436. };
  9437. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9438. get: function () {
  9439. return Tools._PerformanceNoneLogLevel;
  9440. },
  9441. enumerable: true,
  9442. configurable: true
  9443. });
  9444. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9445. get: function () {
  9446. return Tools._PerformanceUserMarkLogLevel;
  9447. },
  9448. enumerable: true,
  9449. configurable: true
  9450. });
  9451. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9452. get: function () {
  9453. return Tools._PerformanceConsoleLogLevel;
  9454. },
  9455. enumerable: true,
  9456. configurable: true
  9457. });
  9458. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9459. set: function (level) {
  9460. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9461. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9462. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9463. return;
  9464. }
  9465. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9466. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9467. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9468. return;
  9469. }
  9470. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9471. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9472. },
  9473. enumerable: true,
  9474. configurable: true
  9475. });
  9476. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9477. };
  9478. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9479. };
  9480. Tools._StartUserMark = function (counterName, condition) {
  9481. if (condition === void 0) { condition = true; }
  9482. if (!Tools._performance) {
  9483. if (!Tools.IsWindowObjectExist()) {
  9484. return;
  9485. }
  9486. Tools._performance = window.performance;
  9487. }
  9488. if (!condition || !Tools._performance.mark) {
  9489. return;
  9490. }
  9491. Tools._performance.mark(counterName + "-Begin");
  9492. };
  9493. Tools._EndUserMark = function (counterName, condition) {
  9494. if (condition === void 0) { condition = true; }
  9495. if (!condition || !Tools._performance.mark) {
  9496. return;
  9497. }
  9498. Tools._performance.mark(counterName + "-End");
  9499. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9500. };
  9501. Tools._StartPerformanceConsole = function (counterName, condition) {
  9502. if (condition === void 0) { condition = true; }
  9503. if (!condition) {
  9504. return;
  9505. }
  9506. Tools._StartUserMark(counterName, condition);
  9507. if (console.time) {
  9508. console.time(counterName);
  9509. }
  9510. };
  9511. Tools._EndPerformanceConsole = function (counterName, condition) {
  9512. if (condition === void 0) { condition = true; }
  9513. if (!condition) {
  9514. return;
  9515. }
  9516. Tools._EndUserMark(counterName, condition);
  9517. if (console.time) {
  9518. console.timeEnd(counterName);
  9519. }
  9520. };
  9521. Object.defineProperty(Tools, "Now", {
  9522. get: function () {
  9523. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9524. return window.performance.now();
  9525. }
  9526. return Date.now();
  9527. },
  9528. enumerable: true,
  9529. configurable: true
  9530. });
  9531. /**
  9532. * This method will return the name of the class used to create the instance of the given object.
  9533. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9534. * @param object the object to get the class name from
  9535. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9536. */
  9537. Tools.GetClassName = function (object, isType) {
  9538. if (isType === void 0) { isType = false; }
  9539. var name = null;
  9540. if (!isType && object.getClassName) {
  9541. name = object.getClassName();
  9542. }
  9543. else {
  9544. if (object instanceof Object) {
  9545. var classObj = isType ? object : Object.getPrototypeOf(object);
  9546. name = classObj.constructor["__bjsclassName__"];
  9547. }
  9548. if (!name) {
  9549. name = typeof object;
  9550. }
  9551. }
  9552. return name;
  9553. };
  9554. Tools.First = function (array, predicate) {
  9555. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9556. var el = array_1[_i];
  9557. if (predicate(el)) {
  9558. return el;
  9559. }
  9560. }
  9561. return null;
  9562. };
  9563. /**
  9564. * This method will return the name of the full name of the class, including its owning module (if any).
  9565. * 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).
  9566. * @param object the object to get the class name from
  9567. * @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.
  9568. */
  9569. Tools.getFullClassName = function (object, isType) {
  9570. if (isType === void 0) { isType = false; }
  9571. var className = null;
  9572. var moduleName = null;
  9573. if (!isType && object.getClassName) {
  9574. className = object.getClassName();
  9575. }
  9576. else {
  9577. if (object instanceof Object) {
  9578. var classObj = isType ? object : Object.getPrototypeOf(object);
  9579. className = classObj.constructor["__bjsclassName__"];
  9580. moduleName = classObj.constructor["__bjsmoduleName__"];
  9581. }
  9582. if (!className) {
  9583. className = typeof object;
  9584. }
  9585. }
  9586. if (!className) {
  9587. return null;
  9588. }
  9589. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9590. };
  9591. /**
  9592. * 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.
  9593. * @param array
  9594. */
  9595. Tools.arrayOrStringFeeder = function (array) {
  9596. return function (index) {
  9597. if (index >= array.length) {
  9598. return null;
  9599. }
  9600. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9601. if (val && val.getHashCode) {
  9602. val = val.getHashCode();
  9603. }
  9604. if (typeof val === "string") {
  9605. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9606. }
  9607. return val;
  9608. };
  9609. };
  9610. /**
  9611. * Compute the hashCode of a stream of number
  9612. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9613. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9614. * @return the hash code computed
  9615. */
  9616. Tools.hashCodeFromStream = function (feeder) {
  9617. // Based from here: http://stackoverflow.com/a/7616484/802124
  9618. var hash = 0;
  9619. var index = 0;
  9620. var chr = feeder(index++);
  9621. while (chr != null) {
  9622. hash = ((hash << 5) - hash) + chr;
  9623. hash |= 0; // Convert to 32bit integer
  9624. chr = feeder(index++);
  9625. }
  9626. return hash;
  9627. };
  9628. /**
  9629. * Returns a promise that resolves after the given amount of time.
  9630. * @param delay Number of milliseconds to delay
  9631. * @returns Promise that resolves after the given amount of time
  9632. */
  9633. Tools.DelayAsync = function (delay) {
  9634. return new Promise(function (resolve) {
  9635. setTimeout(function () {
  9636. resolve();
  9637. }, delay);
  9638. });
  9639. };
  9640. Tools.BaseUrl = "";
  9641. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9642. /**
  9643. * Default behaviour for cors in the application.
  9644. * It can be a string if the expected behavior is identical in the entire app.
  9645. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9646. */
  9647. Tools.CorsBehavior = "anonymous";
  9648. Tools.UseFallbackTexture = true;
  9649. /**
  9650. * Use this object to register external classes like custom textures or material
  9651. * to allow the laoders to instantiate them
  9652. */
  9653. Tools.RegisteredExternalClasses = {};
  9654. // Used in case of a texture loading problem
  9655. 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";
  9656. Tools.PreprocessUrl = function (url) {
  9657. return url;
  9658. };
  9659. // Logs
  9660. Tools._NoneLogLevel = 0;
  9661. Tools._MessageLogLevel = 1;
  9662. Tools._WarningLogLevel = 2;
  9663. Tools._ErrorLogLevel = 4;
  9664. Tools._LogCache = "";
  9665. Tools.errorsCount = 0;
  9666. Tools.Log = Tools._LogEnabled;
  9667. Tools.Warn = Tools._WarnEnabled;
  9668. Tools.Error = Tools._ErrorEnabled;
  9669. // Performances
  9670. Tools._PerformanceNoneLogLevel = 0;
  9671. Tools._PerformanceUserMarkLogLevel = 1;
  9672. Tools._PerformanceConsoleLogLevel = 2;
  9673. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9674. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9675. return Tools;
  9676. }());
  9677. BABYLON.Tools = Tools;
  9678. /**
  9679. * This class is used to track a performance counter which is number based.
  9680. * The user has access to many properties which give statistics of different nature
  9681. *
  9682. * The implementer can track two kinds of Performance Counter: time and count
  9683. * 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.
  9684. * 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.
  9685. */
  9686. var PerfCounter = /** @class */ (function () {
  9687. function PerfCounter() {
  9688. this._startMonitoringTime = 0;
  9689. this._min = 0;
  9690. this._max = 0;
  9691. this._average = 0;
  9692. this._lastSecAverage = 0;
  9693. this._current = 0;
  9694. this._totalValueCount = 0;
  9695. this._totalAccumulated = 0;
  9696. this._lastSecAccumulated = 0;
  9697. this._lastSecTime = 0;
  9698. this._lastSecValueCount = 0;
  9699. }
  9700. Object.defineProperty(PerfCounter.prototype, "min", {
  9701. /**
  9702. * Returns the smallest value ever
  9703. */
  9704. get: function () {
  9705. return this._min;
  9706. },
  9707. enumerable: true,
  9708. configurable: true
  9709. });
  9710. Object.defineProperty(PerfCounter.prototype, "max", {
  9711. /**
  9712. * Returns the biggest value ever
  9713. */
  9714. get: function () {
  9715. return this._max;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Object.defineProperty(PerfCounter.prototype, "average", {
  9721. /**
  9722. * Returns the average value since the performance counter is running
  9723. */
  9724. get: function () {
  9725. return this._average;
  9726. },
  9727. enumerable: true,
  9728. configurable: true
  9729. });
  9730. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9731. /**
  9732. * Returns the average value of the last second the counter was monitored
  9733. */
  9734. get: function () {
  9735. return this._lastSecAverage;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Object.defineProperty(PerfCounter.prototype, "current", {
  9741. /**
  9742. * Returns the current value
  9743. */
  9744. get: function () {
  9745. return this._current;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(PerfCounter.prototype, "total", {
  9751. get: function () {
  9752. return this._totalAccumulated;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(PerfCounter.prototype, "count", {
  9758. get: function () {
  9759. return this._totalValueCount;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. /**
  9765. * Call this method to start monitoring a new frame.
  9766. * 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.
  9767. */
  9768. PerfCounter.prototype.fetchNewFrame = function () {
  9769. this._totalValueCount++;
  9770. this._current = 0;
  9771. this._lastSecValueCount++;
  9772. };
  9773. /**
  9774. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9775. * @param newCount the count value to add to the monitored count
  9776. * @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.
  9777. */
  9778. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9779. if (!PerfCounter.Enabled) {
  9780. return;
  9781. }
  9782. this._current += newCount;
  9783. if (fetchResult) {
  9784. this._fetchResult();
  9785. }
  9786. };
  9787. /**
  9788. * Start monitoring this performance counter
  9789. */
  9790. PerfCounter.prototype.beginMonitoring = function () {
  9791. if (!PerfCounter.Enabled) {
  9792. return;
  9793. }
  9794. this._startMonitoringTime = Tools.Now;
  9795. };
  9796. /**
  9797. * Compute the time lapsed since the previous beginMonitoring() call.
  9798. * @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
  9799. */
  9800. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9801. if (newFrame === void 0) { newFrame = true; }
  9802. if (!PerfCounter.Enabled) {
  9803. return;
  9804. }
  9805. if (newFrame) {
  9806. this.fetchNewFrame();
  9807. }
  9808. var currentTime = Tools.Now;
  9809. this._current = currentTime - this._startMonitoringTime;
  9810. if (newFrame) {
  9811. this._fetchResult();
  9812. }
  9813. };
  9814. PerfCounter.prototype._fetchResult = function () {
  9815. this._totalAccumulated += this._current;
  9816. this._lastSecAccumulated += this._current;
  9817. // Min/Max update
  9818. this._min = Math.min(this._min, this._current);
  9819. this._max = Math.max(this._max, this._current);
  9820. this._average = this._totalAccumulated / this._totalValueCount;
  9821. // Reset last sec?
  9822. var now = Tools.Now;
  9823. if ((now - this._lastSecTime) > 1000) {
  9824. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9825. this._lastSecTime = now;
  9826. this._lastSecAccumulated = 0;
  9827. this._lastSecValueCount = 0;
  9828. }
  9829. };
  9830. PerfCounter.Enabled = true;
  9831. return PerfCounter;
  9832. }());
  9833. BABYLON.PerfCounter = PerfCounter;
  9834. /**
  9835. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9836. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9837. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9838. * @param name The name of the class, case should be preserved
  9839. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9840. */
  9841. function className(name, module) {
  9842. return function (target) {
  9843. target["__bjsclassName__"] = name;
  9844. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9845. };
  9846. }
  9847. BABYLON.className = className;
  9848. /**
  9849. * An implementation of a loop for asynchronous functions.
  9850. */
  9851. var AsyncLoop = /** @class */ (function () {
  9852. /**
  9853. * Constroctor.
  9854. * @param iterations the number of iterations.
  9855. * @param _fn the function to run each iteration
  9856. * @param _successCallback the callback that will be called upon succesful execution
  9857. * @param offset starting offset.
  9858. */
  9859. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9860. if (offset === void 0) { offset = 0; }
  9861. this.iterations = iterations;
  9862. this._fn = _fn;
  9863. this._successCallback = _successCallback;
  9864. this.index = offset - 1;
  9865. this._done = false;
  9866. }
  9867. /**
  9868. * Execute the next iteration. Must be called after the last iteration was finished.
  9869. */
  9870. AsyncLoop.prototype.executeNext = function () {
  9871. if (!this._done) {
  9872. if (this.index + 1 < this.iterations) {
  9873. ++this.index;
  9874. this._fn(this);
  9875. }
  9876. else {
  9877. this.breakLoop();
  9878. }
  9879. }
  9880. };
  9881. /**
  9882. * Break the loop and run the success callback.
  9883. */
  9884. AsyncLoop.prototype.breakLoop = function () {
  9885. this._done = true;
  9886. this._successCallback();
  9887. };
  9888. /**
  9889. * Helper function
  9890. */
  9891. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9892. if (offset === void 0) { offset = 0; }
  9893. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9894. loop.executeNext();
  9895. return loop;
  9896. };
  9897. /**
  9898. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9899. * @param iterations total number of iterations
  9900. * @param syncedIterations number of synchronous iterations in each async iteration.
  9901. * @param fn the function to call each iteration.
  9902. * @param callback a success call back that will be called when iterating stops.
  9903. * @param breakFunction a break condition (optional)
  9904. * @param timeout timeout settings for the setTimeout function. default - 0.
  9905. * @constructor
  9906. */
  9907. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9908. if (timeout === void 0) { timeout = 0; }
  9909. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9910. if (breakFunction && breakFunction())
  9911. loop.breakLoop();
  9912. else {
  9913. setTimeout(function () {
  9914. for (var i = 0; i < syncedIterations; ++i) {
  9915. var iteration = (loop.index * syncedIterations) + i;
  9916. if (iteration >= iterations)
  9917. break;
  9918. fn(iteration);
  9919. if (breakFunction && breakFunction()) {
  9920. loop.breakLoop();
  9921. break;
  9922. }
  9923. }
  9924. loop.executeNext();
  9925. }, timeout);
  9926. }
  9927. }, callback);
  9928. };
  9929. return AsyncLoop;
  9930. }());
  9931. BABYLON.AsyncLoop = AsyncLoop;
  9932. })(BABYLON || (BABYLON = {}));
  9933. //# sourceMappingURL=babylon.tools.js.map
  9934. var BABYLON;
  9935. (function (BABYLON) {
  9936. var PromiseStates;
  9937. (function (PromiseStates) {
  9938. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9939. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9940. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9941. })(PromiseStates || (PromiseStates = {}));
  9942. var FulFillmentAgregator = /** @class */ (function () {
  9943. function FulFillmentAgregator() {
  9944. this.count = 0;
  9945. this.target = 0;
  9946. this.results = [];
  9947. }
  9948. return FulFillmentAgregator;
  9949. }());
  9950. var InternalPromise = /** @class */ (function () {
  9951. function InternalPromise(resolver) {
  9952. var _this = this;
  9953. this._state = PromiseStates.Pending;
  9954. this._children = new Array();
  9955. this._rejectWasConsumed = false;
  9956. if (!resolver) {
  9957. return;
  9958. }
  9959. try {
  9960. resolver(function (value) {
  9961. _this._resolve(value);
  9962. }, function (reason) {
  9963. _this._reject(reason);
  9964. });
  9965. }
  9966. catch (e) {
  9967. this._reject(e);
  9968. }
  9969. }
  9970. InternalPromise.prototype.catch = function (onRejected) {
  9971. return this.then(undefined, onRejected);
  9972. };
  9973. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9974. var _this = this;
  9975. var newPromise = new InternalPromise();
  9976. newPromise._onFulfilled = onFulfilled;
  9977. newPromise._onRejected = onRejected;
  9978. // Composition
  9979. this._children.push(newPromise);
  9980. if (this._state !== PromiseStates.Pending) {
  9981. BABYLON.Tools.SetImmediate(function () {
  9982. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9983. var returnedValue = newPromise._resolve(_this._result);
  9984. if (returnedValue !== undefined && returnedValue !== null) {
  9985. if (returnedValue._state !== undefined) {
  9986. var returnedPromise = returnedValue;
  9987. newPromise._children.push(returnedPromise);
  9988. newPromise = returnedPromise;
  9989. }
  9990. else {
  9991. newPromise._result = returnedValue;
  9992. }
  9993. }
  9994. }
  9995. else {
  9996. newPromise._reject(_this._reason);
  9997. }
  9998. });
  9999. }
  10000. return newPromise;
  10001. };
  10002. InternalPromise.prototype._moveChildren = function (children) {
  10003. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10004. if (this._state === PromiseStates.Fulfilled) {
  10005. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10006. var child = _b[_i];
  10007. child._resolve(this._result);
  10008. }
  10009. }
  10010. else if (this._state === PromiseStates.Rejected) {
  10011. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10012. var child = _d[_c];
  10013. child._reject(this._reason);
  10014. }
  10015. }
  10016. var _a;
  10017. };
  10018. InternalPromise.prototype._resolve = function (value) {
  10019. try {
  10020. this._state = PromiseStates.Fulfilled;
  10021. var returnedValue = null;
  10022. if (this._onFulfilled) {
  10023. returnedValue = this._onFulfilled(value);
  10024. }
  10025. if (returnedValue !== undefined && returnedValue !== null) {
  10026. if (returnedValue._state !== undefined) {
  10027. // Transmit children
  10028. var returnedPromise = returnedValue;
  10029. returnedPromise._moveChildren(this._children);
  10030. value = returnedPromise._result;
  10031. }
  10032. else {
  10033. value = returnedValue;
  10034. }
  10035. }
  10036. this._result = value;
  10037. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10038. var child = _a[_i];
  10039. child._resolve(value);
  10040. }
  10041. this._children.length = 0;
  10042. delete this._onFulfilled;
  10043. delete this._onRejected;
  10044. }
  10045. catch (e) {
  10046. this._reject(e, true);
  10047. }
  10048. };
  10049. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10050. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10051. this._state = PromiseStates.Rejected;
  10052. this._reason = reason;
  10053. if (this._onRejected && !onLocalThrow) {
  10054. try {
  10055. this._onRejected(reason);
  10056. this._rejectWasConsumed = true;
  10057. }
  10058. catch (e) {
  10059. reason = e;
  10060. }
  10061. }
  10062. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10063. var child = _a[_i];
  10064. if (this._rejectWasConsumed) {
  10065. child._resolve(null);
  10066. }
  10067. else {
  10068. child._reject(reason);
  10069. }
  10070. }
  10071. this._children.length = 0;
  10072. delete this._onFulfilled;
  10073. delete this._onRejected;
  10074. };
  10075. InternalPromise.resolve = function (value) {
  10076. var newPromise = new InternalPromise();
  10077. newPromise._resolve(value);
  10078. return newPromise;
  10079. };
  10080. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10081. promise.then(function (value) {
  10082. agregator.results[index] = value;
  10083. agregator.count++;
  10084. if (agregator.count === agregator.target) {
  10085. agregator.rootPromise._resolve(agregator.results);
  10086. }
  10087. return null;
  10088. }, function (reason) {
  10089. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10090. agregator.rootPromise._reject(reason);
  10091. }
  10092. });
  10093. };
  10094. InternalPromise.all = function (promises) {
  10095. var newPromise = new InternalPromise();
  10096. var agregator = new FulFillmentAgregator();
  10097. agregator.target = promises.length;
  10098. agregator.rootPromise = newPromise;
  10099. if (promises.length) {
  10100. for (var index = 0; index < promises.length; index++) {
  10101. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10102. }
  10103. }
  10104. else {
  10105. newPromise._resolve([]);
  10106. }
  10107. return newPromise;
  10108. };
  10109. InternalPromise.race = function (promises) {
  10110. var newPromise = new InternalPromise();
  10111. if (promises.length) {
  10112. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10113. var promise = promises_1[_i];
  10114. promise.then(function (value) {
  10115. if (newPromise) {
  10116. newPromise._resolve(value);
  10117. newPromise = null;
  10118. }
  10119. return null;
  10120. }, function (reason) {
  10121. if (newPromise) {
  10122. newPromise._reject(reason);
  10123. newPromise = null;
  10124. }
  10125. });
  10126. }
  10127. }
  10128. return newPromise;
  10129. };
  10130. return InternalPromise;
  10131. }());
  10132. /**
  10133. * Helper class that provides a small promise polyfill
  10134. */
  10135. var PromisePolyfill = /** @class */ (function () {
  10136. function PromisePolyfill() {
  10137. }
  10138. /**
  10139. * Static function used to check if the polyfill is required
  10140. * If this is the case then the function will inject the polyfill to window.Promise
  10141. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10142. */
  10143. PromisePolyfill.Apply = function (force) {
  10144. if (force === void 0) { force = false; }
  10145. if (force || typeof Promise === 'undefined') {
  10146. var root = window;
  10147. root.Promise = InternalPromise;
  10148. }
  10149. };
  10150. return PromisePolyfill;
  10151. }());
  10152. BABYLON.PromisePolyfill = PromisePolyfill;
  10153. })(BABYLON || (BABYLON = {}));
  10154. //# sourceMappingURL=babylon.promise.js.map
  10155. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10156. var BABYLON;
  10157. (function (BABYLON) {
  10158. /**
  10159. * Helper class to push actions to a pool of workers.
  10160. */
  10161. var WorkerPool = /** @class */ (function () {
  10162. /**
  10163. * Constructor
  10164. * @param workers Array of workers to use for actions
  10165. */
  10166. function WorkerPool(workers) {
  10167. this._pendingActions = new Array();
  10168. this._workerInfos = workers.map(function (worker) { return ({
  10169. worker: worker,
  10170. active: false
  10171. }); });
  10172. }
  10173. /**
  10174. * Terminates all workers and clears any pending actions.
  10175. */
  10176. WorkerPool.prototype.dispose = function () {
  10177. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10178. var workerInfo = _a[_i];
  10179. workerInfo.worker.terminate();
  10180. }
  10181. delete this._workerInfos;
  10182. delete this._pendingActions;
  10183. };
  10184. /**
  10185. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10186. * pended until a worker has completed its action.
  10187. * @param action The action to perform. Call onComplete when the action is complete.
  10188. */
  10189. WorkerPool.prototype.push = function (action) {
  10190. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10191. var workerInfo = _a[_i];
  10192. if (!workerInfo.active) {
  10193. this._execute(workerInfo, action);
  10194. return;
  10195. }
  10196. }
  10197. this._pendingActions.push(action);
  10198. };
  10199. WorkerPool.prototype._execute = function (workerInfo, action) {
  10200. var _this = this;
  10201. workerInfo.active = true;
  10202. action(workerInfo.worker, function () {
  10203. workerInfo.active = false;
  10204. var nextAction = _this._pendingActions.shift();
  10205. if (nextAction) {
  10206. _this._execute(workerInfo, nextAction);
  10207. }
  10208. });
  10209. };
  10210. return WorkerPool;
  10211. }());
  10212. BABYLON.WorkerPool = WorkerPool;
  10213. })(BABYLON || (BABYLON = {}));
  10214. //# sourceMappingURL=babylon.workerPool.js.map
  10215. var BABYLON;
  10216. (function (BABYLON) {
  10217. var _AlphaState = /** @class */ (function () {
  10218. /**
  10219. * Initializes the state.
  10220. */
  10221. function _AlphaState() {
  10222. this._isAlphaBlendDirty = false;
  10223. this._isBlendFunctionParametersDirty = false;
  10224. this._isBlendEquationParametersDirty = false;
  10225. this._isBlendConstantsDirty = false;
  10226. this._alphaBlend = false;
  10227. this._blendFunctionParameters = new Array(4);
  10228. this._blendEquationParameters = new Array(2);
  10229. this._blendConstants = new Array(4);
  10230. this.reset();
  10231. }
  10232. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10233. get: function () {
  10234. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10235. },
  10236. enumerable: true,
  10237. configurable: true
  10238. });
  10239. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10240. get: function () {
  10241. return this._alphaBlend;
  10242. },
  10243. set: function (value) {
  10244. if (this._alphaBlend === value) {
  10245. return;
  10246. }
  10247. this._alphaBlend = value;
  10248. this._isAlphaBlendDirty = true;
  10249. },
  10250. enumerable: true,
  10251. configurable: true
  10252. });
  10253. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10254. if (this._blendConstants[0] === r &&
  10255. this._blendConstants[1] === g &&
  10256. this._blendConstants[2] === b &&
  10257. this._blendConstants[3] === a) {
  10258. return;
  10259. }
  10260. this._blendConstants[0] = r;
  10261. this._blendConstants[1] = g;
  10262. this._blendConstants[2] = b;
  10263. this._blendConstants[3] = a;
  10264. this._isBlendConstantsDirty = true;
  10265. };
  10266. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10267. if (this._blendFunctionParameters[0] === value0 &&
  10268. this._blendFunctionParameters[1] === value1 &&
  10269. this._blendFunctionParameters[2] === value2 &&
  10270. this._blendFunctionParameters[3] === value3) {
  10271. return;
  10272. }
  10273. this._blendFunctionParameters[0] = value0;
  10274. this._blendFunctionParameters[1] = value1;
  10275. this._blendFunctionParameters[2] = value2;
  10276. this._blendFunctionParameters[3] = value3;
  10277. this._isBlendFunctionParametersDirty = true;
  10278. };
  10279. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10280. if (this._blendEquationParameters[0] === rgb &&
  10281. this._blendEquationParameters[1] === alpha) {
  10282. return;
  10283. }
  10284. this._blendEquationParameters[0] = rgb;
  10285. this._blendEquationParameters[1] = alpha;
  10286. this._isBlendEquationParametersDirty = true;
  10287. };
  10288. _AlphaState.prototype.reset = function () {
  10289. this._alphaBlend = false;
  10290. this._blendFunctionParameters[0] = null;
  10291. this._blendFunctionParameters[1] = null;
  10292. this._blendFunctionParameters[2] = null;
  10293. this._blendFunctionParameters[3] = null;
  10294. this._blendEquationParameters[0] = null;
  10295. this._blendEquationParameters[1] = null;
  10296. this._blendConstants[0] = null;
  10297. this._blendConstants[1] = null;
  10298. this._blendConstants[2] = null;
  10299. this._blendConstants[3] = null;
  10300. this._isAlphaBlendDirty = true;
  10301. this._isBlendFunctionParametersDirty = false;
  10302. this._isBlendEquationParametersDirty = false;
  10303. this._isBlendConstantsDirty = false;
  10304. };
  10305. _AlphaState.prototype.apply = function (gl) {
  10306. if (!this.isDirty) {
  10307. return;
  10308. }
  10309. // Alpha blend
  10310. if (this._isAlphaBlendDirty) {
  10311. if (this._alphaBlend) {
  10312. gl.enable(gl.BLEND);
  10313. }
  10314. else {
  10315. gl.disable(gl.BLEND);
  10316. }
  10317. this._isAlphaBlendDirty = false;
  10318. }
  10319. // Alpha function
  10320. if (this._isBlendFunctionParametersDirty) {
  10321. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10322. this._isBlendFunctionParametersDirty = false;
  10323. }
  10324. // Alpha equation
  10325. if (this._isBlendEquationParametersDirty) {
  10326. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10327. this._isBlendEquationParametersDirty = false;
  10328. }
  10329. // Constants
  10330. if (this._isBlendConstantsDirty) {
  10331. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10332. this._isBlendConstantsDirty = false;
  10333. }
  10334. };
  10335. return _AlphaState;
  10336. }());
  10337. BABYLON._AlphaState = _AlphaState;
  10338. })(BABYLON || (BABYLON = {}));
  10339. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10340. var BABYLON;
  10341. (function (BABYLON) {
  10342. var _DepthCullingState = /** @class */ (function () {
  10343. /**
  10344. * Initializes the state.
  10345. */
  10346. function _DepthCullingState() {
  10347. this._isDepthTestDirty = false;
  10348. this._isDepthMaskDirty = false;
  10349. this._isDepthFuncDirty = false;
  10350. this._isCullFaceDirty = false;
  10351. this._isCullDirty = false;
  10352. this._isZOffsetDirty = false;
  10353. this._isFrontFaceDirty = false;
  10354. this.reset();
  10355. }
  10356. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10357. get: function () {
  10358. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10359. },
  10360. enumerable: true,
  10361. configurable: true
  10362. });
  10363. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10364. get: function () {
  10365. return this._zOffset;
  10366. },
  10367. set: function (value) {
  10368. if (this._zOffset === value) {
  10369. return;
  10370. }
  10371. this._zOffset = value;
  10372. this._isZOffsetDirty = true;
  10373. },
  10374. enumerable: true,
  10375. configurable: true
  10376. });
  10377. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10378. get: function () {
  10379. return this._cullFace;
  10380. },
  10381. set: function (value) {
  10382. if (this._cullFace === value) {
  10383. return;
  10384. }
  10385. this._cullFace = value;
  10386. this._isCullFaceDirty = true;
  10387. },
  10388. enumerable: true,
  10389. configurable: true
  10390. });
  10391. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10392. get: function () {
  10393. return this._cull;
  10394. },
  10395. set: function (value) {
  10396. if (this._cull === value) {
  10397. return;
  10398. }
  10399. this._cull = value;
  10400. this._isCullDirty = true;
  10401. },
  10402. enumerable: true,
  10403. configurable: true
  10404. });
  10405. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10406. get: function () {
  10407. return this._depthFunc;
  10408. },
  10409. set: function (value) {
  10410. if (this._depthFunc === value) {
  10411. return;
  10412. }
  10413. this._depthFunc = value;
  10414. this._isDepthFuncDirty = true;
  10415. },
  10416. enumerable: true,
  10417. configurable: true
  10418. });
  10419. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10420. get: function () {
  10421. return this._depthMask;
  10422. },
  10423. set: function (value) {
  10424. if (this._depthMask === value) {
  10425. return;
  10426. }
  10427. this._depthMask = value;
  10428. this._isDepthMaskDirty = true;
  10429. },
  10430. enumerable: true,
  10431. configurable: true
  10432. });
  10433. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10434. get: function () {
  10435. return this._depthTest;
  10436. },
  10437. set: function (value) {
  10438. if (this._depthTest === value) {
  10439. return;
  10440. }
  10441. this._depthTest = value;
  10442. this._isDepthTestDirty = true;
  10443. },
  10444. enumerable: true,
  10445. configurable: true
  10446. });
  10447. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10448. get: function () {
  10449. return this._frontFace;
  10450. },
  10451. set: function (value) {
  10452. if (this._frontFace === value) {
  10453. return;
  10454. }
  10455. this._frontFace = value;
  10456. this._isFrontFaceDirty = true;
  10457. },
  10458. enumerable: true,
  10459. configurable: true
  10460. });
  10461. _DepthCullingState.prototype.reset = function () {
  10462. this._depthMask = true;
  10463. this._depthTest = true;
  10464. this._depthFunc = null;
  10465. this._cullFace = null;
  10466. this._cull = null;
  10467. this._zOffset = 0;
  10468. this._frontFace = null;
  10469. this._isDepthTestDirty = true;
  10470. this._isDepthMaskDirty = true;
  10471. this._isDepthFuncDirty = false;
  10472. this._isCullFaceDirty = false;
  10473. this._isCullDirty = false;
  10474. this._isZOffsetDirty = false;
  10475. this._isFrontFaceDirty = false;
  10476. };
  10477. _DepthCullingState.prototype.apply = function (gl) {
  10478. if (!this.isDirty) {
  10479. return;
  10480. }
  10481. // Cull
  10482. if (this._isCullDirty) {
  10483. if (this.cull) {
  10484. gl.enable(gl.CULL_FACE);
  10485. }
  10486. else {
  10487. gl.disable(gl.CULL_FACE);
  10488. }
  10489. this._isCullDirty = false;
  10490. }
  10491. // Cull face
  10492. if (this._isCullFaceDirty) {
  10493. gl.cullFace(this.cullFace);
  10494. this._isCullFaceDirty = false;
  10495. }
  10496. // Depth mask
  10497. if (this._isDepthMaskDirty) {
  10498. gl.depthMask(this.depthMask);
  10499. this._isDepthMaskDirty = false;
  10500. }
  10501. // Depth test
  10502. if (this._isDepthTestDirty) {
  10503. if (this.depthTest) {
  10504. gl.enable(gl.DEPTH_TEST);
  10505. }
  10506. else {
  10507. gl.disable(gl.DEPTH_TEST);
  10508. }
  10509. this._isDepthTestDirty = false;
  10510. }
  10511. // Depth func
  10512. if (this._isDepthFuncDirty) {
  10513. gl.depthFunc(this.depthFunc);
  10514. this._isDepthFuncDirty = false;
  10515. }
  10516. // zOffset
  10517. if (this._isZOffsetDirty) {
  10518. if (this.zOffset) {
  10519. gl.enable(gl.POLYGON_OFFSET_FILL);
  10520. gl.polygonOffset(this.zOffset, 0);
  10521. }
  10522. else {
  10523. gl.disable(gl.POLYGON_OFFSET_FILL);
  10524. }
  10525. this._isZOffsetDirty = false;
  10526. }
  10527. // Front face
  10528. if (this._isFrontFaceDirty) {
  10529. gl.frontFace(this.frontFace);
  10530. this._isFrontFaceDirty = false;
  10531. }
  10532. };
  10533. return _DepthCullingState;
  10534. }());
  10535. BABYLON._DepthCullingState = _DepthCullingState;
  10536. })(BABYLON || (BABYLON = {}));
  10537. //# sourceMappingURL=babylon.depthCullingState.js.map
  10538. var BABYLON;
  10539. (function (BABYLON) {
  10540. var _StencilState = /** @class */ (function () {
  10541. function _StencilState() {
  10542. this._isStencilTestDirty = false;
  10543. this._isStencilMaskDirty = false;
  10544. this._isStencilFuncDirty = false;
  10545. this._isStencilOpDirty = false;
  10546. this.reset();
  10547. }
  10548. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10549. get: function () {
  10550. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10551. },
  10552. enumerable: true,
  10553. configurable: true
  10554. });
  10555. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10556. get: function () {
  10557. return this._stencilFunc;
  10558. },
  10559. set: function (value) {
  10560. if (this._stencilFunc === value) {
  10561. return;
  10562. }
  10563. this._stencilFunc = value;
  10564. this._isStencilFuncDirty = true;
  10565. },
  10566. enumerable: true,
  10567. configurable: true
  10568. });
  10569. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10570. get: function () {
  10571. return this._stencilFuncRef;
  10572. },
  10573. set: function (value) {
  10574. if (this._stencilFuncRef === value) {
  10575. return;
  10576. }
  10577. this._stencilFuncRef = value;
  10578. this._isStencilFuncDirty = true;
  10579. },
  10580. enumerable: true,
  10581. configurable: true
  10582. });
  10583. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10584. get: function () {
  10585. return this._stencilFuncMask;
  10586. },
  10587. set: function (value) {
  10588. if (this._stencilFuncMask === value) {
  10589. return;
  10590. }
  10591. this._stencilFuncMask = value;
  10592. this._isStencilFuncDirty = true;
  10593. },
  10594. enumerable: true,
  10595. configurable: true
  10596. });
  10597. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10598. get: function () {
  10599. return this._stencilOpStencilFail;
  10600. },
  10601. set: function (value) {
  10602. if (this._stencilOpStencilFail === value) {
  10603. return;
  10604. }
  10605. this._stencilOpStencilFail = value;
  10606. this._isStencilOpDirty = true;
  10607. },
  10608. enumerable: true,
  10609. configurable: true
  10610. });
  10611. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10612. get: function () {
  10613. return this._stencilOpDepthFail;
  10614. },
  10615. set: function (value) {
  10616. if (this._stencilOpDepthFail === value) {
  10617. return;
  10618. }
  10619. this._stencilOpDepthFail = value;
  10620. this._isStencilOpDirty = true;
  10621. },
  10622. enumerable: true,
  10623. configurable: true
  10624. });
  10625. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10626. get: function () {
  10627. return this._stencilOpStencilDepthPass;
  10628. },
  10629. set: function (value) {
  10630. if (this._stencilOpStencilDepthPass === value) {
  10631. return;
  10632. }
  10633. this._stencilOpStencilDepthPass = value;
  10634. this._isStencilOpDirty = true;
  10635. },
  10636. enumerable: true,
  10637. configurable: true
  10638. });
  10639. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10640. get: function () {
  10641. return this._stencilMask;
  10642. },
  10643. set: function (value) {
  10644. if (this._stencilMask === value) {
  10645. return;
  10646. }
  10647. this._stencilMask = value;
  10648. this._isStencilMaskDirty = true;
  10649. },
  10650. enumerable: true,
  10651. configurable: true
  10652. });
  10653. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10654. get: function () {
  10655. return this._stencilTest;
  10656. },
  10657. set: function (value) {
  10658. if (this._stencilTest === value) {
  10659. return;
  10660. }
  10661. this._stencilTest = value;
  10662. this._isStencilTestDirty = true;
  10663. },
  10664. enumerable: true,
  10665. configurable: true
  10666. });
  10667. _StencilState.prototype.reset = function () {
  10668. this._stencilTest = false;
  10669. this._stencilMask = 0xFF;
  10670. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10671. this._stencilFuncRef = 1;
  10672. this._stencilFuncMask = 0xFF;
  10673. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10674. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10675. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10676. this._isStencilTestDirty = true;
  10677. this._isStencilMaskDirty = true;
  10678. this._isStencilFuncDirty = true;
  10679. this._isStencilOpDirty = true;
  10680. };
  10681. _StencilState.prototype.apply = function (gl) {
  10682. if (!this.isDirty) {
  10683. return;
  10684. }
  10685. // Stencil test
  10686. if (this._isStencilTestDirty) {
  10687. if (this.stencilTest) {
  10688. gl.enable(gl.STENCIL_TEST);
  10689. }
  10690. else {
  10691. gl.disable(gl.STENCIL_TEST);
  10692. }
  10693. this._isStencilTestDirty = false;
  10694. }
  10695. // Stencil mask
  10696. if (this._isStencilMaskDirty) {
  10697. gl.stencilMask(this.stencilMask);
  10698. this._isStencilMaskDirty = false;
  10699. }
  10700. // Stencil func
  10701. if (this._isStencilFuncDirty) {
  10702. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10703. this._isStencilFuncDirty = false;
  10704. }
  10705. // Stencil op
  10706. if (this._isStencilOpDirty) {
  10707. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10708. this._isStencilOpDirty = false;
  10709. }
  10710. };
  10711. return _StencilState;
  10712. }());
  10713. BABYLON._StencilState = _StencilState;
  10714. })(BABYLON || (BABYLON = {}));
  10715. //# sourceMappingURL=babylon.stencilState.js.map
  10716. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10717. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10718. s = arguments[i];
  10719. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10720. t[p] = s[p];
  10721. }
  10722. return t;
  10723. };
  10724. var BABYLON;
  10725. (function (BABYLON) {
  10726. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10727. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10728. };
  10729. var compileRawShader = function (gl, source, type) {
  10730. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10731. gl.shaderSource(shader, source);
  10732. gl.compileShader(shader);
  10733. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10734. var log = gl.getShaderInfoLog(shader);
  10735. if (log) {
  10736. throw new Error(log);
  10737. }
  10738. }
  10739. if (!shader) {
  10740. throw new Error("Something went wrong while compile the shader.");
  10741. }
  10742. return shader;
  10743. };
  10744. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10745. var magFilter = gl.NEAREST;
  10746. var minFilter = gl.NEAREST;
  10747. switch (samplingMode) {
  10748. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10749. magFilter = gl.LINEAR;
  10750. if (generateMipMaps) {
  10751. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10752. }
  10753. else {
  10754. minFilter = gl.LINEAR;
  10755. }
  10756. break;
  10757. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10758. magFilter = gl.LINEAR;
  10759. if (generateMipMaps) {
  10760. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10761. }
  10762. else {
  10763. minFilter = gl.LINEAR;
  10764. }
  10765. break;
  10766. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10767. magFilter = gl.NEAREST;
  10768. if (generateMipMaps) {
  10769. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10770. }
  10771. else {
  10772. minFilter = gl.NEAREST;
  10773. }
  10774. break;
  10775. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10776. magFilter = gl.NEAREST;
  10777. if (generateMipMaps) {
  10778. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10779. }
  10780. else {
  10781. minFilter = gl.NEAREST;
  10782. }
  10783. break;
  10784. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10785. magFilter = gl.NEAREST;
  10786. if (generateMipMaps) {
  10787. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10788. }
  10789. else {
  10790. minFilter = gl.LINEAR;
  10791. }
  10792. break;
  10793. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10794. magFilter = gl.NEAREST;
  10795. if (generateMipMaps) {
  10796. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10797. }
  10798. else {
  10799. minFilter = gl.LINEAR;
  10800. }
  10801. break;
  10802. case BABYLON.Texture.NEAREST_LINEAR:
  10803. magFilter = gl.NEAREST;
  10804. minFilter = gl.LINEAR;
  10805. break;
  10806. case BABYLON.Texture.NEAREST_NEAREST:
  10807. magFilter = gl.NEAREST;
  10808. minFilter = gl.NEAREST;
  10809. break;
  10810. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10811. magFilter = gl.LINEAR;
  10812. if (generateMipMaps) {
  10813. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10814. }
  10815. else {
  10816. minFilter = gl.NEAREST;
  10817. }
  10818. break;
  10819. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10820. magFilter = gl.LINEAR;
  10821. if (generateMipMaps) {
  10822. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10823. }
  10824. else {
  10825. minFilter = gl.NEAREST;
  10826. }
  10827. break;
  10828. case BABYLON.Texture.LINEAR_LINEAR:
  10829. magFilter = gl.LINEAR;
  10830. minFilter = gl.LINEAR;
  10831. break;
  10832. case BABYLON.Texture.LINEAR_NEAREST:
  10833. magFilter = gl.LINEAR;
  10834. minFilter = gl.NEAREST;
  10835. break;
  10836. }
  10837. return {
  10838. min: minFilter,
  10839. mag: magFilter
  10840. };
  10841. };
  10842. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10843. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10844. var img;
  10845. var onload = function () {
  10846. loadedImages[index] = img;
  10847. loadedImages._internalCount++;
  10848. if (scene) {
  10849. scene._removePendingData(img);
  10850. }
  10851. if (loadedImages._internalCount === 6) {
  10852. onfinish(loadedImages);
  10853. }
  10854. };
  10855. var onerror = function (message, exception) {
  10856. if (scene) {
  10857. scene._removePendingData(img);
  10858. }
  10859. if (onErrorCallBack) {
  10860. onErrorCallBack(message, exception);
  10861. }
  10862. };
  10863. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10864. if (scene) {
  10865. scene._addPendingData(img);
  10866. }
  10867. };
  10868. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10869. if (onError === void 0) { onError = null; }
  10870. var loadedImages = [];
  10871. loadedImages._internalCount = 0;
  10872. for (var index = 0; index < 6; index++) {
  10873. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10874. }
  10875. };
  10876. var BufferPointer = /** @class */ (function () {
  10877. function BufferPointer() {
  10878. }
  10879. return BufferPointer;
  10880. }());
  10881. /**
  10882. * Interface for attribute information associated with buffer instanciation
  10883. */
  10884. var InstancingAttributeInfo = /** @class */ (function () {
  10885. function InstancingAttributeInfo() {
  10886. }
  10887. return InstancingAttributeInfo;
  10888. }());
  10889. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10890. /**
  10891. * Define options used to create a render target texture
  10892. */
  10893. var RenderTargetCreationOptions = /** @class */ (function () {
  10894. function RenderTargetCreationOptions() {
  10895. }
  10896. return RenderTargetCreationOptions;
  10897. }());
  10898. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10899. /**
  10900. * Define options used to create a depth texture
  10901. */
  10902. var DepthTextureCreationOptions = /** @class */ (function () {
  10903. function DepthTextureCreationOptions() {
  10904. }
  10905. return DepthTextureCreationOptions;
  10906. }());
  10907. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10908. /**
  10909. * Class used to describe the capabilities of the engine relatively to the current browser
  10910. */
  10911. var EngineCapabilities = /** @class */ (function () {
  10912. function EngineCapabilities() {
  10913. }
  10914. return EngineCapabilities;
  10915. }());
  10916. BABYLON.EngineCapabilities = EngineCapabilities;
  10917. /**
  10918. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10919. */
  10920. var Engine = /** @class */ (function () {
  10921. /**
  10922. * Creates a new engine
  10923. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10924. * @param antialias defines enable antialiasing (default: false)
  10925. * @param options defines further options to be sent to the getContext() function
  10926. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10927. */
  10928. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10929. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10930. var _this = this;
  10931. // Public members
  10932. /**
  10933. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10934. */
  10935. this.forcePOTTextures = false;
  10936. /**
  10937. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10938. */
  10939. this.isFullscreen = false;
  10940. /**
  10941. * Gets a boolean indicating if the pointer is currently locked
  10942. */
  10943. this.isPointerLock = false;
  10944. /**
  10945. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10946. */
  10947. this.cullBackFaces = true;
  10948. /**
  10949. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10950. */
  10951. this.renderEvenInBackground = true;
  10952. /**
  10953. * Gets or sets a boolean indicating that cache can be kept between frames
  10954. */
  10955. this.preventCacheWipeBetweenFrames = false;
  10956. /**
  10957. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10958. **/
  10959. this.enableOfflineSupport = false;
  10960. /**
  10961. * Gets the list of created scenes
  10962. */
  10963. this.scenes = new Array();
  10964. /**
  10965. * Gets the list of created postprocesses
  10966. */
  10967. this.postProcesses = new Array();
  10968. // Observables
  10969. /**
  10970. * Observable event triggered each time the rendering canvas is resized
  10971. */
  10972. this.onResizeObservable = new BABYLON.Observable();
  10973. /**
  10974. * Observable event triggered each time the canvas loses focus
  10975. */
  10976. this.onCanvasBlurObservable = new BABYLON.Observable();
  10977. /**
  10978. * Observable event triggered each time the canvas gains focus
  10979. */
  10980. this.onCanvasFocusObservable = new BABYLON.Observable();
  10981. /**
  10982. * Observable event triggered each time the canvas receives pointerout event
  10983. */
  10984. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10985. /**
  10986. * Observable event triggered before each texture is initialized
  10987. */
  10988. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10989. //WebVR
  10990. this._vrDisplay = undefined;
  10991. this._vrSupported = false;
  10992. this._vrExclusivePointerMode = false;
  10993. // Uniform buffers list
  10994. /**
  10995. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10996. */
  10997. this.disableUniformBuffers = false;
  10998. /** @ignore */
  10999. this._uniformBuffers = new Array();
  11000. // Observables
  11001. /**
  11002. * Observable raised when the engine begins a new frame
  11003. */
  11004. this.onBeginFrameObservable = new BABYLON.Observable();
  11005. /**
  11006. * Observable raised when the engine ends the current frame
  11007. */
  11008. this.onEndFrameObservable = new BABYLON.Observable();
  11009. /**
  11010. * Observable raised when the engine is about to compile a shader
  11011. */
  11012. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11013. /**
  11014. * Observable raised when the engine has jsut compiled a shader
  11015. */
  11016. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11017. this._windowIsBackground = false;
  11018. this._webGLVersion = 1.0;
  11019. /** @ignore */
  11020. this._badOS = false;
  11021. /** @ignore */
  11022. this._badDesktopOS = false;
  11023. /**
  11024. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11025. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11026. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11027. */
  11028. this.disableTextureBindingOptimization = false;
  11029. /**
  11030. * Observable signaled when VR display mode changes
  11031. */
  11032. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11033. /**
  11034. * Observable signaled when VR request present is complete
  11035. */
  11036. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11037. /**
  11038. * Observable signaled when VR request present starts
  11039. */
  11040. this.onVRRequestPresentStart = new BABYLON.Observable();
  11041. this._colorWrite = true;
  11042. /** @ignore */
  11043. this._drawCalls = new BABYLON.PerfCounter();
  11044. /** @ignore */
  11045. this._textureCollisions = new BABYLON.PerfCounter();
  11046. this._renderingQueueLaunched = false;
  11047. this._activeRenderLoops = new Array();
  11048. // Deterministic lockstepMaxSteps
  11049. this._deterministicLockstep = false;
  11050. this._lockstepMaxSteps = 4;
  11051. // Lost context
  11052. /**
  11053. * Observable signaled when a context lost event is raised
  11054. */
  11055. this.onContextLostObservable = new BABYLON.Observable();
  11056. /**
  11057. * Observable signaled when a context restored event is raised
  11058. */
  11059. this.onContextRestoredObservable = new BABYLON.Observable();
  11060. this._contextWasLost = false;
  11061. this._doNotHandleContextLost = false;
  11062. // FPS
  11063. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11064. this._fps = 60;
  11065. this._deltaTime = 0;
  11066. /**
  11067. * Turn this value on if you want to pause FPS computation when in background
  11068. */
  11069. this.disablePerformanceMonitorInBackground = false;
  11070. // States
  11071. /** @ignore */
  11072. this._depthCullingState = new BABYLON._DepthCullingState();
  11073. /** @ignore */
  11074. this._stencilState = new BABYLON._StencilState();
  11075. /** @ignore */
  11076. this._alphaState = new BABYLON._AlphaState();
  11077. /** @ignore */
  11078. this._alphaMode = Engine.ALPHA_DISABLE;
  11079. // Cache
  11080. this._internalTexturesCache = new Array();
  11081. /** @ignore */
  11082. this._activeChannel = 0;
  11083. this._currentTextureChannel = -1;
  11084. /** @ignore */
  11085. this._boundTexturesCache = {};
  11086. this._compiledEffects = {};
  11087. this._vertexAttribArraysEnabled = [];
  11088. this._uintIndicesCurrentlySet = false;
  11089. this._currentBoundBuffer = new Array();
  11090. this._currentBufferPointers = new Array();
  11091. this._currentInstanceLocations = new Array();
  11092. this._currentInstanceBuffers = new Array();
  11093. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11094. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11095. this._vaoRecordInProgress = false;
  11096. this._mustWipeVertexAttributes = false;
  11097. this._nextFreeTextureSlots = new Array();
  11098. this._maxSimultaneousTextures = 0;
  11099. this._activeRequests = new Array();
  11100. // Hardware supported Compressed Textures
  11101. this._texturesSupported = new Array();
  11102. this._onVRFullScreenTriggered = function () {
  11103. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11104. //get the old size before we change
  11105. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11106. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11107. //get the width and height, change the render size
  11108. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11109. _this.setHardwareScalingLevel(1);
  11110. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11111. }
  11112. else {
  11113. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11114. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11115. }
  11116. };
  11117. this._boundUniforms = {};
  11118. // Register promises
  11119. BABYLON.PromisePolyfill.Apply();
  11120. var canvas = null;
  11121. Engine.Instances.push(this);
  11122. if (!canvasOrContext) {
  11123. return;
  11124. }
  11125. options = options || {};
  11126. if (canvasOrContext.getContext) {
  11127. canvas = canvasOrContext;
  11128. this._renderingCanvas = canvas;
  11129. if (antialias != null) {
  11130. options.antialias = antialias;
  11131. }
  11132. if (options.deterministicLockstep === undefined) {
  11133. options.deterministicLockstep = false;
  11134. }
  11135. if (options.lockstepMaxSteps === undefined) {
  11136. options.lockstepMaxSteps = 4;
  11137. }
  11138. if (options.preserveDrawingBuffer === undefined) {
  11139. options.preserveDrawingBuffer = false;
  11140. }
  11141. if (options.audioEngine === undefined) {
  11142. options.audioEngine = true;
  11143. }
  11144. if (options.stencil === undefined) {
  11145. options.stencil = true;
  11146. }
  11147. this._deterministicLockstep = options.deterministicLockstep;
  11148. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11149. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11150. // Exceptions
  11151. if (navigator && navigator.userAgent) {
  11152. var ua = navigator.userAgent;
  11153. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11154. var exception = _a[_i];
  11155. var key = exception.key;
  11156. var targets = exception.targets;
  11157. if (ua.indexOf(key) > -1) {
  11158. if (exception.capture && exception.captureConstraint) {
  11159. var capture = exception.capture;
  11160. var constraint = exception.captureConstraint;
  11161. var regex = new RegExp(capture);
  11162. var matches = regex.exec(ua);
  11163. if (matches && matches.length > 0) {
  11164. var capturedValue = parseInt(matches[matches.length - 1]);
  11165. if (capturedValue >= constraint) {
  11166. continue;
  11167. }
  11168. }
  11169. }
  11170. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11171. var target = targets_1[_b];
  11172. switch (target) {
  11173. case "uniformBuffer":
  11174. this.disableUniformBuffers = true;
  11175. break;
  11176. case "textureBindingOptimization":
  11177. this.disableTextureBindingOptimization = true;
  11178. break;
  11179. }
  11180. }
  11181. }
  11182. }
  11183. }
  11184. // GL
  11185. if (!options.disableWebGL2Support) {
  11186. try {
  11187. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11188. if (this._gl) {
  11189. this._webGLVersion = 2.0;
  11190. }
  11191. }
  11192. catch (e) {
  11193. // Do nothing
  11194. }
  11195. }
  11196. if (!this._gl) {
  11197. if (!canvas) {
  11198. throw new Error("The provided canvas is null or undefined.");
  11199. }
  11200. try {
  11201. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11202. }
  11203. catch (e) {
  11204. throw new Error("WebGL not supported");
  11205. }
  11206. }
  11207. if (!this._gl) {
  11208. throw new Error("WebGL not supported");
  11209. }
  11210. this._onCanvasFocus = function () {
  11211. _this.onCanvasFocusObservable.notifyObservers(_this);
  11212. };
  11213. this._onCanvasBlur = function () {
  11214. _this.onCanvasBlurObservable.notifyObservers(_this);
  11215. };
  11216. canvas.addEventListener("focus", this._onCanvasFocus);
  11217. canvas.addEventListener("blur", this._onCanvasBlur);
  11218. this._onBlur = function () {
  11219. if (_this.disablePerformanceMonitorInBackground) {
  11220. _this._performanceMonitor.disable();
  11221. }
  11222. _this._windowIsBackground = true;
  11223. };
  11224. this._onFocus = function () {
  11225. if (_this.disablePerformanceMonitorInBackground) {
  11226. _this._performanceMonitor.enable();
  11227. }
  11228. _this._windowIsBackground = false;
  11229. };
  11230. this._onCanvasPointerOut = function (ev) {
  11231. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11232. };
  11233. window.addEventListener("blur", this._onBlur);
  11234. window.addEventListener("focus", this._onFocus);
  11235. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11236. // Context lost
  11237. if (!this._doNotHandleContextLost) {
  11238. this._onContextLost = function (evt) {
  11239. evt.preventDefault();
  11240. _this._contextWasLost = true;
  11241. BABYLON.Tools.Warn("WebGL context lost.");
  11242. _this.onContextLostObservable.notifyObservers(_this);
  11243. };
  11244. this._onContextRestored = function (evt) {
  11245. // Adding a timeout to avoid race condition at browser level
  11246. setTimeout(function () {
  11247. // Rebuild gl context
  11248. _this._initGLContext();
  11249. // Rebuild effects
  11250. _this._rebuildEffects();
  11251. // Rebuild textures
  11252. _this._rebuildInternalTextures();
  11253. // Rebuild buffers
  11254. _this._rebuildBuffers();
  11255. // Cache
  11256. _this.wipeCaches(true);
  11257. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11258. _this.onContextRestoredObservable.notifyObservers(_this);
  11259. _this._contextWasLost = false;
  11260. }, 0);
  11261. };
  11262. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11263. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11264. }
  11265. }
  11266. else {
  11267. this._gl = canvasOrContext;
  11268. this._renderingCanvas = this._gl.canvas;
  11269. if (this._gl.renderbufferStorageMultisample) {
  11270. this._webGLVersion = 2.0;
  11271. }
  11272. options.stencil = this._gl.getContextAttributes().stencil;
  11273. }
  11274. // Viewport
  11275. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11276. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11277. this.resize();
  11278. this._isStencilEnable = options.stencil ? true : false;
  11279. this._initGLContext();
  11280. if (canvas) {
  11281. // Fullscreen
  11282. this._onFullscreenChange = function () {
  11283. if (document.fullscreen !== undefined) {
  11284. _this.isFullscreen = document.fullscreen;
  11285. }
  11286. else if (document.mozFullScreen !== undefined) {
  11287. _this.isFullscreen = document.mozFullScreen;
  11288. }
  11289. else if (document.webkitIsFullScreen !== undefined) {
  11290. _this.isFullscreen = document.webkitIsFullScreen;
  11291. }
  11292. else if (document.msIsFullScreen !== undefined) {
  11293. _this.isFullscreen = document.msIsFullScreen;
  11294. }
  11295. // Pointer lock
  11296. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11297. canvas.requestPointerLock = canvas.requestPointerLock ||
  11298. canvas.msRequestPointerLock ||
  11299. canvas.mozRequestPointerLock ||
  11300. canvas.webkitRequestPointerLock;
  11301. if (canvas.requestPointerLock) {
  11302. canvas.requestPointerLock();
  11303. }
  11304. }
  11305. };
  11306. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11307. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11308. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11309. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11310. // Pointer lock
  11311. this._onPointerLockChange = function () {
  11312. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11313. document.webkitPointerLockElement === canvas ||
  11314. document.msPointerLockElement === canvas ||
  11315. document.pointerLockElement === canvas);
  11316. };
  11317. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11318. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11319. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11320. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11321. this._onVRDisplayPointerRestricted = function () {
  11322. if (canvas) {
  11323. canvas.requestPointerLock();
  11324. }
  11325. };
  11326. this._onVRDisplayPointerUnrestricted = function () {
  11327. document.exitPointerLock();
  11328. };
  11329. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11330. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11331. }
  11332. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11333. Engine.audioEngine = new BABYLON.AudioEngine();
  11334. }
  11335. // Prepare buffer pointers
  11336. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11337. this._currentBufferPointers[i] = new BufferPointer();
  11338. }
  11339. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11340. // Load WebVR Devices
  11341. if (options.autoEnableWebVR) {
  11342. this.initWebVR();
  11343. }
  11344. // Detect if we are running on a faulty buggy OS.
  11345. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11346. // Detect if we are running on a faulty buggy desktop OS.
  11347. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11348. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11349. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11350. }
  11351. Object.defineProperty(Engine, "LastCreatedEngine", {
  11352. /**
  11353. * Gets the latest created engine
  11354. */
  11355. get: function () {
  11356. if (Engine.Instances.length === 0) {
  11357. return null;
  11358. }
  11359. return Engine.Instances[Engine.Instances.length - 1];
  11360. },
  11361. enumerable: true,
  11362. configurable: true
  11363. });
  11364. Object.defineProperty(Engine, "LastCreatedScene", {
  11365. /**
  11366. * Gets the latest created scene
  11367. */
  11368. get: function () {
  11369. var lastCreatedEngine = Engine.LastCreatedEngine;
  11370. if (!lastCreatedEngine) {
  11371. return null;
  11372. }
  11373. if (lastCreatedEngine.scenes.length === 0) {
  11374. return null;
  11375. }
  11376. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11377. },
  11378. enumerable: true,
  11379. configurable: true
  11380. });
  11381. /**
  11382. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11383. * @param flag defines which part of the materials must be marked as dirty
  11384. * @param predicate defines a predicate used to filter which materials should be affected
  11385. */
  11386. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11387. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11388. var engine = Engine.Instances[engineIndex];
  11389. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11390. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11391. }
  11392. }
  11393. };
  11394. Object.defineProperty(Engine, "NEVER", {
  11395. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11396. get: function () {
  11397. return Engine._NEVER;
  11398. },
  11399. enumerable: true,
  11400. configurable: true
  11401. });
  11402. Object.defineProperty(Engine, "ALWAYS", {
  11403. /** 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 */
  11404. get: function () {
  11405. return Engine._ALWAYS;
  11406. },
  11407. enumerable: true,
  11408. configurable: true
  11409. });
  11410. Object.defineProperty(Engine, "LESS", {
  11411. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11412. get: function () {
  11413. return Engine._LESS;
  11414. },
  11415. enumerable: true,
  11416. configurable: true
  11417. });
  11418. Object.defineProperty(Engine, "EQUAL", {
  11419. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11420. get: function () {
  11421. return Engine._EQUAL;
  11422. },
  11423. enumerable: true,
  11424. configurable: true
  11425. });
  11426. Object.defineProperty(Engine, "LEQUAL", {
  11427. /** 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 */
  11428. get: function () {
  11429. return Engine._LEQUAL;
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. Object.defineProperty(Engine, "GREATER", {
  11435. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11436. get: function () {
  11437. return Engine._GREATER;
  11438. },
  11439. enumerable: true,
  11440. configurable: true
  11441. });
  11442. Object.defineProperty(Engine, "GEQUAL", {
  11443. /** 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 */
  11444. get: function () {
  11445. return Engine._GEQUAL;
  11446. },
  11447. enumerable: true,
  11448. configurable: true
  11449. });
  11450. Object.defineProperty(Engine, "NOTEQUAL", {
  11451. /** 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 */
  11452. get: function () {
  11453. return Engine._NOTEQUAL;
  11454. },
  11455. enumerable: true,
  11456. configurable: true
  11457. });
  11458. Object.defineProperty(Engine, "KEEP", {
  11459. /** Passed to stencilOperation to specify that stencil value must be kept */
  11460. get: function () {
  11461. return Engine._KEEP;
  11462. },
  11463. enumerable: true,
  11464. configurable: true
  11465. });
  11466. Object.defineProperty(Engine, "REPLACE", {
  11467. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11468. get: function () {
  11469. return Engine._REPLACE;
  11470. },
  11471. enumerable: true,
  11472. configurable: true
  11473. });
  11474. Object.defineProperty(Engine, "INCR", {
  11475. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11476. get: function () {
  11477. return Engine._INCR;
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(Engine, "DECR", {
  11483. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11484. get: function () {
  11485. return Engine._DECR;
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. Object.defineProperty(Engine, "INVERT", {
  11491. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11492. get: function () {
  11493. return Engine._INVERT;
  11494. },
  11495. enumerable: true,
  11496. configurable: true
  11497. });
  11498. Object.defineProperty(Engine, "INCR_WRAP", {
  11499. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11500. get: function () {
  11501. return Engine._INCR_WRAP;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Object.defineProperty(Engine, "DECR_WRAP", {
  11507. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11508. get: function () {
  11509. return Engine._DECR_WRAP;
  11510. },
  11511. enumerable: true,
  11512. configurable: true
  11513. });
  11514. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11515. // Alpha
  11516. /** Defines that alpha blending is disabled */
  11517. get: function () {
  11518. return Engine._ALPHA_DISABLE;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11524. /** Defines that alpha blending to SRC + DEST */
  11525. get: function () {
  11526. return Engine._ALPHA_ONEONE;
  11527. },
  11528. enumerable: true,
  11529. configurable: true
  11530. });
  11531. Object.defineProperty(Engine, "ALPHA_ADD", {
  11532. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11533. get: function () {
  11534. return Engine._ALPHA_ADD;
  11535. },
  11536. enumerable: true,
  11537. configurable: true
  11538. });
  11539. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11540. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11541. get: function () {
  11542. return Engine._ALPHA_COMBINE;
  11543. },
  11544. enumerable: true,
  11545. configurable: true
  11546. });
  11547. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11548. /** Defines that alpha blending to DEST - SRC * DEST */
  11549. get: function () {
  11550. return Engine._ALPHA_SUBTRACT;
  11551. },
  11552. enumerable: true,
  11553. configurable: true
  11554. });
  11555. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11556. /** Defines that alpha blending to SRC * DEST */
  11557. get: function () {
  11558. return Engine._ALPHA_MULTIPLY;
  11559. },
  11560. enumerable: true,
  11561. configurable: true
  11562. });
  11563. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11564. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11565. get: function () {
  11566. return Engine._ALPHA_MAXIMIZED;
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11572. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11573. get: function () {
  11574. return Engine._ALPHA_PREMULTIPLIED;
  11575. },
  11576. enumerable: true,
  11577. configurable: true
  11578. });
  11579. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11580. /**
  11581. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11582. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11583. */
  11584. get: function () {
  11585. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11586. },
  11587. enumerable: true,
  11588. configurable: true
  11589. });
  11590. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11591. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11592. get: function () {
  11593. return Engine._ALPHA_INTERPOLATE;
  11594. },
  11595. enumerable: true,
  11596. configurable: true
  11597. });
  11598. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11599. /**
  11600. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11601. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11602. */
  11603. get: function () {
  11604. return Engine._ALPHA_SCREENMODE;
  11605. },
  11606. enumerable: true,
  11607. configurable: true
  11608. });
  11609. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11610. // Delays
  11611. /** Defines that the ressource is not delayed*/
  11612. get: function () {
  11613. return Engine._DELAYLOADSTATE_NONE;
  11614. },
  11615. enumerable: true,
  11616. configurable: true
  11617. });
  11618. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11619. /** Defines that the ressource was successfully delay loaded */
  11620. get: function () {
  11621. return Engine._DELAYLOADSTATE_LOADED;
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11627. /** Defines that the ressource is currently delay loading */
  11628. get: function () {
  11629. return Engine._DELAYLOADSTATE_LOADING;
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11635. /** Defines that the ressource is delayed and has not started loading */
  11636. get: function () {
  11637. return Engine._DELAYLOADSTATE_NOTLOADED;
  11638. },
  11639. enumerable: true,
  11640. configurable: true
  11641. });
  11642. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11643. /** ALPHA */
  11644. get: function () {
  11645. return Engine._TEXTUREFORMAT_ALPHA;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11651. /** LUMINANCE */
  11652. get: function () {
  11653. return Engine._TEXTUREFORMAT_LUMINANCE;
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11659. /**
  11660. * R32F
  11661. */
  11662. get: function () {
  11663. return Engine._TEXTUREFORMAT_R32F;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11669. /**
  11670. * RG32F
  11671. */
  11672. get: function () {
  11673. return Engine._TEXTUREFORMAT_RG32F;
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11679. /**
  11680. * RGB32F
  11681. */
  11682. get: function () {
  11683. return Engine._TEXTUREFORMAT_RGB32F;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11689. /**
  11690. * RGBA32F
  11691. */
  11692. get: function () {
  11693. return Engine._TEXTUREFORMAT_RGBA32F;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11699. /** LUMINANCE_ALPHA */
  11700. get: function () {
  11701. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11707. /** RGB */
  11708. get: function () {
  11709. return Engine._TEXTUREFORMAT_RGB;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11715. /** RGBA */
  11716. get: function () {
  11717. return Engine._TEXTUREFORMAT_RGBA;
  11718. },
  11719. enumerable: true,
  11720. configurable: true
  11721. });
  11722. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11723. /** UNSIGNED_INT */
  11724. get: function () {
  11725. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11731. /** FLOAT */
  11732. get: function () {
  11733. return Engine._TEXTURETYPE_FLOAT;
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11739. /** HALF_FLOAT */
  11740. get: function () {
  11741. return Engine._TEXTURETYPE_HALF_FLOAT;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11747. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11748. get: function () {
  11749. return Engine._SCALEMODE_FLOOR;
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11755. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11756. get: function () {
  11757. return Engine._SCALEMODE_NEAREST;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11763. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11764. get: function () {
  11765. return Engine._SCALEMODE_CEILING;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(Engine, "Version", {
  11771. /**
  11772. * Returns the current version of the framework
  11773. */
  11774. get: function () {
  11775. return "3.2.0-beta.5";
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11781. /**
  11782. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11783. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11784. */
  11785. get: function () {
  11786. return this._vrExclusivePointerMode;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11792. /**
  11793. * Gets a boolean indicating that the engine supports uniform buffers
  11794. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11795. */
  11796. get: function () {
  11797. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11803. /**
  11804. * Gets a boolean indicating that only power of 2 textures are supported
  11805. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11806. */
  11807. get: function () {
  11808. return this._webGLVersion < 2 || this.forcePOTTextures;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11814. /**
  11815. * Gets the performance monitor attached to this engine
  11816. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11817. */
  11818. get: function () {
  11819. return this._performanceMonitor;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11825. /**
  11826. * Gets the list of texture formats supported
  11827. */
  11828. get: function () {
  11829. return this._texturesSupported;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11835. /**
  11836. * Gets the list of texture formats in use
  11837. */
  11838. get: function () {
  11839. return this._textureFormatInUse;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine.prototype, "currentViewport", {
  11845. /**
  11846. * Gets the current viewport
  11847. */
  11848. get: function () {
  11849. return this._cachedViewport;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11855. /**
  11856. * Gets the default empty texture
  11857. */
  11858. get: function () {
  11859. if (!this._emptyTexture) {
  11860. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11861. }
  11862. return this._emptyTexture;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11868. /**
  11869. * Gets the default empty 3D texture
  11870. */
  11871. get: function () {
  11872. if (!this._emptyTexture3D) {
  11873. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11874. }
  11875. return this._emptyTexture3D;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11881. /**
  11882. * Gets the default empty cube texture
  11883. */
  11884. get: function () {
  11885. if (!this._emptyCubeTexture) {
  11886. var faceData = new Uint8Array(4);
  11887. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11888. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11889. }
  11890. return this._emptyCubeTexture;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Engine.prototype._rebuildInternalTextures = function () {
  11896. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11897. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11898. var internalTexture = currentState_1[_i];
  11899. internalTexture._rebuild();
  11900. }
  11901. };
  11902. Engine.prototype._rebuildEffects = function () {
  11903. for (var key in this._compiledEffects) {
  11904. var effect = this._compiledEffects[key];
  11905. effect._prepareEffect();
  11906. }
  11907. BABYLON.Effect.ResetCache();
  11908. };
  11909. Engine.prototype._rebuildBuffers = function () {
  11910. // Index / Vertex
  11911. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11912. var scene = _a[_i];
  11913. scene.resetCachedMaterial();
  11914. scene._rebuildGeometries();
  11915. scene._rebuildTextures();
  11916. }
  11917. // Uniforms
  11918. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11919. var uniformBuffer = _c[_b];
  11920. uniformBuffer._rebuild();
  11921. }
  11922. };
  11923. Engine.prototype._initGLContext = function () {
  11924. // Caps
  11925. this._caps = new EngineCapabilities();
  11926. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11927. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11928. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11929. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11930. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11931. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11932. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11933. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11934. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11935. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11936. // Infos
  11937. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11938. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11939. if (rendererInfo != null) {
  11940. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11941. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11942. }
  11943. if (!this._glVendor) {
  11944. this._glVendor = "Unknown vendor";
  11945. }
  11946. if (!this._glRenderer) {
  11947. this._glRenderer = "Unknown renderer";
  11948. }
  11949. // Constants
  11950. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11951. if (this._gl.RGBA16F !== 0x881A) {
  11952. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11953. }
  11954. if (this._gl.RGBA32F !== 0x8814) {
  11955. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11956. }
  11957. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11958. this._gl.DEPTH24_STENCIL8 = 35056;
  11959. }
  11960. // Extensions
  11961. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11962. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11963. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11964. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11965. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11966. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11967. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11968. 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');
  11969. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11970. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11971. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11972. this._caps.highPrecisionShaderSupported = true;
  11973. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11974. if (this._caps.timerQuery) {
  11975. if (this._webGLVersion === 1) {
  11976. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11977. }
  11978. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11979. }
  11980. // Checks if some of the format renders first to allow the use of webgl inspector.
  11981. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11982. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11983. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11984. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11985. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11986. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11987. if (this._webGLVersion > 1) {
  11988. this._gl.HALF_FLOAT_OES = 0x140B;
  11989. }
  11990. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11991. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11992. // Draw buffers
  11993. if (this._webGLVersion > 1) {
  11994. this._caps.drawBuffersExtension = true;
  11995. }
  11996. else {
  11997. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11998. if (drawBuffersExtension !== null) {
  11999. this._caps.drawBuffersExtension = true;
  12000. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12001. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12002. for (var i = 0; i < 16; i++) {
  12003. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12004. }
  12005. }
  12006. else {
  12007. this._caps.drawBuffersExtension = false;
  12008. }
  12009. }
  12010. // Depth Texture
  12011. if (this._webGLVersion > 1) {
  12012. this._caps.depthTextureExtension = true;
  12013. }
  12014. else {
  12015. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12016. if (depthTextureExtension != null) {
  12017. this._caps.depthTextureExtension = true;
  12018. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12019. }
  12020. }
  12021. // Vertex array object
  12022. if (this._webGLVersion > 1) {
  12023. this._caps.vertexArrayObject = true;
  12024. }
  12025. else {
  12026. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12027. if (vertexArrayObjectExtension != null) {
  12028. this._caps.vertexArrayObject = true;
  12029. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12030. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12031. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12032. }
  12033. else {
  12034. this._caps.vertexArrayObject = false;
  12035. }
  12036. }
  12037. // Instances count
  12038. if (this._webGLVersion > 1) {
  12039. this._caps.instancedArrays = true;
  12040. }
  12041. else {
  12042. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12043. if (instanceExtension != null) {
  12044. this._caps.instancedArrays = true;
  12045. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12046. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12047. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12048. }
  12049. else {
  12050. this._caps.instancedArrays = false;
  12051. }
  12052. }
  12053. // Intelligently add supported compressed formats in order to check for.
  12054. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12055. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12056. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12057. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12058. if (this._caps.astc)
  12059. this.texturesSupported.push('-astc.ktx');
  12060. if (this._caps.s3tc)
  12061. this.texturesSupported.push('-dxt.ktx');
  12062. if (this._caps.pvrtc)
  12063. this.texturesSupported.push('-pvrtc.ktx');
  12064. if (this._caps.etc2)
  12065. this.texturesSupported.push('-etc2.ktx');
  12066. if (this._caps.etc1)
  12067. this.texturesSupported.push('-etc1.ktx');
  12068. if (this._gl.getShaderPrecisionFormat) {
  12069. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12070. if (highp) {
  12071. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12072. }
  12073. }
  12074. // Depth buffer
  12075. this.setDepthBuffer(true);
  12076. this.setDepthFunctionToLessOrEqual();
  12077. this.setDepthWrite(true);
  12078. // Texture maps
  12079. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12080. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12081. this._nextFreeTextureSlots.push(slot);
  12082. }
  12083. };
  12084. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12085. /**
  12086. * Gets version of the current webGL context
  12087. */
  12088. get: function () {
  12089. return this._webGLVersion;
  12090. },
  12091. enumerable: true,
  12092. configurable: true
  12093. });
  12094. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12095. /**
  12096. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12097. */
  12098. get: function () {
  12099. return this._isStencilEnable;
  12100. },
  12101. enumerable: true,
  12102. configurable: true
  12103. });
  12104. Engine.prototype._prepareWorkingCanvas = function () {
  12105. if (this._workingCanvas) {
  12106. return;
  12107. }
  12108. this._workingCanvas = document.createElement("canvas");
  12109. var context = this._workingCanvas.getContext("2d");
  12110. if (context) {
  12111. this._workingContext = context;
  12112. }
  12113. };
  12114. /**
  12115. * Reset the texture cache to empty state
  12116. */
  12117. Engine.prototype.resetTextureCache = function () {
  12118. for (var key in this._boundTexturesCache) {
  12119. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12120. continue;
  12121. }
  12122. var boundTexture = this._boundTexturesCache[key];
  12123. if (boundTexture) {
  12124. this._removeDesignatedSlot(boundTexture);
  12125. }
  12126. this._boundTexturesCache[key] = null;
  12127. }
  12128. if (!this.disableTextureBindingOptimization) {
  12129. this._nextFreeTextureSlots = [];
  12130. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12131. this._nextFreeTextureSlots.push(slot);
  12132. }
  12133. }
  12134. this._currentTextureChannel = -1;
  12135. };
  12136. /**
  12137. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12138. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12139. * @returns true if engine is in deterministic lock step mode
  12140. */
  12141. Engine.prototype.isDeterministicLockStep = function () {
  12142. return this._deterministicLockstep;
  12143. };
  12144. /**
  12145. * Gets the max steps when engine is running in deterministic lock step
  12146. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12147. * @returns the max steps
  12148. */
  12149. Engine.prototype.getLockstepMaxSteps = function () {
  12150. return this._lockstepMaxSteps;
  12151. };
  12152. /**
  12153. * Gets an object containing information about the current webGL context
  12154. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12155. */
  12156. Engine.prototype.getGlInfo = function () {
  12157. return {
  12158. vendor: this._glVendor,
  12159. renderer: this._glRenderer,
  12160. version: this._glVersion
  12161. };
  12162. };
  12163. /**
  12164. * Gets current aspect ratio
  12165. * @param camera defines the camera to use to get the aspect ratio
  12166. * @param useScreen defines if screen size must be used (or the current render target if any)
  12167. * @returns a number defining the aspect ratio
  12168. */
  12169. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12170. if (useScreen === void 0) { useScreen = false; }
  12171. var viewport = camera.viewport;
  12172. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12173. };
  12174. /**
  12175. * Gets the current render width
  12176. * @param useScreen defines if screen size must be used (or the current render target if any)
  12177. * @returns a number defining the current render width
  12178. */
  12179. Engine.prototype.getRenderWidth = function (useScreen) {
  12180. if (useScreen === void 0) { useScreen = false; }
  12181. if (!useScreen && this._currentRenderTarget) {
  12182. return this._currentRenderTarget.width;
  12183. }
  12184. return this._gl.drawingBufferWidth;
  12185. };
  12186. /**
  12187. * Gets the current render height
  12188. * @param useScreen defines if screen size must be used (or the current render target if any)
  12189. * @returns a number defining the current render height
  12190. */
  12191. Engine.prototype.getRenderHeight = function (useScreen) {
  12192. if (useScreen === void 0) { useScreen = false; }
  12193. if (!useScreen && this._currentRenderTarget) {
  12194. return this._currentRenderTarget.height;
  12195. }
  12196. return this._gl.drawingBufferHeight;
  12197. };
  12198. /**
  12199. * Gets the HTML canvas attached with the current webGL context
  12200. * @returns a HTML canvas
  12201. */
  12202. Engine.prototype.getRenderingCanvas = function () {
  12203. return this._renderingCanvas;
  12204. };
  12205. /**
  12206. * Gets the client rect of the HTML canvas attached with the current webGL context
  12207. * @returns a client rectanglee
  12208. */
  12209. Engine.prototype.getRenderingCanvasClientRect = function () {
  12210. if (!this._renderingCanvas) {
  12211. return null;
  12212. }
  12213. return this._renderingCanvas.getBoundingClientRect();
  12214. };
  12215. /**
  12216. * Defines the hardware scaling level.
  12217. * By default the hardware scaling level is computed from the window device ratio.
  12218. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12219. * @param level defines the level to use
  12220. */
  12221. Engine.prototype.setHardwareScalingLevel = function (level) {
  12222. this._hardwareScalingLevel = level;
  12223. this.resize();
  12224. };
  12225. /**
  12226. * Gets the current hardware scaling level.
  12227. * By default the hardware scaling level is computed from the window device ratio.
  12228. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12229. * @returns a number indicating the current hardware scaling level
  12230. */
  12231. Engine.prototype.getHardwareScalingLevel = function () {
  12232. return this._hardwareScalingLevel;
  12233. };
  12234. /**
  12235. * Gets the list of loaded textures
  12236. * @returns an array containing all loaded textures
  12237. */
  12238. Engine.prototype.getLoadedTexturesCache = function () {
  12239. return this._internalTexturesCache;
  12240. };
  12241. /**
  12242. * Gets the object containing all engine capabilities
  12243. * @returns the EngineCapabilities object
  12244. */
  12245. Engine.prototype.getCaps = function () {
  12246. return this._caps;
  12247. };
  12248. Object.defineProperty(Engine.prototype, "drawCalls", {
  12249. /** @ignore */
  12250. get: function () {
  12251. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12252. return 0;
  12253. },
  12254. enumerable: true,
  12255. configurable: true
  12256. });
  12257. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12258. /** @ignore */
  12259. get: function () {
  12260. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12261. return null;
  12262. },
  12263. enumerable: true,
  12264. configurable: true
  12265. });
  12266. /**
  12267. * Gets the current depth function
  12268. * @returns a number defining the depth function
  12269. */
  12270. Engine.prototype.getDepthFunction = function () {
  12271. return this._depthCullingState.depthFunc;
  12272. };
  12273. /**
  12274. * Sets the current depth function
  12275. * @param depthFunc defines the function to use
  12276. */
  12277. Engine.prototype.setDepthFunction = function (depthFunc) {
  12278. this._depthCullingState.depthFunc = depthFunc;
  12279. };
  12280. /**
  12281. * Sets the current depth function to GREATER
  12282. */
  12283. Engine.prototype.setDepthFunctionToGreater = function () {
  12284. this._depthCullingState.depthFunc = this._gl.GREATER;
  12285. };
  12286. /**
  12287. * Sets the current depth function to GEQUAL
  12288. */
  12289. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12290. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12291. };
  12292. /**
  12293. * Sets the current depth function to LESS
  12294. */
  12295. Engine.prototype.setDepthFunctionToLess = function () {
  12296. this._depthCullingState.depthFunc = this._gl.LESS;
  12297. };
  12298. /**
  12299. * Sets the current depth function to LEQUAL
  12300. */
  12301. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12302. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12303. };
  12304. /**
  12305. * Gets a boolean indicating if stencil buffer is enabled
  12306. * @returns the current stencil buffer state
  12307. */
  12308. Engine.prototype.getStencilBuffer = function () {
  12309. return this._stencilState.stencilTest;
  12310. };
  12311. /**
  12312. * Enable or disable the stencil buffer
  12313. * @param enable defines if the stencil buffer must be enabled or disabled
  12314. */
  12315. Engine.prototype.setStencilBuffer = function (enable) {
  12316. this._stencilState.stencilTest = enable;
  12317. };
  12318. /**
  12319. * Gets the current stencil mask
  12320. * @returns a number defining the new stencil mask to use
  12321. */
  12322. Engine.prototype.getStencilMask = function () {
  12323. return this._stencilState.stencilMask;
  12324. };
  12325. /**
  12326. * Sets the current stencil mask
  12327. * @param mask defines the new stencil mask to use
  12328. */
  12329. Engine.prototype.setStencilMask = function (mask) {
  12330. this._stencilState.stencilMask = mask;
  12331. };
  12332. /**
  12333. * Gets the current stencil function
  12334. * @returns a number defining the stencil function to use
  12335. */
  12336. Engine.prototype.getStencilFunction = function () {
  12337. return this._stencilState.stencilFunc;
  12338. };
  12339. /**
  12340. * Gets the current stencil reference value
  12341. * @returns a number defining the stencil reference value to use
  12342. */
  12343. Engine.prototype.getStencilFunctionReference = function () {
  12344. return this._stencilState.stencilFuncRef;
  12345. };
  12346. /**
  12347. * Gets the current stencil mask
  12348. * @returns a number defining the stencil mask to use
  12349. */
  12350. Engine.prototype.getStencilFunctionMask = function () {
  12351. return this._stencilState.stencilFuncMask;
  12352. };
  12353. /**
  12354. * Sets the current stencil function
  12355. * @param stencilFunc defines the new stencil function to use
  12356. */
  12357. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12358. this._stencilState.stencilFunc = stencilFunc;
  12359. };
  12360. /**
  12361. * Sets the current stencil reference
  12362. * @param reference defines the new stencil reference to use
  12363. */
  12364. Engine.prototype.setStencilFunctionReference = function (reference) {
  12365. this._stencilState.stencilFuncRef = reference;
  12366. };
  12367. /**
  12368. * Sets the current stencil mask
  12369. * @param mask defines the new stencil mask to use
  12370. */
  12371. Engine.prototype.setStencilFunctionMask = function (mask) {
  12372. this._stencilState.stencilFuncMask = mask;
  12373. };
  12374. /**
  12375. * Gets the current stencil operation when stencil fails
  12376. * @returns a number defining stencil operation to use when stencil fails
  12377. */
  12378. Engine.prototype.getStencilOperationFail = function () {
  12379. return this._stencilState.stencilOpStencilFail;
  12380. };
  12381. /**
  12382. * Gets the current stencil operation when depth fails
  12383. * @returns a number defining stencil operation to use when depth fails
  12384. */
  12385. Engine.prototype.getStencilOperationDepthFail = function () {
  12386. return this._stencilState.stencilOpDepthFail;
  12387. };
  12388. /**
  12389. * Gets the current stencil operation when stencil passes
  12390. * @returns a number defining stencil operation to use when stencil passes
  12391. */
  12392. Engine.prototype.getStencilOperationPass = function () {
  12393. return this._stencilState.stencilOpStencilDepthPass;
  12394. };
  12395. /**
  12396. * Sets the stencil operation to use when stencil fails
  12397. * @param operation defines the stencil operation to use when stencil fails
  12398. */
  12399. Engine.prototype.setStencilOperationFail = function (operation) {
  12400. this._stencilState.stencilOpStencilFail = operation;
  12401. };
  12402. /**
  12403. * Sets the stencil operation to use when depth fails
  12404. * @param operation defines the stencil operation to use when depth fails
  12405. */
  12406. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12407. this._stencilState.stencilOpDepthFail = operation;
  12408. };
  12409. /**
  12410. * Sets the stencil operation to use when stencil passes
  12411. * @param operation defines the stencil operation to use when stencil passes
  12412. */
  12413. Engine.prototype.setStencilOperationPass = function (operation) {
  12414. this._stencilState.stencilOpStencilDepthPass = operation;
  12415. };
  12416. /**
  12417. * Sets a boolean indicating if the dithering state is enabled or disabled
  12418. * @param value defines the dithering state
  12419. */
  12420. Engine.prototype.setDitheringState = function (value) {
  12421. if (value) {
  12422. this._gl.enable(this._gl.DITHER);
  12423. }
  12424. else {
  12425. this._gl.disable(this._gl.DITHER);
  12426. }
  12427. };
  12428. /**
  12429. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12430. * @param value defines the rasterizer state
  12431. */
  12432. Engine.prototype.setRasterizerState = function (value) {
  12433. if (value) {
  12434. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12435. }
  12436. else {
  12437. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12438. }
  12439. };
  12440. /**
  12441. * stop executing a render loop function and remove it from the execution array
  12442. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12443. */
  12444. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12445. if (!renderFunction) {
  12446. this._activeRenderLoops = [];
  12447. return;
  12448. }
  12449. var index = this._activeRenderLoops.indexOf(renderFunction);
  12450. if (index >= 0) {
  12451. this._activeRenderLoops.splice(index, 1);
  12452. }
  12453. };
  12454. /** @ignore */
  12455. Engine.prototype._renderLoop = function () {
  12456. if (!this._contextWasLost) {
  12457. var shouldRender = true;
  12458. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12459. shouldRender = false;
  12460. }
  12461. if (shouldRender) {
  12462. // Start new frame
  12463. this.beginFrame();
  12464. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12465. var renderFunction = this._activeRenderLoops[index];
  12466. renderFunction();
  12467. }
  12468. // Present
  12469. this.endFrame();
  12470. }
  12471. }
  12472. if (this._activeRenderLoops.length > 0) {
  12473. // Register new frame
  12474. var requester = null;
  12475. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12476. requester = this._vrDisplay;
  12477. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12478. }
  12479. else {
  12480. this._renderingQueueLaunched = false;
  12481. }
  12482. };
  12483. /**
  12484. * Register and execute a render loop. The engine can have more than one render function
  12485. * @param renderFunction defines the function to continuously execute
  12486. */
  12487. Engine.prototype.runRenderLoop = function (renderFunction) {
  12488. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12489. return;
  12490. }
  12491. this._activeRenderLoops.push(renderFunction);
  12492. if (!this._renderingQueueLaunched) {
  12493. this._renderingQueueLaunched = true;
  12494. this._bindedRenderFunction = this._renderLoop.bind(this);
  12495. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12496. }
  12497. };
  12498. /**
  12499. * Toggle full screen mode
  12500. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12501. * @param options defines an option object to be sent to the requestFullscreen function
  12502. */
  12503. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12504. if (this.isFullscreen) {
  12505. BABYLON.Tools.ExitFullscreen();
  12506. }
  12507. else {
  12508. this._pointerLockRequested = requestPointerLock;
  12509. if (this._renderingCanvas) {
  12510. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12511. }
  12512. }
  12513. };
  12514. /**
  12515. * Clear the current render buffer or the current render target (if any is set up)
  12516. * @param color defines the color to use
  12517. * @param backBuffer defines if the back buffer must be cleared
  12518. * @param depth defines if the depth buffer must be cleared
  12519. * @param stencil defines if the stencil buffer must be cleared
  12520. */
  12521. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12522. if (stencil === void 0) { stencil = false; }
  12523. this.applyStates();
  12524. var mode = 0;
  12525. if (backBuffer && color) {
  12526. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12527. mode |= this._gl.COLOR_BUFFER_BIT;
  12528. }
  12529. if (depth) {
  12530. this._gl.clearDepth(1.0);
  12531. mode |= this._gl.DEPTH_BUFFER_BIT;
  12532. }
  12533. if (stencil) {
  12534. this._gl.clearStencil(0);
  12535. mode |= this._gl.STENCIL_BUFFER_BIT;
  12536. }
  12537. this._gl.clear(mode);
  12538. };
  12539. /**
  12540. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12541. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12542. * @param y defines the y-coordinate of the corner of the clear rectangle
  12543. * @param width defines the width of the clear rectangle
  12544. * @param height defines the height of the clear rectangle
  12545. * @param clearColor defines the clear color
  12546. */
  12547. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12548. var gl = this._gl;
  12549. // Save state
  12550. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12551. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12552. // Change state
  12553. gl.enable(gl.SCISSOR_TEST);
  12554. gl.scissor(x, y, width, height);
  12555. // Clear
  12556. this.clear(clearColor, true, true, true);
  12557. // Restore state
  12558. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12559. if (curScissor === true) {
  12560. gl.enable(gl.SCISSOR_TEST);
  12561. }
  12562. else {
  12563. gl.disable(gl.SCISSOR_TEST);
  12564. }
  12565. };
  12566. /**
  12567. * Set the WebGL's viewport
  12568. * @param viewport defines the viewport element to be used
  12569. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12570. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12571. */
  12572. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12573. var width = requiredWidth || this.getRenderWidth();
  12574. var height = requiredHeight || this.getRenderHeight();
  12575. var x = viewport.x || 0;
  12576. var y = viewport.y || 0;
  12577. this._cachedViewport = viewport;
  12578. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12579. };
  12580. /**
  12581. * Directly set the WebGL Viewport
  12582. * @param x defines the x coordinate of the viewport (in screen space)
  12583. * @param y defines the y coordinate of the viewport (in screen space)
  12584. * @param width defines the width of the viewport (in screen space)
  12585. * @param height defines the height of the viewport (in screen space)
  12586. * @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
  12587. */
  12588. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12589. var currentViewport = this._cachedViewport;
  12590. this._cachedViewport = null;
  12591. this._gl.viewport(x, y, width, height);
  12592. return currentViewport;
  12593. };
  12594. /**
  12595. * Begin a new frame
  12596. */
  12597. Engine.prototype.beginFrame = function () {
  12598. this.onBeginFrameObservable.notifyObservers(this);
  12599. this._measureFps();
  12600. };
  12601. /**
  12602. * Enf the current frame
  12603. */
  12604. Engine.prototype.endFrame = function () {
  12605. // Force a flush in case we are using a bad OS.
  12606. if (this._badOS) {
  12607. this.flushFramebuffer();
  12608. }
  12609. // Submit frame to the vr device, if enabled
  12610. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12611. // TODO: We should only submit the frame if we read frameData successfully.
  12612. this._vrDisplay.submitFrame();
  12613. }
  12614. this.onEndFrameObservable.notifyObservers(this);
  12615. };
  12616. /**
  12617. * Resize the view according to the canvas' size
  12618. */
  12619. Engine.prototype.resize = function () {
  12620. // We're not resizing the size of the canvas while in VR mode & presenting
  12621. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12622. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12623. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12624. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12625. }
  12626. };
  12627. /**
  12628. * Force a specific size of the canvas
  12629. * @param width defines the new canvas' width
  12630. * @param height defines the new canvas' height
  12631. */
  12632. Engine.prototype.setSize = function (width, height) {
  12633. if (!this._renderingCanvas) {
  12634. return;
  12635. }
  12636. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12637. return;
  12638. }
  12639. this._renderingCanvas.width = width;
  12640. this._renderingCanvas.height = height;
  12641. for (var index = 0; index < this.scenes.length; index++) {
  12642. var scene = this.scenes[index];
  12643. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12644. var cam = scene.cameras[camIndex];
  12645. cam._currentRenderId = 0;
  12646. }
  12647. }
  12648. if (this.onResizeObservable.hasObservers) {
  12649. this.onResizeObservable.notifyObservers(this);
  12650. }
  12651. };
  12652. // WebVR functions
  12653. /**
  12654. * Gets a boolean indicating if a webVR device was detected
  12655. * @returns true if a webVR device was detected
  12656. */
  12657. Engine.prototype.isVRDevicePresent = function () {
  12658. return !!this._vrDisplay;
  12659. };
  12660. /**
  12661. * Gets the current webVR device
  12662. * @returns the current webVR device (or null)
  12663. */
  12664. Engine.prototype.getVRDevice = function () {
  12665. return this._vrDisplay;
  12666. };
  12667. /**
  12668. * Initializes a webVR display and starts listening to display change events
  12669. * The onVRDisplayChangedObservable will be notified upon these changes
  12670. * @returns The onVRDisplayChangedObservable
  12671. */
  12672. Engine.prototype.initWebVR = function () {
  12673. this.initWebVRAsync();
  12674. return this.onVRDisplayChangedObservable;
  12675. };
  12676. /**
  12677. * Initializes a webVR display and starts listening to display change events
  12678. * The onVRDisplayChangedObservable will be notified upon these changes
  12679. * @returns A promise containing a VRDisplay and if vr is supported
  12680. */
  12681. Engine.prototype.initWebVRAsync = function () {
  12682. var _this = this;
  12683. var notifyObservers = function () {
  12684. var eventArgs = {
  12685. vrDisplay: _this._vrDisplay,
  12686. vrSupported: _this._vrSupported
  12687. };
  12688. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12689. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12690. };
  12691. if (!this._onVrDisplayConnect) {
  12692. this._onVrDisplayConnect = function (event) {
  12693. _this._vrDisplay = event.display;
  12694. notifyObservers();
  12695. };
  12696. this._onVrDisplayDisconnect = function () {
  12697. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12698. _this._vrDisplay = undefined;
  12699. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12700. notifyObservers();
  12701. };
  12702. this._onVrDisplayPresentChange = function () {
  12703. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12704. };
  12705. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12706. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12707. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12708. }
  12709. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12710. this._webVRInitPromise.then(notifyObservers);
  12711. return this._webVRInitPromise;
  12712. };
  12713. /**
  12714. * Call this function to switch to webVR mode
  12715. * Will do nothing if webVR is not supported or if there is no webVR device
  12716. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12717. */
  12718. Engine.prototype.enableVR = function () {
  12719. var _this = this;
  12720. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12721. var onResolved = function () {
  12722. _this.onVRRequestPresentComplete.notifyObservers(true);
  12723. _this._onVRFullScreenTriggered();
  12724. };
  12725. var onRejected = function () {
  12726. _this.onVRRequestPresentComplete.notifyObservers(false);
  12727. };
  12728. this.onVRRequestPresentStart.notifyObservers(this);
  12729. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12730. }
  12731. };
  12732. /**
  12733. * Call this function to leave webVR mode
  12734. * Will do nothing if webVR is not supported or if there is no webVR device
  12735. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12736. */
  12737. Engine.prototype.disableVR = function () {
  12738. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12739. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12740. }
  12741. };
  12742. Engine.prototype._getVRDisplaysAsync = function () {
  12743. var _this = this;
  12744. return new Promise(function (res, rej) {
  12745. if (navigator.getVRDisplays) {
  12746. navigator.getVRDisplays().then(function (devices) {
  12747. _this._vrSupported = true;
  12748. // note that devices may actually be an empty array. This is fine;
  12749. // we expect this._vrDisplay to be undefined in this case.
  12750. _this._vrDisplay = devices[0];
  12751. res({
  12752. vrDisplay: _this._vrDisplay,
  12753. vrSupported: _this._vrSupported
  12754. });
  12755. });
  12756. }
  12757. else {
  12758. _this._vrDisplay = undefined;
  12759. _this._vrSupported = false;
  12760. res({
  12761. vrDisplay: _this._vrDisplay,
  12762. vrSupported: _this._vrSupported
  12763. });
  12764. }
  12765. });
  12766. };
  12767. /**
  12768. * Binds the frame buffer to the specified texture.
  12769. * @param texture The texture to render to or null for the default canvas
  12770. * @param faceIndex The face of the texture to render to in case of cube texture
  12771. * @param requiredWidth The width of the target to render to
  12772. * @param requiredHeight The height of the target to render to
  12773. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12774. * @param depthStencilTexture The depth stencil texture to use to render
  12775. */
  12776. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12777. if (this._currentRenderTarget) {
  12778. this.unBindFramebuffer(this._currentRenderTarget);
  12779. }
  12780. this._currentRenderTarget = texture;
  12781. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12782. var gl = this._gl;
  12783. if (texture.isCube) {
  12784. if (faceIndex === undefined) {
  12785. faceIndex = 0;
  12786. }
  12787. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12788. if (depthStencilTexture) {
  12789. if (depthStencilTexture._generateStencilBuffer) {
  12790. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12791. }
  12792. else {
  12793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12794. }
  12795. }
  12796. }
  12797. if (this._cachedViewport && !forceFullscreenViewport) {
  12798. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12799. }
  12800. else {
  12801. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12802. }
  12803. this.wipeCaches();
  12804. };
  12805. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12806. if (this._currentFramebuffer !== framebuffer) {
  12807. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12808. this._currentFramebuffer = framebuffer;
  12809. }
  12810. };
  12811. /**
  12812. * Unbind the current render target texture from the webGL context
  12813. * @param texture defines the render target texture to unbind
  12814. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12815. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12816. */
  12817. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12818. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12819. this._currentRenderTarget = null;
  12820. // If MSAA, we need to bitblt back to main texture
  12821. var gl = this._gl;
  12822. if (texture._MSAAFramebuffer) {
  12823. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12824. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12825. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12826. }
  12827. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12828. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12829. gl.generateMipmap(gl.TEXTURE_2D);
  12830. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12831. }
  12832. if (onBeforeUnbind) {
  12833. if (texture._MSAAFramebuffer) {
  12834. // Bind the correct framebuffer
  12835. this.bindUnboundFramebuffer(texture._framebuffer);
  12836. }
  12837. onBeforeUnbind();
  12838. }
  12839. this.bindUnboundFramebuffer(null);
  12840. };
  12841. /**
  12842. * Unbind a list of render target textures from the webGL context
  12843. * This is used only when drawBuffer extension or webGL2 are active
  12844. * @param textures defines the render target textures to unbind
  12845. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12846. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12847. */
  12848. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12849. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12850. this._currentRenderTarget = null;
  12851. // If MSAA, we need to bitblt back to main texture
  12852. var gl = this._gl;
  12853. if (textures[0]._MSAAFramebuffer) {
  12854. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12855. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12856. var attachments = textures[0]._attachments;
  12857. if (!attachments) {
  12858. attachments = new Array(textures.length);
  12859. textures[0]._attachments = attachments;
  12860. }
  12861. for (var i = 0; i < textures.length; i++) {
  12862. var texture = textures[i];
  12863. for (var j = 0; j < attachments.length; j++) {
  12864. attachments[j] = gl.NONE;
  12865. }
  12866. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12867. gl.readBuffer(attachments[i]);
  12868. gl.drawBuffers(attachments);
  12869. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12870. }
  12871. for (var i = 0; i < attachments.length; i++) {
  12872. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12873. }
  12874. gl.drawBuffers(attachments);
  12875. }
  12876. for (var i = 0; i < textures.length; i++) {
  12877. var texture = textures[i];
  12878. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12879. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12880. gl.generateMipmap(gl.TEXTURE_2D);
  12881. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12882. }
  12883. }
  12884. if (onBeforeUnbind) {
  12885. if (textures[0]._MSAAFramebuffer) {
  12886. // Bind the correct framebuffer
  12887. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12888. }
  12889. onBeforeUnbind();
  12890. }
  12891. this.bindUnboundFramebuffer(null);
  12892. };
  12893. /**
  12894. * Force the mipmap generation for the given render target texture
  12895. * @param texture defines the render target texture to use
  12896. */
  12897. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12898. if (texture.generateMipMaps) {
  12899. var gl = this._gl;
  12900. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12901. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12902. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12903. }
  12904. };
  12905. /**
  12906. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12907. */
  12908. Engine.prototype.flushFramebuffer = function () {
  12909. this._gl.flush();
  12910. };
  12911. /**
  12912. * Unbind the current render target and bind the default framebuffer
  12913. */
  12914. Engine.prototype.restoreDefaultFramebuffer = function () {
  12915. if (this._currentRenderTarget) {
  12916. this.unBindFramebuffer(this._currentRenderTarget);
  12917. }
  12918. else {
  12919. this.bindUnboundFramebuffer(null);
  12920. }
  12921. if (this._cachedViewport) {
  12922. this.setViewport(this._cachedViewport);
  12923. }
  12924. this.wipeCaches();
  12925. };
  12926. // UBOs
  12927. /**
  12928. * Create an uniform buffer
  12929. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12930. * @param elements defines the content of the uniform buffer
  12931. * @returns the webGL uniform buffer
  12932. */
  12933. Engine.prototype.createUniformBuffer = function (elements) {
  12934. var ubo = this._gl.createBuffer();
  12935. if (!ubo) {
  12936. throw new Error("Unable to create uniform buffer");
  12937. }
  12938. this.bindUniformBuffer(ubo);
  12939. if (elements instanceof Float32Array) {
  12940. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12941. }
  12942. else {
  12943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12944. }
  12945. this.bindUniformBuffer(null);
  12946. ubo.references = 1;
  12947. return ubo;
  12948. };
  12949. /**
  12950. * Create a dynamic uniform buffer
  12951. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12952. * @param elements defines the content of the uniform buffer
  12953. * @returns the webGL uniform buffer
  12954. */
  12955. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12956. var ubo = this._gl.createBuffer();
  12957. if (!ubo) {
  12958. throw new Error("Unable to create dynamic uniform buffer");
  12959. }
  12960. this.bindUniformBuffer(ubo);
  12961. if (elements instanceof Float32Array) {
  12962. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12963. }
  12964. else {
  12965. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12966. }
  12967. this.bindUniformBuffer(null);
  12968. ubo.references = 1;
  12969. return ubo;
  12970. };
  12971. /**
  12972. * Update an existing uniform buffer
  12973. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12974. * @param uniformBuffer defines the target uniform buffer
  12975. * @param elements defines the content to update
  12976. * @param offset defines the offset in the uniform buffer where update should start
  12977. * @param count defines the size of the data to update
  12978. */
  12979. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12980. this.bindUniformBuffer(uniformBuffer);
  12981. if (offset === undefined) {
  12982. offset = 0;
  12983. }
  12984. if (count === undefined) {
  12985. if (elements instanceof Float32Array) {
  12986. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12987. }
  12988. else {
  12989. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12990. }
  12991. }
  12992. else {
  12993. if (elements instanceof Float32Array) {
  12994. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12995. }
  12996. else {
  12997. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12998. }
  12999. }
  13000. this.bindUniformBuffer(null);
  13001. };
  13002. // VBOs
  13003. Engine.prototype._resetVertexBufferBinding = function () {
  13004. this.bindArrayBuffer(null);
  13005. this._cachedVertexBuffers = null;
  13006. };
  13007. /**
  13008. * Creates a vertex buffer
  13009. * @param data the data for the vertex buffer
  13010. * @returns the new WebGL static buffer
  13011. */
  13012. Engine.prototype.createVertexBuffer = function (data) {
  13013. var vbo = this._gl.createBuffer();
  13014. if (!vbo) {
  13015. throw new Error("Unable to create vertex buffer");
  13016. }
  13017. this.bindArrayBuffer(vbo);
  13018. if (data instanceof Array) {
  13019. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13020. }
  13021. else {
  13022. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13023. }
  13024. this._resetVertexBufferBinding();
  13025. vbo.references = 1;
  13026. return vbo;
  13027. };
  13028. /**
  13029. * Creates a dynamic vertex buffer
  13030. * @param data the data for the dynamic vertex buffer
  13031. * @returns the new WebGL dynamic buffer
  13032. */
  13033. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13034. var vbo = this._gl.createBuffer();
  13035. if (!vbo) {
  13036. throw new Error("Unable to create dynamic vertex buffer");
  13037. }
  13038. this.bindArrayBuffer(vbo);
  13039. if (data instanceof Array) {
  13040. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13041. }
  13042. else {
  13043. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13044. }
  13045. this._resetVertexBufferBinding();
  13046. vbo.references = 1;
  13047. return vbo;
  13048. };
  13049. /**
  13050. * Update a dynamic index buffer
  13051. * @param indexBuffer defines the target index buffer
  13052. * @param indices defines the data to update
  13053. * @param offset defines the offset in the target index buffer where update should start
  13054. */
  13055. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13056. if (offset === void 0) { offset = 0; }
  13057. // Force cache update
  13058. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13059. this.bindIndexBuffer(indexBuffer);
  13060. var arrayBuffer;
  13061. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13062. arrayBuffer = indices;
  13063. }
  13064. else {
  13065. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13066. }
  13067. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13068. this._resetIndexBufferBinding();
  13069. };
  13070. /**
  13071. * Updates a dynamic vertex buffer.
  13072. * @param vertexBuffer the vertex buffer to update
  13073. * @param data the data used to update the vertex buffer
  13074. * @param byteOffset the byte offset of the data
  13075. * @param byteLength the byte length of the data
  13076. */
  13077. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13078. this.bindArrayBuffer(vertexBuffer);
  13079. if (byteOffset === undefined) {
  13080. byteOffset = 0;
  13081. }
  13082. if (byteLength === undefined) {
  13083. if (data instanceof Array) {
  13084. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13085. }
  13086. else {
  13087. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13088. }
  13089. }
  13090. else {
  13091. if (data instanceof Array) {
  13092. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13093. }
  13094. else {
  13095. if (data instanceof ArrayBuffer) {
  13096. data = new Uint8Array(data, byteOffset, byteLength);
  13097. }
  13098. else {
  13099. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13100. }
  13101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13102. }
  13103. }
  13104. this._resetVertexBufferBinding();
  13105. };
  13106. Engine.prototype._resetIndexBufferBinding = function () {
  13107. this.bindIndexBuffer(null);
  13108. this._cachedIndexBuffer = null;
  13109. };
  13110. /**
  13111. * Creates a new index buffer
  13112. * @param indices defines the content of the index buffer
  13113. * @param updatable defines if the index buffer must be updatable
  13114. * @returns a new webGL buffer
  13115. */
  13116. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13117. var vbo = this._gl.createBuffer();
  13118. if (!vbo) {
  13119. throw new Error("Unable to create index buffer");
  13120. }
  13121. this.bindIndexBuffer(vbo);
  13122. // Check for 32 bits indices
  13123. var arrayBuffer;
  13124. var need32Bits = false;
  13125. if (indices instanceof Uint16Array) {
  13126. arrayBuffer = indices;
  13127. }
  13128. else {
  13129. //check 32 bit support
  13130. if (this._caps.uintIndices) {
  13131. if (indices instanceof Uint32Array) {
  13132. arrayBuffer = indices;
  13133. need32Bits = true;
  13134. }
  13135. else {
  13136. //number[] or Int32Array, check if 32 bit is necessary
  13137. for (var index = 0; index < indices.length; index++) {
  13138. if (indices[index] > 65535) {
  13139. need32Bits = true;
  13140. break;
  13141. }
  13142. }
  13143. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13144. }
  13145. }
  13146. else {
  13147. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13148. arrayBuffer = new Uint16Array(indices);
  13149. }
  13150. }
  13151. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13152. this._resetIndexBufferBinding();
  13153. vbo.references = 1;
  13154. vbo.is32Bits = need32Bits;
  13155. return vbo;
  13156. };
  13157. /**
  13158. * Bind a webGL buffer to the webGL context
  13159. * @param buffer defines the buffer to bind
  13160. */
  13161. Engine.prototype.bindArrayBuffer = function (buffer) {
  13162. if (!this._vaoRecordInProgress) {
  13163. this._unbindVertexArrayObject();
  13164. }
  13165. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13166. };
  13167. /**
  13168. * Bind an uniform buffer to the current webGL context
  13169. * @param buffer defines the buffer to bind
  13170. */
  13171. Engine.prototype.bindUniformBuffer = function (buffer) {
  13172. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13173. };
  13174. /**
  13175. * Bind a buffer to the current webGL context at a given location
  13176. * @param buffer defines the buffer to bind
  13177. * @param location defines the index where to bind the buffer
  13178. */
  13179. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13180. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13181. };
  13182. /**
  13183. * Bind a specific block at a given index in a specific shader program
  13184. * @param shaderProgram defines the shader program
  13185. * @param blockName defines the block name
  13186. * @param index defines the index where to bind the block
  13187. */
  13188. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13189. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13190. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13191. };
  13192. ;
  13193. Engine.prototype.bindIndexBuffer = function (buffer) {
  13194. if (!this._vaoRecordInProgress) {
  13195. this._unbindVertexArrayObject();
  13196. }
  13197. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13198. };
  13199. Engine.prototype.bindBuffer = function (buffer, target) {
  13200. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13201. this._gl.bindBuffer(target, buffer);
  13202. this._currentBoundBuffer[target] = buffer;
  13203. }
  13204. };
  13205. /**
  13206. * update the bound buffer with the given data
  13207. * @param data defines the data to update
  13208. */
  13209. Engine.prototype.updateArrayBuffer = function (data) {
  13210. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13211. };
  13212. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13213. var pointer = this._currentBufferPointers[indx];
  13214. var changed = false;
  13215. if (!pointer.active) {
  13216. changed = true;
  13217. pointer.active = true;
  13218. pointer.index = indx;
  13219. pointer.size = size;
  13220. pointer.type = type;
  13221. pointer.normalized = normalized;
  13222. pointer.stride = stride;
  13223. pointer.offset = offset;
  13224. pointer.buffer = buffer;
  13225. }
  13226. else {
  13227. if (pointer.buffer !== buffer) {
  13228. pointer.buffer = buffer;
  13229. changed = true;
  13230. }
  13231. if (pointer.size !== size) {
  13232. pointer.size = size;
  13233. changed = true;
  13234. }
  13235. if (pointer.type !== type) {
  13236. pointer.type = type;
  13237. changed = true;
  13238. }
  13239. if (pointer.normalized !== normalized) {
  13240. pointer.normalized = normalized;
  13241. changed = true;
  13242. }
  13243. if (pointer.stride !== stride) {
  13244. pointer.stride = stride;
  13245. changed = true;
  13246. }
  13247. if (pointer.offset !== offset) {
  13248. pointer.offset = offset;
  13249. changed = true;
  13250. }
  13251. }
  13252. if (changed || this._vaoRecordInProgress) {
  13253. this.bindArrayBuffer(buffer);
  13254. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13255. }
  13256. };
  13257. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13258. if (indexBuffer == null) {
  13259. return;
  13260. }
  13261. if (this._cachedIndexBuffer !== indexBuffer) {
  13262. this._cachedIndexBuffer = indexBuffer;
  13263. this.bindIndexBuffer(indexBuffer);
  13264. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13265. }
  13266. };
  13267. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13268. var attributes = effect.getAttributesNames();
  13269. if (!this._vaoRecordInProgress) {
  13270. this._unbindVertexArrayObject();
  13271. }
  13272. this.unbindAllAttributes();
  13273. for (var index = 0; index < attributes.length; index++) {
  13274. var order = effect.getAttributeLocation(index);
  13275. if (order >= 0) {
  13276. var vertexBuffer = vertexBuffers[attributes[index]];
  13277. if (!vertexBuffer) {
  13278. continue;
  13279. }
  13280. this._gl.enableVertexAttribArray(order);
  13281. if (!this._vaoRecordInProgress) {
  13282. this._vertexAttribArraysEnabled[order] = true;
  13283. }
  13284. var buffer = vertexBuffer.getBuffer();
  13285. if (buffer) {
  13286. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13287. if (vertexBuffer.getIsInstanced()) {
  13288. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13289. if (!this._vaoRecordInProgress) {
  13290. this._currentInstanceLocations.push(order);
  13291. this._currentInstanceBuffers.push(buffer);
  13292. }
  13293. }
  13294. }
  13295. }
  13296. }
  13297. };
  13298. /**
  13299. * Records a vertex array object
  13300. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13301. * @param vertexBuffers defines the list of vertex buffers to store
  13302. * @param indexBuffer defines the index buffer to store
  13303. * @param effect defines the effect to store
  13304. * @returns the new vertex array object
  13305. */
  13306. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13307. var vao = this._gl.createVertexArray();
  13308. this._vaoRecordInProgress = true;
  13309. this._gl.bindVertexArray(vao);
  13310. this._mustWipeVertexAttributes = true;
  13311. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13312. this.bindIndexBuffer(indexBuffer);
  13313. this._vaoRecordInProgress = false;
  13314. this._gl.bindVertexArray(null);
  13315. return vao;
  13316. };
  13317. /**
  13318. * Bind a specific vertex array object
  13319. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13320. * @param vertexArrayObject defines the vertex array object to bind
  13321. * @param indexBuffer defines the index buffer to bind
  13322. */
  13323. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13324. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13325. this._cachedVertexArrayObject = vertexArrayObject;
  13326. this._gl.bindVertexArray(vertexArrayObject);
  13327. this._cachedVertexBuffers = null;
  13328. this._cachedIndexBuffer = null;
  13329. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13330. this._mustWipeVertexAttributes = true;
  13331. }
  13332. };
  13333. /**
  13334. * Bind webGl buffers directly to the webGL context
  13335. * @param vertexBuffer defines the vertex buffer to bind
  13336. * @param indexBuffer defines the index buffer to bind
  13337. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13338. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13339. * @param effect defines the effect associated with the vertex buffer
  13340. */
  13341. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13342. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13343. this._cachedVertexBuffers = vertexBuffer;
  13344. this._cachedEffectForVertexBuffers = effect;
  13345. var attributesCount = effect.getAttributesCount();
  13346. this._unbindVertexArrayObject();
  13347. this.unbindAllAttributes();
  13348. var offset = 0;
  13349. for (var index = 0; index < attributesCount; index++) {
  13350. if (index < vertexDeclaration.length) {
  13351. var order = effect.getAttributeLocation(index);
  13352. if (order >= 0) {
  13353. this._gl.enableVertexAttribArray(order);
  13354. this._vertexAttribArraysEnabled[order] = true;
  13355. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13356. }
  13357. offset += vertexDeclaration[index] * 4;
  13358. }
  13359. }
  13360. }
  13361. this._bindIndexBufferWithCache(indexBuffer);
  13362. };
  13363. Engine.prototype._unbindVertexArrayObject = function () {
  13364. if (!this._cachedVertexArrayObject) {
  13365. return;
  13366. }
  13367. this._cachedVertexArrayObject = null;
  13368. this._gl.bindVertexArray(null);
  13369. };
  13370. /**
  13371. * Bind a list of vertex buffers to the webGL context
  13372. * @param vertexBuffers defines the list of vertex buffers to bind
  13373. * @param indexBuffer defines the index buffer to bind
  13374. * @param effect defines the effect associated with the vertex buffers
  13375. */
  13376. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13377. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13378. this._cachedVertexBuffers = vertexBuffers;
  13379. this._cachedEffectForVertexBuffers = effect;
  13380. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13381. }
  13382. this._bindIndexBufferWithCache(indexBuffer);
  13383. };
  13384. /**
  13385. * Unbind all instance attributes
  13386. */
  13387. Engine.prototype.unbindInstanceAttributes = function () {
  13388. var boundBuffer;
  13389. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13390. var instancesBuffer = this._currentInstanceBuffers[i];
  13391. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13392. boundBuffer = instancesBuffer;
  13393. this.bindArrayBuffer(instancesBuffer);
  13394. }
  13395. var offsetLocation = this._currentInstanceLocations[i];
  13396. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13397. }
  13398. this._currentInstanceBuffers.length = 0;
  13399. this._currentInstanceLocations.length = 0;
  13400. };
  13401. /**
  13402. * Release and free the memory of a vertex array object
  13403. * @param vao defines the vertex array object to delete
  13404. */
  13405. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13406. this._gl.deleteVertexArray(vao);
  13407. };
  13408. /** @ignore */
  13409. Engine.prototype._releaseBuffer = function (buffer) {
  13410. buffer.references--;
  13411. if (buffer.references === 0) {
  13412. this._gl.deleteBuffer(buffer);
  13413. return true;
  13414. }
  13415. return false;
  13416. };
  13417. /**
  13418. * Creates a webGL buffer to use with instanciation
  13419. * @param capacity defines the size of the buffer
  13420. * @returns the webGL buffer
  13421. */
  13422. Engine.prototype.createInstancesBuffer = function (capacity) {
  13423. var buffer = this._gl.createBuffer();
  13424. if (!buffer) {
  13425. throw new Error("Unable to create instance buffer");
  13426. }
  13427. buffer.capacity = capacity;
  13428. this.bindArrayBuffer(buffer);
  13429. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13430. return buffer;
  13431. };
  13432. /**
  13433. * Delete a webGL buffer used with instanciation
  13434. * @param buffer defines the webGL buffer to delete
  13435. */
  13436. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13437. this._gl.deleteBuffer(buffer);
  13438. };
  13439. /**
  13440. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13441. * @param instancesBuffer defines the webGL buffer to update and bind
  13442. * @param data defines the data to store in the buffer
  13443. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13444. */
  13445. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13446. this.bindArrayBuffer(instancesBuffer);
  13447. if (data) {
  13448. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13449. }
  13450. if (offsetLocations[0].index !== undefined) {
  13451. var stride = 0;
  13452. for (var i = 0; i < offsetLocations.length; i++) {
  13453. var ai = offsetLocations[i];
  13454. stride += ai.attributeSize * 4;
  13455. }
  13456. for (var i = 0; i < offsetLocations.length; i++) {
  13457. var ai = offsetLocations[i];
  13458. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13459. this._gl.enableVertexAttribArray(ai.index);
  13460. this._vertexAttribArraysEnabled[ai.index] = true;
  13461. }
  13462. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13463. this._gl.vertexAttribDivisor(ai.index, 1);
  13464. this._currentInstanceLocations.push(ai.index);
  13465. this._currentInstanceBuffers.push(instancesBuffer);
  13466. }
  13467. }
  13468. else {
  13469. for (var index = 0; index < 4; index++) {
  13470. var offsetLocation = offsetLocations[index];
  13471. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13472. this._gl.enableVertexAttribArray(offsetLocation);
  13473. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13474. }
  13475. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13476. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13477. this._currentInstanceLocations.push(offsetLocation);
  13478. this._currentInstanceBuffers.push(instancesBuffer);
  13479. }
  13480. }
  13481. };
  13482. /**
  13483. * Apply all cached states (depth, culling, stencil and alpha)
  13484. */
  13485. Engine.prototype.applyStates = function () {
  13486. this._depthCullingState.apply(this._gl);
  13487. this._stencilState.apply(this._gl);
  13488. this._alphaState.apply(this._gl);
  13489. };
  13490. /**
  13491. * Send a draw order
  13492. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13493. * @param indexStart defines the starting index
  13494. * @param indexCount defines the number of index to draw
  13495. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13496. */
  13497. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13498. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13499. };
  13500. /**
  13501. * Draw a list of points
  13502. * @param verticesStart defines the index of first vertex to draw
  13503. * @param verticesCount defines the count of vertices to draw
  13504. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13505. */
  13506. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13507. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13508. };
  13509. /**
  13510. * Draw a list of unindexed primitives
  13511. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13512. * @param verticesStart defines the index of first vertex to draw
  13513. * @param verticesCount defines the count of vertices to draw
  13514. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13515. */
  13516. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13517. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13518. };
  13519. /**
  13520. * Draw a list of indexed primitives
  13521. * @param fillMode defines the primitive to use
  13522. * @param indexStart defines the starting index
  13523. * @param indexCount defines the number of index to draw
  13524. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13525. */
  13526. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13527. // Apply states
  13528. this.applyStates();
  13529. this._drawCalls.addCount(1, false);
  13530. // Render
  13531. var drawMode = this._drawMode(fillMode);
  13532. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13533. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13534. if (instancesCount) {
  13535. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13536. }
  13537. else {
  13538. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13539. }
  13540. };
  13541. /**
  13542. * Draw a list of unindexed primitives
  13543. * @param fillMode defines the primitive to use
  13544. * @param verticesStart defines the index of first vertex to draw
  13545. * @param verticesCount defines the count of vertices to draw
  13546. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13547. */
  13548. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13549. // Apply states
  13550. this.applyStates();
  13551. this._drawCalls.addCount(1, false);
  13552. var drawMode = this._drawMode(fillMode);
  13553. if (instancesCount) {
  13554. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13555. }
  13556. else {
  13557. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13558. }
  13559. };
  13560. Engine.prototype._drawMode = function (fillMode) {
  13561. switch (fillMode) {
  13562. // Triangle views
  13563. case BABYLON.Material.TriangleFillMode:
  13564. return this._gl.TRIANGLES;
  13565. case BABYLON.Material.PointFillMode:
  13566. return this._gl.POINTS;
  13567. case BABYLON.Material.WireFrameFillMode:
  13568. return this._gl.LINES;
  13569. // Draw modes
  13570. case BABYLON.Material.PointListDrawMode:
  13571. return this._gl.POINTS;
  13572. case BABYLON.Material.LineListDrawMode:
  13573. return this._gl.LINES;
  13574. case BABYLON.Material.LineLoopDrawMode:
  13575. return this._gl.LINE_LOOP;
  13576. case BABYLON.Material.LineStripDrawMode:
  13577. return this._gl.LINE_STRIP;
  13578. case BABYLON.Material.TriangleStripDrawMode:
  13579. return this._gl.TRIANGLE_STRIP;
  13580. case BABYLON.Material.TriangleFanDrawMode:
  13581. return this._gl.TRIANGLE_FAN;
  13582. default:
  13583. return this._gl.TRIANGLES;
  13584. }
  13585. };
  13586. // Shaders
  13587. /** @ignore */
  13588. Engine.prototype._releaseEffect = function (effect) {
  13589. if (this._compiledEffects[effect._key]) {
  13590. delete this._compiledEffects[effect._key];
  13591. this._deleteProgram(effect.getProgram());
  13592. }
  13593. };
  13594. /** @ignore */
  13595. Engine.prototype._deleteProgram = function (program) {
  13596. if (program) {
  13597. program.__SPECTOR_rebuildProgram = null;
  13598. if (program.transformFeedback) {
  13599. this.deleteTransformFeedback(program.transformFeedback);
  13600. program.transformFeedback = null;
  13601. }
  13602. this._gl.deleteProgram(program);
  13603. }
  13604. };
  13605. /**
  13606. * Create a new effect (used to store vertex/fragment shaders)
  13607. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13608. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13609. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13610. * @param samplers defines an array of string used to represent textures
  13611. * @param defines defines the string containing the defines to use to compile the shaders
  13612. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13613. * @param onCompiled defines a function to call when the effect creation is successful
  13614. * @param onError defines a function to call when the effect creation has failed
  13615. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13616. * @returns the new Effect
  13617. */
  13618. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13619. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13620. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13621. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13622. if (this._compiledEffects[name]) {
  13623. var compiledEffect = this._compiledEffects[name];
  13624. if (onCompiled && compiledEffect.isReady()) {
  13625. onCompiled(compiledEffect);
  13626. }
  13627. return compiledEffect;
  13628. }
  13629. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13630. effect._key = name;
  13631. this._compiledEffects[name] = effect;
  13632. return effect;
  13633. };
  13634. /**
  13635. * Create an effect to use with particle systems
  13636. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13637. * @param uniformsNames defines a list of attribute names
  13638. * @param samplers defines an array of string used to represent textures
  13639. * @param defines defines the string containing the defines to use to compile the shaders
  13640. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13641. * @param onCompiled defines a function to call when the effect creation is successful
  13642. * @param onError defines a function to call when the effect creation has failed
  13643. * @returns the new Effect
  13644. */
  13645. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13646. if (uniformsNames === void 0) { uniformsNames = []; }
  13647. if (samplers === void 0) { samplers = []; }
  13648. if (defines === void 0) { defines = ""; }
  13649. return this.createEffect({
  13650. vertex: "particles",
  13651. fragmentElement: fragmentName
  13652. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13653. };
  13654. /**
  13655. * Directly creates a webGL program
  13656. * @param vertexCode defines the vertex shader code to use
  13657. * @param fragmentCode defines the fragment shader code to use
  13658. * @param context defines the webGL context to use (if not set, the current one will be used)
  13659. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13660. * @returns the new webGL program
  13661. */
  13662. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13663. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13664. context = context || this._gl;
  13665. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13666. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13667. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13668. };
  13669. /**
  13670. * Creates a webGL program
  13671. * @param vertexCode defines the vertex shader code to use
  13672. * @param fragmentCode defines the fragment shader code to use
  13673. * @param defines defines the string containing the defines to use to compile the shaders
  13674. * @param context defines the webGL context to use (if not set, the current one will be used)
  13675. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13676. * @returns the new webGL program
  13677. */
  13678. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13679. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13680. context = context || this._gl;
  13681. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13682. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13683. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13684. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13685. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13686. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13687. return program;
  13688. };
  13689. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13690. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13691. var shaderProgram = context.createProgram();
  13692. if (!shaderProgram) {
  13693. throw new Error("Unable to create program");
  13694. }
  13695. context.attachShader(shaderProgram, vertexShader);
  13696. context.attachShader(shaderProgram, fragmentShader);
  13697. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13698. var transformFeedback = this.createTransformFeedback();
  13699. this.bindTransformFeedback(transformFeedback);
  13700. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13701. shaderProgram.transformFeedback = transformFeedback;
  13702. }
  13703. context.linkProgram(shaderProgram);
  13704. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13705. this.bindTransformFeedback(null);
  13706. }
  13707. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13708. if (!linked) {
  13709. context.validateProgram(shaderProgram);
  13710. var error = context.getProgramInfoLog(shaderProgram);
  13711. if (error) {
  13712. throw new Error(error);
  13713. }
  13714. }
  13715. context.deleteShader(vertexShader);
  13716. context.deleteShader(fragmentShader);
  13717. return shaderProgram;
  13718. };
  13719. /**
  13720. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13721. * @param shaderProgram defines the webGL program to use
  13722. * @param uniformsNames defines the list of uniform names
  13723. * @returns an array of webGL uniform locations
  13724. */
  13725. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13726. var results = new Array();
  13727. for (var index = 0; index < uniformsNames.length; index++) {
  13728. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13729. }
  13730. return results;
  13731. };
  13732. /**
  13733. * Gets the lsit of active attributes for a given webGL program
  13734. * @param shaderProgram defines the webGL program to use
  13735. * @param attributesNames defines the list of attribute names to get
  13736. * @returns an array of indices indicating the offset of each attribute
  13737. */
  13738. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13739. var results = [];
  13740. for (var index = 0; index < attributesNames.length; index++) {
  13741. try {
  13742. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13743. }
  13744. catch (e) {
  13745. results.push(-1);
  13746. }
  13747. }
  13748. return results;
  13749. };
  13750. /**
  13751. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13752. * @param effect defines the effect to activate
  13753. */
  13754. Engine.prototype.enableEffect = function (effect) {
  13755. if (!effect) {
  13756. return;
  13757. }
  13758. // Use program
  13759. this.bindSamplers(effect);
  13760. this._currentEffect = effect;
  13761. if (effect.onBind) {
  13762. effect.onBind(effect);
  13763. }
  13764. effect.onBindObservable.notifyObservers(effect);
  13765. };
  13766. /**
  13767. * Set the value of an uniform to an array of int32
  13768. * @param uniform defines the webGL uniform location where to store the value
  13769. * @param array defines the array of int32 to store
  13770. */
  13771. Engine.prototype.setIntArray = function (uniform, array) {
  13772. if (!uniform)
  13773. return;
  13774. this._gl.uniform1iv(uniform, array);
  13775. };
  13776. /**
  13777. * Set the value of an uniform to an array of int32 (stored as vec2)
  13778. * @param uniform defines the webGL uniform location where to store the value
  13779. * @param array defines the array of int32 to store
  13780. */
  13781. Engine.prototype.setIntArray2 = function (uniform, array) {
  13782. if (!uniform || array.length % 2 !== 0)
  13783. return;
  13784. this._gl.uniform2iv(uniform, array);
  13785. };
  13786. /**
  13787. * Set the value of an uniform to an array of int32 (stored as vec3)
  13788. * @param uniform defines the webGL uniform location where to store the value
  13789. * @param array defines the array of int32 to store
  13790. */
  13791. Engine.prototype.setIntArray3 = function (uniform, array) {
  13792. if (!uniform || array.length % 3 !== 0)
  13793. return;
  13794. this._gl.uniform3iv(uniform, array);
  13795. };
  13796. /**
  13797. * Set the value of an uniform to an array of int32 (stored as vec4)
  13798. * @param uniform defines the webGL uniform location where to store the value
  13799. * @param array defines the array of int32 to store
  13800. */
  13801. Engine.prototype.setIntArray4 = function (uniform, array) {
  13802. if (!uniform || array.length % 4 !== 0)
  13803. return;
  13804. this._gl.uniform4iv(uniform, array);
  13805. };
  13806. /**
  13807. * Set the value of an uniform to an array of float32
  13808. * @param uniform defines the webGL uniform location where to store the value
  13809. * @param array defines the array of float32 to store
  13810. */
  13811. Engine.prototype.setFloatArray = function (uniform, array) {
  13812. if (!uniform)
  13813. return;
  13814. this._gl.uniform1fv(uniform, array);
  13815. };
  13816. /**
  13817. * Set the value of an uniform to an array of float32 (stored as vec2)
  13818. * @param uniform defines the webGL uniform location where to store the value
  13819. * @param array defines the array of float32 to store
  13820. */
  13821. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13822. if (!uniform || array.length % 2 !== 0)
  13823. return;
  13824. this._gl.uniform2fv(uniform, array);
  13825. };
  13826. /**
  13827. * Set the value of an uniform to an array of float32 (stored as vec3)
  13828. * @param uniform defines the webGL uniform location where to store the value
  13829. * @param array defines the array of float32 to store
  13830. */
  13831. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13832. if (!uniform || array.length % 3 !== 0)
  13833. return;
  13834. this._gl.uniform3fv(uniform, array);
  13835. };
  13836. /**
  13837. * Set the value of an uniform to an array of float32 (stored as vec4)
  13838. * @param uniform defines the webGL uniform location where to store the value
  13839. * @param array defines the array of float32 to store
  13840. */
  13841. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13842. if (!uniform || array.length % 4 !== 0)
  13843. return;
  13844. this._gl.uniform4fv(uniform, array);
  13845. };
  13846. /**
  13847. * Set the value of an uniform to an array of number
  13848. * @param uniform defines the webGL uniform location where to store the value
  13849. * @param array defines the array of number to store
  13850. */
  13851. Engine.prototype.setArray = function (uniform, array) {
  13852. if (!uniform)
  13853. return;
  13854. this._gl.uniform1fv(uniform, array);
  13855. };
  13856. /**
  13857. * Set the value of an uniform to an array of number (stored as vec2)
  13858. * @param uniform defines the webGL uniform location where to store the value
  13859. * @param array defines the array of number to store
  13860. */
  13861. Engine.prototype.setArray2 = function (uniform, array) {
  13862. if (!uniform || array.length % 2 !== 0)
  13863. return;
  13864. this._gl.uniform2fv(uniform, array);
  13865. };
  13866. /**
  13867. * Set the value of an uniform to an array of number (stored as vec3)
  13868. * @param uniform defines the webGL uniform location where to store the value
  13869. * @param array defines the array of number to store
  13870. */
  13871. Engine.prototype.setArray3 = function (uniform, array) {
  13872. if (!uniform || array.length % 3 !== 0)
  13873. return;
  13874. this._gl.uniform3fv(uniform, array);
  13875. };
  13876. /**
  13877. * Set the value of an uniform to an array of number (stored as vec4)
  13878. * @param uniform defines the webGL uniform location where to store the value
  13879. * @param array defines the array of number to store
  13880. */
  13881. Engine.prototype.setArray4 = function (uniform, array) {
  13882. if (!uniform || array.length % 4 !== 0)
  13883. return;
  13884. this._gl.uniform4fv(uniform, array);
  13885. };
  13886. /**
  13887. * Set the value of an uniform to an array of float32 (stored as matrices)
  13888. * @param uniform defines the webGL uniform location where to store the value
  13889. * @param matrices defines the array of float32 to store
  13890. */
  13891. Engine.prototype.setMatrices = function (uniform, matrices) {
  13892. if (!uniform)
  13893. return;
  13894. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13895. };
  13896. /**
  13897. * Set the value of an uniform to a matrix
  13898. * @param uniform defines the webGL uniform location where to store the value
  13899. * @param matrix defines the matrix to store
  13900. */
  13901. Engine.prototype.setMatrix = function (uniform, matrix) {
  13902. if (!uniform)
  13903. return;
  13904. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13905. };
  13906. /**
  13907. * Set the value of an uniform to a matrix (3x3)
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13910. */
  13911. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13912. if (!uniform)
  13913. return;
  13914. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13915. };
  13916. /**
  13917. * Set the value of an uniform to a matrix (2x2)
  13918. * @param uniform defines the webGL uniform location where to store the value
  13919. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13920. */
  13921. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13922. if (!uniform)
  13923. return;
  13924. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13925. };
  13926. /**
  13927. * Set the value of an uniform to a number (int)
  13928. * @param uniform defines the webGL uniform location where to store the value
  13929. * @param value defines the int number to store
  13930. */
  13931. Engine.prototype.setInt = function (uniform, value) {
  13932. if (!uniform)
  13933. return;
  13934. this._gl.uniform1i(uniform, value);
  13935. };
  13936. /**
  13937. * Set the value of an uniform to a number (float)
  13938. * @param uniform defines the webGL uniform location where to store the value
  13939. * @param value defines the float number to store
  13940. */
  13941. Engine.prototype.setFloat = function (uniform, value) {
  13942. if (!uniform)
  13943. return;
  13944. this._gl.uniform1f(uniform, value);
  13945. };
  13946. /**
  13947. * Set the value of an uniform to a vec2
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param x defines the 1st component of the value
  13950. * @param y defines the 2nd component of the value
  13951. */
  13952. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13953. if (!uniform)
  13954. return;
  13955. this._gl.uniform2f(uniform, x, y);
  13956. };
  13957. /**
  13958. * Set the value of an uniform to a vec3
  13959. * @param uniform defines the webGL uniform location where to store the value
  13960. * @param x defines the 1st component of the value
  13961. * @param y defines the 2nd component of the value
  13962. * @param z defines the 3rd component of the value
  13963. */
  13964. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13965. if (!uniform)
  13966. return;
  13967. this._gl.uniform3f(uniform, x, y, z);
  13968. };
  13969. /**
  13970. * Set the value of an uniform to a boolean
  13971. * @param uniform defines the webGL uniform location where to store the value
  13972. * @param bool defines the boolean to store
  13973. */
  13974. Engine.prototype.setBool = function (uniform, bool) {
  13975. if (!uniform)
  13976. return;
  13977. this._gl.uniform1i(uniform, bool);
  13978. };
  13979. /**
  13980. * Set the value of an uniform to a vec4
  13981. * @param uniform defines the webGL uniform location where to store the value
  13982. * @param x defines the 1st component of the value
  13983. * @param y defines the 2nd component of the value
  13984. * @param z defines the 3rd component of the value
  13985. * @param w defines the 4th component of the value
  13986. */
  13987. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13988. if (!uniform)
  13989. return;
  13990. this._gl.uniform4f(uniform, x, y, z, w);
  13991. };
  13992. /**
  13993. * Set the value of an uniform to a Color3
  13994. * @param uniform defines the webGL uniform location where to store the value
  13995. * @param color3 defines the color to store
  13996. */
  13997. Engine.prototype.setColor3 = function (uniform, color3) {
  13998. if (!uniform)
  13999. return;
  14000. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14001. };
  14002. /**
  14003. * Set the value of an uniform to a Color3 and an alpha value
  14004. * @param uniform defines the webGL uniform location where to store the value
  14005. * @param color3 defines the color to store
  14006. * @param alpha defines the alpha component to store
  14007. */
  14008. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14009. if (!uniform)
  14010. return;
  14011. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14012. };
  14013. /**
  14014. * Sets a Color4 on a uniform variable
  14015. * @param uniform defines the uniform location
  14016. * @param color4 defines the value to be set
  14017. */
  14018. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14019. if (!uniform)
  14020. return;
  14021. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14022. };
  14023. // States
  14024. /**
  14025. * Set various states to the webGL context
  14026. * @param culling defines backface culling state
  14027. * @param zOffset defines the value to apply to zOffset (0 by default)
  14028. * @param force defines if states must be applied even if cache is up to date
  14029. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14030. */
  14031. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14032. if (zOffset === void 0) { zOffset = 0; }
  14033. if (reverseSide === void 0) { reverseSide = false; }
  14034. // Culling
  14035. if (this._depthCullingState.cull !== culling || force) {
  14036. this._depthCullingState.cull = culling;
  14037. }
  14038. // Cull face
  14039. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14040. if (this._depthCullingState.cullFace !== cullFace || force) {
  14041. this._depthCullingState.cullFace = cullFace;
  14042. }
  14043. // Z offset
  14044. this.setZOffset(zOffset);
  14045. // Front face
  14046. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14047. if (this._depthCullingState.frontFace !== frontFace || force) {
  14048. this._depthCullingState.frontFace = frontFace;
  14049. }
  14050. };
  14051. /**
  14052. * Set the z offset to apply to current rendering
  14053. * @param value defines the offset to apply
  14054. */
  14055. Engine.prototype.setZOffset = function (value) {
  14056. this._depthCullingState.zOffset = value;
  14057. };
  14058. /**
  14059. * Gets the current value of the zOffset
  14060. * @returns the current zOffset state
  14061. */
  14062. Engine.prototype.getZOffset = function () {
  14063. return this._depthCullingState.zOffset;
  14064. };
  14065. /**
  14066. * Enable or disable depth buffering
  14067. * @param enable defines the state to set
  14068. */
  14069. Engine.prototype.setDepthBuffer = function (enable) {
  14070. this._depthCullingState.depthTest = enable;
  14071. };
  14072. /**
  14073. * Gets a boolean indicating if depth writing is enabled
  14074. * @returns the current depth writing state
  14075. */
  14076. Engine.prototype.getDepthWrite = function () {
  14077. return this._depthCullingState.depthMask;
  14078. };
  14079. /**
  14080. * Enable or disable depth writing
  14081. * @param enable defines the state to set
  14082. */
  14083. Engine.prototype.setDepthWrite = function (enable) {
  14084. this._depthCullingState.depthMask = enable;
  14085. };
  14086. /**
  14087. * Enable or disable color writing
  14088. * @param enable defines the state to set
  14089. */
  14090. Engine.prototype.setColorWrite = function (enable) {
  14091. this._gl.colorMask(enable, enable, enable, enable);
  14092. this._colorWrite = enable;
  14093. };
  14094. /**
  14095. * Gets a boolean indicating if color writing is enabled
  14096. * @returns the current color writing state
  14097. */
  14098. Engine.prototype.getColorWrite = function () {
  14099. return this._colorWrite;
  14100. };
  14101. /**
  14102. * Sets alpha constants used by some alpha blending modes
  14103. * @param r defines the red component
  14104. * @param g defines the green component
  14105. * @param b defines the blue component
  14106. * @param a defines the alpha component
  14107. */
  14108. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14109. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14110. };
  14111. /**
  14112. * Sets the current alpha mode
  14113. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14114. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14115. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14116. */
  14117. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14118. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14119. if (this._alphaMode === mode) {
  14120. return;
  14121. }
  14122. switch (mode) {
  14123. case Engine.ALPHA_DISABLE:
  14124. this._alphaState.alphaBlend = false;
  14125. break;
  14126. case Engine.ALPHA_PREMULTIPLIED:
  14127. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14128. this._alphaState.alphaBlend = true;
  14129. break;
  14130. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14131. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14132. this._alphaState.alphaBlend = true;
  14133. break;
  14134. case Engine.ALPHA_COMBINE:
  14135. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14136. this._alphaState.alphaBlend = true;
  14137. break;
  14138. case Engine.ALPHA_ONEONE:
  14139. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14140. this._alphaState.alphaBlend = true;
  14141. break;
  14142. case Engine.ALPHA_ADD:
  14143. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14144. this._alphaState.alphaBlend = true;
  14145. break;
  14146. case Engine.ALPHA_SUBTRACT:
  14147. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14148. this._alphaState.alphaBlend = true;
  14149. break;
  14150. case Engine.ALPHA_MULTIPLY:
  14151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14152. this._alphaState.alphaBlend = true;
  14153. break;
  14154. case Engine.ALPHA_MAXIMIZED:
  14155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14156. this._alphaState.alphaBlend = true;
  14157. break;
  14158. case Engine.ALPHA_INTERPOLATE:
  14159. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14160. this._alphaState.alphaBlend = true;
  14161. break;
  14162. case Engine.ALPHA_SCREENMODE:
  14163. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14164. this._alphaState.alphaBlend = true;
  14165. break;
  14166. }
  14167. if (!noDepthWriteChange) {
  14168. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14169. }
  14170. this._alphaMode = mode;
  14171. };
  14172. /**
  14173. * Gets the current alpha mode
  14174. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14175. * @returns the current alpha mode
  14176. */
  14177. Engine.prototype.getAlphaMode = function () {
  14178. return this._alphaMode;
  14179. };
  14180. // Textures
  14181. /**
  14182. * Force the entire cache to be cleared
  14183. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14184. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14185. */
  14186. Engine.prototype.wipeCaches = function (bruteForce) {
  14187. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14188. return;
  14189. }
  14190. this._currentEffect = null;
  14191. if (bruteForce) {
  14192. this.resetTextureCache();
  14193. this._currentProgram = null;
  14194. this._stencilState.reset();
  14195. this._depthCullingState.reset();
  14196. this.setDepthFunctionToLessOrEqual();
  14197. this._alphaState.reset();
  14198. }
  14199. this._resetVertexBufferBinding();
  14200. this._cachedIndexBuffer = null;
  14201. this._cachedEffectForVertexBuffers = null;
  14202. this._unbindVertexArrayObject();
  14203. this.bindIndexBuffer(null);
  14204. };
  14205. /**
  14206. * Set the compressed texture format to use, based on the formats you have, and the formats
  14207. * supported by the hardware / browser.
  14208. *
  14209. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14210. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14211. * to API arguments needed to compressed textures. This puts the burden on the container
  14212. * generator to house the arcane code for determining these for current & future formats.
  14213. *
  14214. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14215. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14216. *
  14217. * Note: The result of this call is not taken into account when a texture is base64.
  14218. *
  14219. * @param formatsAvailable defines the list of those format families you have created
  14220. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14221. *
  14222. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14223. * @returns The extension selected.
  14224. */
  14225. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14226. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14227. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14228. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14229. return this._textureFormatInUse = this._texturesSupported[i];
  14230. }
  14231. }
  14232. }
  14233. // actively set format to nothing, to allow this to be called more than once
  14234. // and possibly fail the 2nd time
  14235. this._textureFormatInUse = null;
  14236. return null;
  14237. };
  14238. /** @ignore */
  14239. Engine.prototype._createTexture = function () {
  14240. var texture = this._gl.createTexture();
  14241. if (!texture) {
  14242. throw new Error("Unable to create texture");
  14243. }
  14244. return texture;
  14245. };
  14246. /**
  14247. * Usually called from BABYLON.Texture.ts.
  14248. * Passed information to create a WebGLTexture
  14249. * @param urlArg defines a value which contains one of the following:
  14250. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14251. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14252. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14253. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14254. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14255. * @param scene needed for loading to the correct scene
  14256. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14257. * @param onLoad optional callback to be called upon successful completion
  14258. * @param onError optional callback to be called upon failure
  14259. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14260. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14261. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14262. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14263. */
  14264. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14265. var _this = this;
  14266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14267. if (onLoad === void 0) { onLoad = null; }
  14268. if (onError === void 0) { onError = null; }
  14269. if (buffer === void 0) { buffer = null; }
  14270. if (fallback === void 0) { fallback = null; }
  14271. if (format === void 0) { format = null; }
  14272. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14273. var fromData = url.substr(0, 5) === "data:";
  14274. var fromBlob = url.substr(0, 5) === "blob:";
  14275. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14276. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14277. // establish the file extension, if possible
  14278. var lastDot = url.lastIndexOf('.');
  14279. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14280. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14281. var isTGA = (extension.indexOf(".tga") === 0);
  14282. // determine if a ktx file should be substituted
  14283. var isKTX = false;
  14284. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14285. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14286. isKTX = true;
  14287. }
  14288. if (scene) {
  14289. scene._addPendingData(texture);
  14290. }
  14291. texture.url = url;
  14292. texture.generateMipMaps = !noMipmap;
  14293. texture.samplingMode = samplingMode;
  14294. texture.invertY = invertY;
  14295. if (!this._doNotHandleContextLost) {
  14296. // Keep a link to the buffer only if we plan to handle context lost
  14297. texture._buffer = buffer;
  14298. }
  14299. var onLoadObserver = null;
  14300. if (onLoad && !fallback) {
  14301. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14302. }
  14303. if (!fallback)
  14304. this._internalTexturesCache.push(texture);
  14305. var onerror = function (message, exception) {
  14306. if (scene) {
  14307. scene._removePendingData(texture);
  14308. }
  14309. if (onLoadObserver) {
  14310. texture.onLoadedObservable.remove(onLoadObserver);
  14311. }
  14312. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14313. if (isKTX) {
  14314. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14315. }
  14316. else if (BABYLON.Tools.UseFallbackTexture) {
  14317. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14318. }
  14319. if (onError) {
  14320. onError(message || "Unknown error", exception);
  14321. }
  14322. };
  14323. var callback = null;
  14324. // processing for non-image formats
  14325. if (isKTX || isTGA || isDDS) {
  14326. if (isKTX) {
  14327. callback = function (data) {
  14328. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14329. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14330. ktx.uploadLevels(_this._gl, !noMipmap);
  14331. return false;
  14332. }, samplingMode);
  14333. };
  14334. }
  14335. else if (isTGA) {
  14336. callback = function (arrayBuffer) {
  14337. var data = new Uint8Array(arrayBuffer);
  14338. var header = BABYLON.TGATools.GetTGAHeader(data);
  14339. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14340. BABYLON.TGATools.UploadContent(_this._gl, data);
  14341. return false;
  14342. }, samplingMode);
  14343. };
  14344. }
  14345. else if (isDDS) {
  14346. callback = function (data) {
  14347. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14348. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14349. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14350. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14351. return false;
  14352. }, samplingMode);
  14353. };
  14354. }
  14355. if (!buffer) {
  14356. this._loadFile(url, function (data) {
  14357. if (callback) {
  14358. callback(data);
  14359. }
  14360. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14361. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14362. });
  14363. }
  14364. else {
  14365. if (callback) {
  14366. callback(buffer);
  14367. }
  14368. }
  14369. // image format processing
  14370. }
  14371. else {
  14372. var onload = function (img) {
  14373. if (fromBlob && !_this._doNotHandleContextLost) {
  14374. // We need to store the image if we need to rebuild the texture
  14375. // in case of a webgl context lost
  14376. texture._buffer = img;
  14377. }
  14378. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14379. var gl = _this._gl;
  14380. var isPot = (img.width === potWidth && img.height === potHeight);
  14381. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14382. if (isPot) {
  14383. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14384. return false;
  14385. }
  14386. // Using shaders to rescale because canvas.drawImage is lossy
  14387. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14388. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14389. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14394. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14395. _this._releaseTexture(source);
  14396. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14397. continuationCallback();
  14398. });
  14399. return true;
  14400. }, samplingMode);
  14401. };
  14402. if (!fromData || isBase64)
  14403. if (buffer instanceof HTMLImageElement) {
  14404. onload(buffer);
  14405. }
  14406. else {
  14407. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14408. }
  14409. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14410. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14411. else
  14412. onload(buffer);
  14413. }
  14414. return texture;
  14415. };
  14416. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14417. var _this = this;
  14418. var rtt = this.createRenderTargetTexture({
  14419. width: destination.width,
  14420. height: destination.height,
  14421. }, {
  14422. generateMipMaps: false,
  14423. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14424. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14425. generateDepthBuffer: false,
  14426. generateStencilBuffer: false
  14427. });
  14428. if (!this._rescalePostProcess) {
  14429. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14430. }
  14431. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14432. _this._rescalePostProcess.onApply = function (effect) {
  14433. effect._bindTexture("textureSampler", source);
  14434. };
  14435. var hostingScene = scene;
  14436. if (!hostingScene) {
  14437. hostingScene = _this.scenes[_this.scenes.length - 1];
  14438. }
  14439. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14440. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14441. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14442. _this.unBindFramebuffer(rtt);
  14443. _this._releaseTexture(rtt);
  14444. if (onComplete) {
  14445. onComplete();
  14446. }
  14447. });
  14448. };
  14449. /**
  14450. * Update a raw texture
  14451. * @param texture defines the texture to update
  14452. * @param data defines the data to store in the texture
  14453. * @param format defines the format of the data
  14454. * @param invertY defines if data must be stored with Y axis inverted
  14455. * @param compression defines the compression used (null by default)
  14456. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14457. */
  14458. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14459. if (compression === void 0) { compression = null; }
  14460. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14461. if (!texture) {
  14462. return;
  14463. }
  14464. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14465. var internalFormat = this._getInternalFormat(format);
  14466. var textureType = this._getWebGLTextureType(type);
  14467. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14468. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14469. if (!this._doNotHandleContextLost) {
  14470. texture._bufferView = data;
  14471. texture.format = format;
  14472. texture.type = type;
  14473. texture.invertY = invertY;
  14474. texture._compression = compression;
  14475. }
  14476. if (texture.width % 4 !== 0) {
  14477. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14478. }
  14479. if (compression && data) {
  14480. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14481. }
  14482. else {
  14483. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14484. }
  14485. if (texture.generateMipMaps) {
  14486. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14487. }
  14488. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14489. // this.resetTextureCache();
  14490. texture.isReady = true;
  14491. };
  14492. /**
  14493. * Creates a raw texture
  14494. * @param data defines the data to store in the texture
  14495. * @param width defines the width of the texture
  14496. * @param height defines the height of the texture
  14497. * @param format defines the format of the data
  14498. * @param generateMipMaps defines if the engine should generate the mip levels
  14499. * @param invertY defines if data must be stored with Y axis inverted
  14500. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14501. * @param compression defines the compression used (null by default)
  14502. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14503. * @returns the raw texture inside an InternalTexture
  14504. */
  14505. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14506. if (compression === void 0) { compression = null; }
  14507. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14508. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14509. texture.baseWidth = width;
  14510. texture.baseHeight = height;
  14511. texture.width = width;
  14512. texture.height = height;
  14513. texture.format = format;
  14514. texture.generateMipMaps = generateMipMaps;
  14515. texture.samplingMode = samplingMode;
  14516. texture.invertY = invertY;
  14517. texture._compression = compression;
  14518. texture.type = type;
  14519. if (!this._doNotHandleContextLost) {
  14520. texture._bufferView = data;
  14521. }
  14522. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14523. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14524. // Filters
  14525. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14526. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14527. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14528. if (generateMipMaps) {
  14529. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14530. }
  14531. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14532. this._internalTexturesCache.push(texture);
  14533. return texture;
  14534. };
  14535. /**
  14536. * Creates a dynamic texture
  14537. * @param width defines the width of the texture
  14538. * @param height defines the height of the texture
  14539. * @param generateMipMaps defines if the engine should generate the mip levels
  14540. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14541. * @returns the dynamic texture inside an InternalTexture
  14542. */
  14543. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14544. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14545. texture.baseWidth = width;
  14546. texture.baseHeight = height;
  14547. if (generateMipMaps) {
  14548. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14549. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14550. }
  14551. // this.resetTextureCache();
  14552. texture.width = width;
  14553. texture.height = height;
  14554. texture.isReady = false;
  14555. texture.generateMipMaps = generateMipMaps;
  14556. texture.samplingMode = samplingMode;
  14557. this.updateTextureSamplingMode(samplingMode, texture);
  14558. this._internalTexturesCache.push(texture);
  14559. return texture;
  14560. };
  14561. /**
  14562. * Update the sampling mode of a given texture
  14563. * @param samplingMode defines the required sampling mode
  14564. * @param texture defines the texture to update
  14565. */
  14566. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14567. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14568. if (texture.isCube) {
  14569. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14570. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14571. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14572. }
  14573. else if (texture.is3D) {
  14574. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14575. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14576. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14577. }
  14578. else {
  14579. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14580. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14581. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14582. }
  14583. texture.samplingMode = samplingMode;
  14584. };
  14585. /**
  14586. * Update the content of a dynamic texture
  14587. * @param texture defines the texture to update
  14588. * @param canvas defines the canvas containing the source
  14589. * @param invertY defines if data must be stored with Y axis inverted
  14590. * @param premulAlpha defines if alpha is stored as premultiplied
  14591. * @param format defines the format of the data
  14592. */
  14593. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14594. if (premulAlpha === void 0) { premulAlpha = false; }
  14595. if (!texture) {
  14596. return;
  14597. }
  14598. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14599. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14600. if (premulAlpha) {
  14601. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14602. }
  14603. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14604. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14605. if (texture.generateMipMaps) {
  14606. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14607. }
  14608. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14609. if (premulAlpha) {
  14610. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14611. }
  14612. texture.isReady = true;
  14613. };
  14614. /**
  14615. * Update a video texture
  14616. * @param texture defines the texture to update
  14617. * @param video defines the video element to use
  14618. * @param invertY defines if data must be stored with Y axis inverted
  14619. */
  14620. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14621. if (!texture || texture._isDisabled) {
  14622. return;
  14623. }
  14624. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14625. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14626. try {
  14627. // Testing video texture support
  14628. if (this._videoTextureSupported === undefined) {
  14629. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14630. if (this._gl.getError() !== 0) {
  14631. this._videoTextureSupported = false;
  14632. }
  14633. else {
  14634. this._videoTextureSupported = true;
  14635. }
  14636. }
  14637. // Copy video through the current working canvas if video texture is not supported
  14638. if (!this._videoTextureSupported) {
  14639. if (!texture._workingCanvas) {
  14640. texture._workingCanvas = document.createElement("canvas");
  14641. var context = texture._workingCanvas.getContext("2d");
  14642. if (!context) {
  14643. throw new Error("Unable to get 2d context");
  14644. }
  14645. texture._workingContext = context;
  14646. texture._workingCanvas.width = texture.width;
  14647. texture._workingCanvas.height = texture.height;
  14648. }
  14649. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14650. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14651. }
  14652. else {
  14653. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14654. }
  14655. if (texture.generateMipMaps) {
  14656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14657. }
  14658. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14659. // this.resetTextureCache();
  14660. texture.isReady = true;
  14661. }
  14662. catch (ex) {
  14663. // Something unexpected
  14664. // Let's disable the texture
  14665. texture._isDisabled = true;
  14666. }
  14667. };
  14668. /**
  14669. * Updates a depth texture Comparison Mode and Function.
  14670. * If the comparison Function is equal to 0, the mode will be set to none.
  14671. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14672. * @param texture The texture to set the comparison function for
  14673. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14674. */
  14675. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14676. if (this.webGLVersion === 1) {
  14677. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14678. return;
  14679. }
  14680. var gl = this._gl;
  14681. if (texture.isCube) {
  14682. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14683. if (comparisonFunction === 0) {
  14684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14686. }
  14687. else {
  14688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14690. }
  14691. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14692. }
  14693. else {
  14694. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14695. if (comparisonFunction === 0) {
  14696. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14697. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14698. }
  14699. else {
  14700. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14701. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14702. }
  14703. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14704. }
  14705. texture._comparisonFunction = comparisonFunction;
  14706. };
  14707. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14708. var width = size.width || size;
  14709. var height = size.height || size;
  14710. internalTexture.baseWidth = width;
  14711. internalTexture.baseHeight = height;
  14712. internalTexture.width = width;
  14713. internalTexture.height = height;
  14714. internalTexture.isReady = true;
  14715. internalTexture.samples = 1;
  14716. internalTexture.generateMipMaps = false;
  14717. internalTexture._generateDepthBuffer = true;
  14718. internalTexture._generateStencilBuffer = generateStencil;
  14719. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14720. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14721. internalTexture._comparisonFunction = comparisonFunction;
  14722. var gl = this._gl;
  14723. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14724. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14725. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14726. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14727. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14728. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14729. if (comparisonFunction === 0) {
  14730. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14731. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14732. }
  14733. else {
  14734. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14735. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14736. }
  14737. };
  14738. /**
  14739. * Creates a depth stencil texture.
  14740. * This is only available in WebGL 2 or with the depth texture extension available.
  14741. * @param size The size of face edge in the texture.
  14742. * @param options The options defining the texture.
  14743. * @returns The texture
  14744. */
  14745. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14746. if (options.isCube) {
  14747. var width = size.width || size;
  14748. return this._createDepthStencilCubeTexture(width, options);
  14749. }
  14750. else {
  14751. return this._createDepthStencilTexture(size, options);
  14752. }
  14753. };
  14754. /**
  14755. * Creates a depth stencil texture.
  14756. * This is only available in WebGL 2 or with the depth texture extension available.
  14757. * @param size The size of face edge in the texture.
  14758. * @param options The options defining the texture.
  14759. * @returns The texture
  14760. */
  14761. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14762. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14763. if (!this._caps.depthTextureExtension) {
  14764. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14765. return internalTexture;
  14766. }
  14767. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14768. var gl = this._gl;
  14769. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14770. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14771. if (this.webGLVersion > 1) {
  14772. if (internalOptions.generateStencil) {
  14773. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14774. }
  14775. else {
  14776. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14777. }
  14778. }
  14779. else {
  14780. if (internalOptions.generateStencil) {
  14781. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14782. }
  14783. else {
  14784. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14785. }
  14786. }
  14787. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14788. return internalTexture;
  14789. };
  14790. /**
  14791. * Creates a depth stencil cube texture.
  14792. * This is only available in WebGL 2.
  14793. * @param size The size of face edge in the cube texture.
  14794. * @param options The options defining the cube texture.
  14795. * @returns The cube texture
  14796. */
  14797. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14798. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14799. internalTexture.isCube = true;
  14800. if (this.webGLVersion === 1) {
  14801. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14802. return internalTexture;
  14803. }
  14804. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14805. var gl = this._gl;
  14806. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14807. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14808. // Create the depth/stencil buffer
  14809. for (var face = 0; face < 6; face++) {
  14810. if (internalOptions.generateStencil) {
  14811. 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);
  14812. }
  14813. else {
  14814. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14815. }
  14816. }
  14817. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14818. return internalTexture;
  14819. };
  14820. /**
  14821. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14822. * @param renderTarget The render target to set the frame buffer for
  14823. */
  14824. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14825. // Create the framebuffer
  14826. var internalTexture = renderTarget.getInternalTexture();
  14827. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14828. return;
  14829. }
  14830. var gl = this._gl;
  14831. var depthStencilTexture = renderTarget.depthStencilTexture;
  14832. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14833. if (depthStencilTexture.isCube) {
  14834. if (depthStencilTexture._generateStencilBuffer) {
  14835. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14836. }
  14837. else {
  14838. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14839. }
  14840. }
  14841. else {
  14842. if (depthStencilTexture._generateStencilBuffer) {
  14843. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14844. }
  14845. else {
  14846. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14847. }
  14848. }
  14849. this.bindUnboundFramebuffer(null);
  14850. };
  14851. /**
  14852. * Creates a new render target texture
  14853. * @param size defines the size of the texture
  14854. * @param options defines the options used to create the texture
  14855. * @returns a new render target texture stored in an InternalTexture
  14856. */
  14857. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14858. var fullOptions = new RenderTargetCreationOptions();
  14859. if (options !== undefined && typeof options === "object") {
  14860. fullOptions.generateMipMaps = options.generateMipMaps;
  14861. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14862. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14863. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14864. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14865. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14866. }
  14867. else {
  14868. fullOptions.generateMipMaps = options;
  14869. fullOptions.generateDepthBuffer = true;
  14870. fullOptions.generateStencilBuffer = false;
  14871. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14872. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14873. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14874. }
  14875. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14876. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14877. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14878. }
  14879. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14880. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14881. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14882. }
  14883. var gl = this._gl;
  14884. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14885. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14886. var width = size.width || size;
  14887. var height = size.height || size;
  14888. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14889. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14890. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14891. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14892. }
  14893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14897. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14898. // Create the framebuffer
  14899. var framebuffer = gl.createFramebuffer();
  14900. this.bindUnboundFramebuffer(framebuffer);
  14901. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14902. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14903. if (fullOptions.generateMipMaps) {
  14904. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14905. }
  14906. // Unbind
  14907. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14909. this.bindUnboundFramebuffer(null);
  14910. texture._framebuffer = framebuffer;
  14911. texture.baseWidth = width;
  14912. texture.baseHeight = height;
  14913. texture.width = width;
  14914. texture.height = height;
  14915. texture.isReady = true;
  14916. texture.samples = 1;
  14917. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14918. texture.samplingMode = fullOptions.samplingMode;
  14919. texture.type = fullOptions.type;
  14920. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14921. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14922. // this.resetTextureCache();
  14923. this._internalTexturesCache.push(texture);
  14924. return texture;
  14925. };
  14926. /**
  14927. * Create a multi render target texture
  14928. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14929. * @param size defines the size of the texture
  14930. * @param options defines the creation options
  14931. * @returns the cube texture as an InternalTexture
  14932. */
  14933. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14934. var generateMipMaps = false;
  14935. var generateDepthBuffer = true;
  14936. var generateStencilBuffer = false;
  14937. var generateDepthTexture = false;
  14938. var textureCount = 1;
  14939. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14940. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14941. var types = new Array();
  14942. var samplingModes = new Array();
  14943. if (options !== undefined) {
  14944. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14945. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14946. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14947. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14948. textureCount = options.textureCount || 1;
  14949. if (options.types) {
  14950. types = options.types;
  14951. }
  14952. if (options.samplingModes) {
  14953. samplingModes = options.samplingModes;
  14954. }
  14955. }
  14956. var gl = this._gl;
  14957. // Create the framebuffer
  14958. var framebuffer = gl.createFramebuffer();
  14959. this.bindUnboundFramebuffer(framebuffer);
  14960. var width = size.width || size;
  14961. var height = size.height || size;
  14962. var textures = [];
  14963. var attachments = [];
  14964. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14965. for (var i = 0; i < textureCount; i++) {
  14966. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14967. var type = types[i] || defaultType;
  14968. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14969. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14970. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14971. }
  14972. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14973. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14974. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14975. }
  14976. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14977. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14978. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14979. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14980. }
  14981. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14982. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14983. textures.push(texture);
  14984. attachments.push(attachment);
  14985. gl.activeTexture(gl["TEXTURE" + i]);
  14986. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14987. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14988. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14989. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14990. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14991. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14992. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14993. if (generateMipMaps) {
  14994. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14995. }
  14996. // Unbind
  14997. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14998. texture._framebuffer = framebuffer;
  14999. texture._depthStencilBuffer = depthStencilBuffer;
  15000. texture.baseWidth = width;
  15001. texture.baseHeight = height;
  15002. texture.width = width;
  15003. texture.height = height;
  15004. texture.isReady = true;
  15005. texture.samples = 1;
  15006. texture.generateMipMaps = generateMipMaps;
  15007. texture.samplingMode = samplingMode;
  15008. texture.type = type;
  15009. texture._generateDepthBuffer = generateDepthBuffer;
  15010. texture._generateStencilBuffer = generateStencilBuffer;
  15011. texture._attachments = attachments;
  15012. this._internalTexturesCache.push(texture);
  15013. }
  15014. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15015. // Depth texture
  15016. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15017. gl.activeTexture(gl.TEXTURE0);
  15018. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15022. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15023. 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);
  15024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15025. depthTexture._framebuffer = framebuffer;
  15026. depthTexture.baseWidth = width;
  15027. depthTexture.baseHeight = height;
  15028. depthTexture.width = width;
  15029. depthTexture.height = height;
  15030. depthTexture.isReady = true;
  15031. depthTexture.samples = 1;
  15032. depthTexture.generateMipMaps = generateMipMaps;
  15033. depthTexture.samplingMode = gl.NEAREST;
  15034. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15035. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15036. textures.push(depthTexture);
  15037. this._internalTexturesCache.push(depthTexture);
  15038. }
  15039. gl.drawBuffers(attachments);
  15040. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15041. this.bindUnboundFramebuffer(null);
  15042. this.resetTextureCache();
  15043. return textures;
  15044. };
  15045. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15046. if (samples === void 0) { samples = 1; }
  15047. var depthStencilBuffer = null;
  15048. var gl = this._gl;
  15049. // Create the depth/stencil buffer
  15050. if (generateStencilBuffer) {
  15051. depthStencilBuffer = gl.createRenderbuffer();
  15052. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15053. if (samples > 1) {
  15054. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15055. }
  15056. else {
  15057. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15058. }
  15059. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15060. }
  15061. else if (generateDepthBuffer) {
  15062. depthStencilBuffer = gl.createRenderbuffer();
  15063. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15064. if (samples > 1) {
  15065. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15066. }
  15067. else {
  15068. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15069. }
  15070. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15071. }
  15072. return depthStencilBuffer;
  15073. };
  15074. /**
  15075. * Updates the sample count of a render target texture
  15076. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15077. * @param texture defines the texture to update
  15078. * @param samples defines the sample count to set
  15079. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15080. */
  15081. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15082. if (this.webGLVersion < 2 || !texture) {
  15083. return 1;
  15084. }
  15085. if (texture.samples === samples) {
  15086. return samples;
  15087. }
  15088. var gl = this._gl;
  15089. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15090. // Dispose previous render buffers
  15091. if (texture._depthStencilBuffer) {
  15092. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15093. texture._depthStencilBuffer = null;
  15094. }
  15095. if (texture._MSAAFramebuffer) {
  15096. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15097. texture._MSAAFramebuffer = null;
  15098. }
  15099. if (texture._MSAARenderBuffer) {
  15100. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15101. texture._MSAARenderBuffer = null;
  15102. }
  15103. if (samples > 1) {
  15104. var framebuffer = gl.createFramebuffer();
  15105. if (!framebuffer) {
  15106. throw new Error("Unable to create multi sampled framebuffer");
  15107. }
  15108. texture._MSAAFramebuffer = framebuffer;
  15109. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15110. var colorRenderbuffer = gl.createRenderbuffer();
  15111. if (!colorRenderbuffer) {
  15112. throw new Error("Unable to create multi sampled framebuffer");
  15113. }
  15114. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15115. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15116. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15117. texture._MSAARenderBuffer = colorRenderbuffer;
  15118. }
  15119. else {
  15120. this.bindUnboundFramebuffer(texture._framebuffer);
  15121. }
  15122. texture.samples = samples;
  15123. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15124. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15125. this.bindUnboundFramebuffer(null);
  15126. return samples;
  15127. };
  15128. /**
  15129. * Update the sample count for a given multiple render target texture
  15130. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15131. * @param textures defines the textures to update
  15132. * @param samples defines the sample count to set
  15133. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15134. */
  15135. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15136. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15137. return 1;
  15138. }
  15139. if (textures[0].samples === samples) {
  15140. return samples;
  15141. }
  15142. var gl = this._gl;
  15143. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15144. // Dispose previous render buffers
  15145. if (textures[0]._depthStencilBuffer) {
  15146. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15147. textures[0]._depthStencilBuffer = null;
  15148. }
  15149. if (textures[0]._MSAAFramebuffer) {
  15150. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15151. textures[0]._MSAAFramebuffer = null;
  15152. }
  15153. for (var i = 0; i < textures.length; i++) {
  15154. if (textures[i]._MSAARenderBuffer) {
  15155. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15156. textures[i]._MSAARenderBuffer = null;
  15157. }
  15158. }
  15159. if (samples > 1) {
  15160. var framebuffer = gl.createFramebuffer();
  15161. if (!framebuffer) {
  15162. throw new Error("Unable to create multi sampled framebuffer");
  15163. }
  15164. this.bindUnboundFramebuffer(framebuffer);
  15165. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15166. var attachments = [];
  15167. for (var i = 0; i < textures.length; i++) {
  15168. var texture = textures[i];
  15169. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15170. var colorRenderbuffer = gl.createRenderbuffer();
  15171. if (!colorRenderbuffer) {
  15172. throw new Error("Unable to create multi sampled framebuffer");
  15173. }
  15174. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15175. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15176. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15177. texture._MSAAFramebuffer = framebuffer;
  15178. texture._MSAARenderBuffer = colorRenderbuffer;
  15179. texture.samples = samples;
  15180. texture._depthStencilBuffer = depthStencilBuffer;
  15181. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15182. attachments.push(attachment);
  15183. }
  15184. gl.drawBuffers(attachments);
  15185. }
  15186. else {
  15187. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15188. }
  15189. this.bindUnboundFramebuffer(null);
  15190. return samples;
  15191. };
  15192. /** @ignore */
  15193. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15194. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15195. };
  15196. /** @ignore */
  15197. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15198. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15199. };
  15200. /**
  15201. * Creates a new render target cube texture
  15202. * @param size defines the size of the texture
  15203. * @param options defines the options used to create the texture
  15204. * @returns a new render target cube texture stored in an InternalTexture
  15205. */
  15206. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15207. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15208. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15209. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15210. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15211. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15212. }
  15213. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15214. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15215. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15216. }
  15217. var gl = this._gl;
  15218. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15219. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15220. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15221. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15222. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15223. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15224. }
  15225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15229. for (var face = 0; face < 6; face++) {
  15230. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15231. }
  15232. // Create the framebuffer
  15233. var framebuffer = gl.createFramebuffer();
  15234. this.bindUnboundFramebuffer(framebuffer);
  15235. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15236. // MipMaps
  15237. if (fullOptions.generateMipMaps) {
  15238. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15239. }
  15240. // Unbind
  15241. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15242. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15243. this.bindUnboundFramebuffer(null);
  15244. texture._framebuffer = framebuffer;
  15245. texture.width = size;
  15246. texture.height = size;
  15247. texture.isReady = true;
  15248. texture.isCube = true;
  15249. texture.samples = 1;
  15250. texture.generateMipMaps = fullOptions.generateMipMaps;
  15251. texture.samplingMode = fullOptions.samplingMode;
  15252. texture.type = fullOptions.type;
  15253. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15254. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15255. this._internalTexturesCache.push(texture);
  15256. return texture;
  15257. };
  15258. /**
  15259. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15260. * @param rootUrl defines the url where the file to load is located
  15261. * @param scene defines the current scene
  15262. * @param scale defines scale to apply to the mip map selection
  15263. * @param offset defines offset to apply to the mip map selection
  15264. * @param onLoad defines an optional callback raised when the texture is loaded
  15265. * @param onError defines an optional callback raised if there is an issue to load the texture
  15266. * @param format defines the format of the data
  15267. * @param forcedExtension defines the extension to use to pick the right loader
  15268. * @returns the cube texture as an InternalTexture
  15269. */
  15270. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15271. var _this = this;
  15272. if (onLoad === void 0) { onLoad = null; }
  15273. if (onError === void 0) { onError = null; }
  15274. if (forcedExtension === void 0) { forcedExtension = null; }
  15275. var callback = function (loadData) {
  15276. if (!loadData) {
  15277. if (onLoad) {
  15278. onLoad(null);
  15279. }
  15280. return;
  15281. }
  15282. var texture = loadData.texture;
  15283. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15284. texture._lodGenerationScale = scale;
  15285. texture._lodGenerationOffset = offset;
  15286. if (_this._caps.textureLOD) {
  15287. // Do not add extra process if texture lod is supported.
  15288. if (onLoad) {
  15289. onLoad(texture);
  15290. }
  15291. return;
  15292. }
  15293. var mipSlices = 3;
  15294. var gl = _this._gl;
  15295. var width = loadData.width;
  15296. if (!width) {
  15297. return;
  15298. }
  15299. var textures = [];
  15300. for (var i = 0; i < mipSlices; i++) {
  15301. //compute LOD from even spacing in smoothness (matching shader calculation)
  15302. var smoothness = i / (mipSlices - 1);
  15303. var roughness = 1 - smoothness;
  15304. var minLODIndex = offset; // roughness = 0
  15305. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15306. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15307. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15308. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15309. glTextureFromLod.isCube = true;
  15310. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15311. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15312. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15315. if (loadData.isDDS) {
  15316. var info = loadData.info;
  15317. var data = loadData.data;
  15318. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15319. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15320. }
  15321. else {
  15322. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15323. }
  15324. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15325. // Wrap in a base texture for easy binding.
  15326. var lodTexture = new BABYLON.BaseTexture(scene);
  15327. lodTexture.isCube = true;
  15328. lodTexture._texture = glTextureFromLod;
  15329. glTextureFromLod.isReady = true;
  15330. textures.push(lodTexture);
  15331. }
  15332. texture._lodTextureHigh = textures[2];
  15333. texture._lodTextureMid = textures[1];
  15334. texture._lodTextureLow = textures[0];
  15335. if (onLoad) {
  15336. onLoad(texture);
  15337. }
  15338. };
  15339. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15340. };
  15341. /**
  15342. * Creates a cube texture
  15343. * @param rootUrl defines the url where the files to load is located
  15344. * @param scene defines the current scene
  15345. * @param files defines the list of files to load (1 per face)
  15346. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15347. * @param onLoad defines an optional callback raised when the texture is loaded
  15348. * @param onError defines an optional callback raised if there is an issue to load the texture
  15349. * @param format defines the format of the data
  15350. * @param forcedExtension defines the extension to use to pick the right loader
  15351. * @returns the cube texture as an InternalTexture
  15352. */
  15353. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15354. var _this = this;
  15355. if (onLoad === void 0) { onLoad = null; }
  15356. if (onError === void 0) { onError = null; }
  15357. if (forcedExtension === void 0) { forcedExtension = null; }
  15358. var gl = this._gl;
  15359. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15360. texture.isCube = true;
  15361. texture.url = rootUrl;
  15362. texture.generateMipMaps = !noMipmap;
  15363. if (!this._doNotHandleContextLost) {
  15364. texture._extension = forcedExtension;
  15365. texture._files = files;
  15366. }
  15367. var isKTX = false;
  15368. var isDDS = false;
  15369. var lastDot = rootUrl.lastIndexOf('.');
  15370. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15371. if (this._textureFormatInUse) {
  15372. extension = this._textureFormatInUse;
  15373. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15374. isKTX = true;
  15375. }
  15376. else {
  15377. isDDS = (extension === ".dds");
  15378. }
  15379. var onerror = function (request, exception) {
  15380. if (onError && request) {
  15381. onError(request.status + " " + request.statusText, exception);
  15382. }
  15383. };
  15384. if (isKTX) {
  15385. this._loadFile(rootUrl, function (data) {
  15386. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15387. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15388. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15389. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15390. ktx.uploadLevels(_this._gl, !noMipmap);
  15391. _this.setCubeMapTextureParams(gl, loadMipmap);
  15392. texture.width = ktx.pixelWidth;
  15393. texture.height = ktx.pixelHeight;
  15394. texture.isReady = true;
  15395. }, undefined, undefined, true, onerror);
  15396. }
  15397. else if (isDDS) {
  15398. if (files && files.length === 6) {
  15399. this._cascadeLoadFiles(scene, function (imgs) {
  15400. var info;
  15401. var loadMipmap = false;
  15402. var width = 0;
  15403. for (var index = 0; index < imgs.length; index++) {
  15404. var data = imgs[index];
  15405. info = BABYLON.DDSTools.GetDDSInfo(data);
  15406. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15407. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15408. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15409. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15410. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15411. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15412. }
  15413. texture.width = info.width;
  15414. texture.height = info.height;
  15415. texture.type = info.textureType;
  15416. width = info.width;
  15417. }
  15418. _this.setCubeMapTextureParams(gl, loadMipmap);
  15419. texture.isReady = true;
  15420. if (onLoad) {
  15421. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15422. }
  15423. }, files, onError);
  15424. }
  15425. else {
  15426. this._loadFile(rootUrl, function (data) {
  15427. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15428. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15429. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15430. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15431. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15432. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15433. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15434. }
  15435. _this.setCubeMapTextureParams(gl, loadMipmap);
  15436. texture.width = info.width;
  15437. texture.height = info.height;
  15438. texture.isReady = true;
  15439. texture.type = info.textureType;
  15440. if (onLoad) {
  15441. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15442. }
  15443. }, undefined, undefined, true, onerror);
  15444. }
  15445. }
  15446. else {
  15447. if (!files) {
  15448. throw new Error("Cannot load cubemap because files were not defined");
  15449. }
  15450. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15451. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15452. var height = width;
  15453. _this._prepareWorkingCanvas();
  15454. if (!_this._workingCanvas || !_this._workingContext) {
  15455. return;
  15456. }
  15457. _this._workingCanvas.width = width;
  15458. _this._workingCanvas.height = height;
  15459. var faces = [
  15460. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15461. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15462. ];
  15463. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15464. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15465. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15466. for (var index = 0; index < faces.length; index++) {
  15467. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15468. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15469. }
  15470. if (!noMipmap) {
  15471. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15472. }
  15473. _this.setCubeMapTextureParams(gl, !noMipmap);
  15474. texture.width = width;
  15475. texture.height = height;
  15476. texture.isReady = true;
  15477. if (format) {
  15478. texture.format = format;
  15479. }
  15480. texture.onLoadedObservable.notifyObservers(texture);
  15481. texture.onLoadedObservable.clear();
  15482. if (onLoad) {
  15483. onLoad();
  15484. }
  15485. }, files, onError);
  15486. }
  15487. this._internalTexturesCache.push(texture);
  15488. return texture;
  15489. };
  15490. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15495. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15496. // this.resetTextureCache();
  15497. };
  15498. /**
  15499. * Update a raw cube texture
  15500. * @param texture defines the texture to udpdate
  15501. * @param data defines the data to store
  15502. * @param format defines the data format
  15503. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15504. * @param invertY defines if data must be stored with Y axis inverted
  15505. * @param compression defines the compression used (null by default)
  15506. * @param level defines which level of the texture to update
  15507. */
  15508. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15509. if (compression === void 0) { compression = null; }
  15510. if (level === void 0) { level = 0; }
  15511. texture._bufferViewArray = data;
  15512. texture.format = format;
  15513. texture.type = type;
  15514. texture.invertY = invertY;
  15515. texture._compression = compression;
  15516. var gl = this._gl;
  15517. var textureType = this._getWebGLTextureType(type);
  15518. var internalFormat = this._getInternalFormat(format);
  15519. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15520. var needConversion = false;
  15521. if (internalFormat === gl.RGB) {
  15522. internalFormat = gl.RGBA;
  15523. needConversion = true;
  15524. }
  15525. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15526. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15527. if (texture.width % 4 !== 0) {
  15528. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15529. }
  15530. // Data are known to be in +X +Y +Z -X -Y -Z
  15531. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15532. var faceData = data[faceIndex];
  15533. if (compression) {
  15534. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15535. }
  15536. else {
  15537. if (needConversion) {
  15538. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15539. }
  15540. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15541. }
  15542. }
  15543. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15544. if (isPot && texture.generateMipMaps && level === 0) {
  15545. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15546. }
  15547. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15548. // this.resetTextureCache();
  15549. texture.isReady = true;
  15550. };
  15551. /**
  15552. * Creates a new raw cube texture
  15553. * @param data defines the array of data to use to create each face
  15554. * @param size defines the size of the textures
  15555. * @param format defines the format of the data
  15556. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15557. * @param generateMipMaps defines if the engine should generate the mip levels
  15558. * @param invertY defines if data must be stored with Y axis inverted
  15559. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15560. * @param compression defines the compression used (null by default)
  15561. * @returns the cube texture as an InternalTexture
  15562. */
  15563. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15564. if (compression === void 0) { compression = null; }
  15565. var gl = this._gl;
  15566. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15567. texture.isCube = true;
  15568. texture.generateMipMaps = generateMipMaps;
  15569. texture.format = format;
  15570. texture.type = type;
  15571. if (!this._doNotHandleContextLost) {
  15572. texture._bufferViewArray = data;
  15573. }
  15574. var textureType = this._getWebGLTextureType(type);
  15575. var internalFormat = this._getInternalFormat(format);
  15576. if (internalFormat === gl.RGB) {
  15577. internalFormat = gl.RGBA;
  15578. }
  15579. var width = size;
  15580. var height = width;
  15581. texture.width = width;
  15582. texture.height = height;
  15583. // Double check on POT to generate Mips.
  15584. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15585. if (!isPot) {
  15586. generateMipMaps = false;
  15587. }
  15588. // Upload data if needed. The texture won't be ready until then.
  15589. if (data) {
  15590. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15591. }
  15592. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15593. // Filters
  15594. if (data && generateMipMaps) {
  15595. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15596. }
  15597. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15600. }
  15601. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15604. }
  15605. else {
  15606. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15609. }
  15610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15612. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15613. return texture;
  15614. };
  15615. /**
  15616. * Creates a new raw cube texture from a specified url
  15617. * @param url defines the url where the data is located
  15618. * @param scene defines the current scene
  15619. * @param size defines the size of the textures
  15620. * @param format defines the format of the data
  15621. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15622. * @param noMipmap defines if the engine should avoid generating the mip levels
  15623. * @param callback defines a callback used to extract texture data from loaded data
  15624. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15625. * @param onLoad defines a callback called when texture is loaded
  15626. * @param onError defines a callback called if there is an error
  15627. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15628. * @param invertY defines if data must be stored with Y axis inverted
  15629. * @returns the cube texture as an InternalTexture
  15630. */
  15631. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15632. var _this = this;
  15633. if (onLoad === void 0) { onLoad = null; }
  15634. if (onError === void 0) { onError = null; }
  15635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15636. if (invertY === void 0) { invertY = false; }
  15637. var gl = this._gl;
  15638. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15639. scene._addPendingData(texture);
  15640. texture.url = url;
  15641. this._internalTexturesCache.push(texture);
  15642. var onerror = function (request, exception) {
  15643. scene._removePendingData(texture);
  15644. if (onError && request) {
  15645. onError(request.status + " " + request.statusText, exception);
  15646. }
  15647. };
  15648. var internalCallback = function (data) {
  15649. var width = texture.width;
  15650. var faceDataArrays = callback(data);
  15651. if (!faceDataArrays) {
  15652. return;
  15653. }
  15654. if (mipmapGenerator) {
  15655. var textureType = _this._getWebGLTextureType(type);
  15656. var internalFormat = _this._getInternalFormat(format);
  15657. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15658. var needConversion = false;
  15659. if (internalFormat === gl.RGB) {
  15660. internalFormat = gl.RGBA;
  15661. needConversion = true;
  15662. }
  15663. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15664. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15665. var mipData = mipmapGenerator(faceDataArrays);
  15666. for (var level = 0; level < mipData.length; level++) {
  15667. var mipSize = width >> level;
  15668. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15669. var mipFaceData = mipData[level][faceIndex];
  15670. if (needConversion) {
  15671. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15672. }
  15673. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15674. }
  15675. }
  15676. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15677. }
  15678. else {
  15679. texture.generateMipMaps = !noMipmap;
  15680. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15681. }
  15682. texture.isReady = true;
  15683. // this.resetTextureCache();
  15684. scene._removePendingData(texture);
  15685. if (onLoad) {
  15686. onLoad();
  15687. }
  15688. };
  15689. this._loadFile(url, function (data) {
  15690. internalCallback(data);
  15691. }, undefined, scene.database, true, onerror);
  15692. return texture;
  15693. };
  15694. ;
  15695. /**
  15696. * Update a raw 3D texture
  15697. * @param texture defines the texture to update
  15698. * @param data defines the data to store
  15699. * @param format defines the data format
  15700. * @param invertY defines if data must be stored with Y axis inverted
  15701. * @param compression defines the used compression (can be null)
  15702. */
  15703. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15704. if (compression === void 0) { compression = null; }
  15705. var internalFormat = this._getInternalFormat(format);
  15706. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15707. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15708. if (!this._doNotHandleContextLost) {
  15709. texture._bufferView = data;
  15710. texture.format = format;
  15711. texture.invertY = invertY;
  15712. texture._compression = compression;
  15713. }
  15714. if (texture.width % 4 !== 0) {
  15715. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15716. }
  15717. if (compression && data) {
  15718. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15719. }
  15720. else {
  15721. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15722. }
  15723. if (texture.generateMipMaps) {
  15724. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15725. }
  15726. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15727. // this.resetTextureCache();
  15728. texture.isReady = true;
  15729. };
  15730. /**
  15731. * Creates a new raw 3D texture
  15732. * @param data defines the data used to create the texture
  15733. * @param width defines the width of the texture
  15734. * @param height defines the height of the texture
  15735. * @param depth defines the depth of the texture
  15736. * @param format defines the format of the texture
  15737. * @param generateMipMaps defines if the engine must generate mip levels
  15738. * @param invertY defines if data must be stored with Y axis inverted
  15739. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15740. * @param compression defines the compressed used (can be null)
  15741. * @returns a new raw 3D texture (stored in an InternalTexture)
  15742. */
  15743. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15744. if (compression === void 0) { compression = null; }
  15745. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15746. texture.baseWidth = width;
  15747. texture.baseHeight = height;
  15748. texture.baseDepth = depth;
  15749. texture.width = width;
  15750. texture.height = height;
  15751. texture.depth = depth;
  15752. texture.format = format;
  15753. texture.generateMipMaps = generateMipMaps;
  15754. texture.samplingMode = samplingMode;
  15755. texture.is3D = true;
  15756. if (!this._doNotHandleContextLost) {
  15757. texture._bufferView = data;
  15758. }
  15759. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15760. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15761. // Filters
  15762. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15763. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15764. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15765. if (generateMipMaps) {
  15766. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15767. }
  15768. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15769. this._internalTexturesCache.push(texture);
  15770. return texture;
  15771. };
  15772. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15773. var gl = this._gl;
  15774. if (!gl) {
  15775. return;
  15776. }
  15777. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15780. if (!noMipmap && !isCompressed) {
  15781. gl.generateMipmap(gl.TEXTURE_2D);
  15782. }
  15783. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15784. // this.resetTextureCache();
  15785. if (scene) {
  15786. scene._removePendingData(texture);
  15787. }
  15788. texture.onLoadedObservable.notifyObservers(texture);
  15789. texture.onLoadedObservable.clear();
  15790. };
  15791. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15792. var _this = this;
  15793. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15794. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15795. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15796. var gl = this._gl;
  15797. if (!gl) {
  15798. return;
  15799. }
  15800. if (!texture._webGLTexture) {
  15801. // this.resetTextureCache();
  15802. if (scene) {
  15803. scene._removePendingData(texture);
  15804. }
  15805. return;
  15806. }
  15807. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15808. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15809. texture.baseWidth = width;
  15810. texture.baseHeight = height;
  15811. texture.width = potWidth;
  15812. texture.height = potHeight;
  15813. texture.isReady = true;
  15814. if (processFunction(potWidth, potHeight, function () {
  15815. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15816. })) {
  15817. // Returning as texture needs extra async steps
  15818. return;
  15819. }
  15820. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15821. };
  15822. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15823. // Create new RGBA data container.
  15824. var rgbaData;
  15825. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15826. rgbaData = new Float32Array(width * height * 4);
  15827. }
  15828. else {
  15829. rgbaData = new Uint32Array(width * height * 4);
  15830. }
  15831. // Convert each pixel.
  15832. for (var x = 0; x < width; x++) {
  15833. for (var y = 0; y < height; y++) {
  15834. var index = (y * width + x) * 3;
  15835. var newIndex = (y * width + x) * 4;
  15836. // Map Old Value to new value.
  15837. rgbaData[newIndex + 0] = rgbData[index + 0];
  15838. rgbaData[newIndex + 1] = rgbData[index + 1];
  15839. rgbaData[newIndex + 2] = rgbData[index + 2];
  15840. // Add fully opaque alpha channel.
  15841. rgbaData[newIndex + 3] = 1;
  15842. }
  15843. }
  15844. return rgbaData;
  15845. };
  15846. /** @ignore */
  15847. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15848. var gl = this._gl;
  15849. if (texture._framebuffer) {
  15850. gl.deleteFramebuffer(texture._framebuffer);
  15851. texture._framebuffer = null;
  15852. }
  15853. if (texture._depthStencilBuffer) {
  15854. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15855. texture._depthStencilBuffer = null;
  15856. }
  15857. if (texture._MSAAFramebuffer) {
  15858. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15859. texture._MSAAFramebuffer = null;
  15860. }
  15861. if (texture._MSAARenderBuffer) {
  15862. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15863. texture._MSAARenderBuffer = null;
  15864. }
  15865. };
  15866. /** @ignore */
  15867. Engine.prototype._releaseTexture = function (texture) {
  15868. var gl = this._gl;
  15869. this._releaseFramebufferObjects(texture);
  15870. gl.deleteTexture(texture._webGLTexture);
  15871. // Unbind channels
  15872. this.unbindAllTextures();
  15873. var index = this._internalTexturesCache.indexOf(texture);
  15874. if (index !== -1) {
  15875. this._internalTexturesCache.splice(index, 1);
  15876. }
  15877. // Integrated fixed lod samplers.
  15878. if (texture._lodTextureHigh) {
  15879. texture._lodTextureHigh.dispose();
  15880. }
  15881. if (texture._lodTextureMid) {
  15882. texture._lodTextureMid.dispose();
  15883. }
  15884. if (texture._lodTextureLow) {
  15885. texture._lodTextureLow.dispose();
  15886. }
  15887. // Set output texture of post process to null if the texture has been released/disposed
  15888. this.scenes.forEach(function (scene) {
  15889. scene.postProcesses.forEach(function (postProcess) {
  15890. if (postProcess._outputTexture == texture) {
  15891. postProcess._outputTexture = null;
  15892. }
  15893. });
  15894. scene.cameras.forEach(function (camera) {
  15895. camera._postProcesses.forEach(function (postProcess) {
  15896. if (postProcess) {
  15897. if (postProcess._outputTexture == texture) {
  15898. postProcess._outputTexture = null;
  15899. }
  15900. }
  15901. });
  15902. });
  15903. });
  15904. };
  15905. Engine.prototype.setProgram = function (program) {
  15906. if (this._currentProgram !== program) {
  15907. this._gl.useProgram(program);
  15908. this._currentProgram = program;
  15909. }
  15910. };
  15911. /**
  15912. * Binds an effect to the webGL context
  15913. * @param effect defines the effect to bind
  15914. */
  15915. Engine.prototype.bindSamplers = function (effect) {
  15916. this.setProgram(effect.getProgram());
  15917. var samplers = effect.getSamplers();
  15918. for (var index = 0; index < samplers.length; index++) {
  15919. var uniform = effect.getUniform(samplers[index]);
  15920. if (uniform) {
  15921. this._boundUniforms[index] = uniform;
  15922. }
  15923. }
  15924. this._currentEffect = null;
  15925. };
  15926. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15927. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15928. return;
  15929. }
  15930. // Remove
  15931. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15932. // Bind last to it
  15933. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15934. // Bind to dummy
  15935. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15936. };
  15937. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15938. if (!internalTexture) {
  15939. return -1;
  15940. }
  15941. internalTexture._initialSlot = channel;
  15942. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  15943. if (channel !== internalTexture._designatedSlot) {
  15944. this._textureCollisions.addCount(1, false);
  15945. }
  15946. }
  15947. else {
  15948. if (channel !== internalTexture._designatedSlot) {
  15949. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  15950. return internalTexture._designatedSlot;
  15951. }
  15952. else {
  15953. // No slot for this texture, let's pick a new one (if we find a free slot)
  15954. if (this._nextFreeTextureSlots.length) {
  15955. return this._nextFreeTextureSlots[0];
  15956. }
  15957. // We need to recycle the oldest bound texture, sorry.
  15958. this._textureCollisions.addCount(1, false);
  15959. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15960. }
  15961. }
  15962. }
  15963. return channel;
  15964. };
  15965. Engine.prototype._linkTrackers = function (previous, next) {
  15966. previous.next = next;
  15967. next.previous = previous;
  15968. };
  15969. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15970. var currentSlot = internalTexture._designatedSlot;
  15971. if (currentSlot === -1) {
  15972. return -1;
  15973. }
  15974. internalTexture._designatedSlot = -1;
  15975. if (this.disableTextureBindingOptimization) {
  15976. return -1;
  15977. }
  15978. // Remove from bound list
  15979. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15980. // Free the slot
  15981. this._boundTexturesCache[currentSlot] = null;
  15982. this._nextFreeTextureSlots.push(currentSlot);
  15983. return currentSlot;
  15984. };
  15985. Engine.prototype._activateCurrentTexture = function () {
  15986. if (this._currentTextureChannel !== this._activeChannel) {
  15987. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15988. this._currentTextureChannel = this._activeChannel;
  15989. }
  15990. };
  15991. /** @ignore */
  15992. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  15993. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15994. if (force === void 0) { force = false; }
  15995. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15996. this._activeChannel = texture._designatedSlot;
  15997. }
  15998. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15999. var isTextureForRendering = texture && texture._initialSlot > -1;
  16000. if (currentTextureBound !== texture || force) {
  16001. if (currentTextureBound) {
  16002. this._removeDesignatedSlot(currentTextureBound);
  16003. }
  16004. this._activateCurrentTexture();
  16005. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16006. this._boundTexturesCache[this._activeChannel] = texture;
  16007. if (texture) {
  16008. if (!this.disableTextureBindingOptimization) {
  16009. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16010. if (slotIndex > -1) {
  16011. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16012. }
  16013. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16014. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16015. }
  16016. texture._designatedSlot = this._activeChannel;
  16017. }
  16018. }
  16019. else if (forTextureDataUpdate) {
  16020. this._activateCurrentTexture();
  16021. }
  16022. if (isTextureForRendering && !forTextureDataUpdate) {
  16023. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16024. }
  16025. };
  16026. /** @ignore */
  16027. Engine.prototype._bindTexture = function (channel, texture) {
  16028. if (channel < 0) {
  16029. return;
  16030. }
  16031. if (texture) {
  16032. channel = this._getCorrectTextureChannel(channel, texture);
  16033. }
  16034. this._activeChannel = channel;
  16035. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16036. };
  16037. /**
  16038. * Sets a texture to the webGL context from a postprocess
  16039. * @param channel defines the channel to use
  16040. * @param postProcess defines the source postprocess
  16041. */
  16042. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16043. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16044. };
  16045. /**
  16046. * Binds the output of the passed in post process to the texture channel specified
  16047. * @param channel The channel the texture should be bound to
  16048. * @param postProcess The post process which's output should be bound
  16049. */
  16050. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16051. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16052. };
  16053. /**
  16054. * Unbind all textures from the webGL context
  16055. */
  16056. Engine.prototype.unbindAllTextures = function () {
  16057. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16058. this._activeChannel = channel;
  16059. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16060. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16061. if (this.webGLVersion > 1) {
  16062. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16063. }
  16064. }
  16065. };
  16066. /**
  16067. * Sets a texture to the according uniform.
  16068. * @param channel The texture channel
  16069. * @param uniform The uniform to set
  16070. * @param texture The texture to apply
  16071. */
  16072. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16073. if (channel < 0) {
  16074. return;
  16075. }
  16076. if (uniform) {
  16077. this._boundUniforms[channel] = uniform;
  16078. }
  16079. this._setTexture(channel, texture);
  16080. };
  16081. /**
  16082. * Sets a depth stencil texture from a render target to the according uniform.
  16083. * @param channel The texture channel
  16084. * @param uniform The uniform to set
  16085. * @param texture The render target texture containing the depth stencil texture to apply
  16086. */
  16087. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16088. if (channel < 0) {
  16089. return;
  16090. }
  16091. if (uniform) {
  16092. this._boundUniforms[channel] = uniform;
  16093. }
  16094. if (!texture || !texture.depthStencilTexture) {
  16095. this._setTexture(channel, null);
  16096. }
  16097. else {
  16098. this._setTexture(channel, texture, false, true);
  16099. }
  16100. };
  16101. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16102. var uniform = this._boundUniforms[sourceSlot];
  16103. if (uniform._currentState === destination) {
  16104. return;
  16105. }
  16106. this._gl.uniform1i(uniform, destination);
  16107. uniform._currentState = destination;
  16108. };
  16109. Engine.prototype._getTextureWrapMode = function (mode) {
  16110. switch (mode) {
  16111. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16112. return this._gl.REPEAT;
  16113. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16114. return this._gl.CLAMP_TO_EDGE;
  16115. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16116. return this._gl.MIRRORED_REPEAT;
  16117. }
  16118. return this._gl.REPEAT;
  16119. };
  16120. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16121. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16122. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16123. // Not ready?
  16124. if (!texture) {
  16125. if (this._boundTexturesCache[channel] != null) {
  16126. this._activeChannel = channel;
  16127. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16128. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16129. if (this.webGLVersion > 1) {
  16130. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16131. }
  16132. }
  16133. return false;
  16134. }
  16135. // Video
  16136. if (texture.video) {
  16137. this._activeChannel = channel;
  16138. texture.update();
  16139. }
  16140. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16141. texture.delayLoad();
  16142. return false;
  16143. }
  16144. var internalTexture;
  16145. if (depthStencilTexture) {
  16146. internalTexture = texture.depthStencilTexture;
  16147. }
  16148. else if (texture.isReady()) {
  16149. internalTexture = texture.getInternalTexture();
  16150. }
  16151. else if (texture.isCube) {
  16152. internalTexture = this.emptyCubeTexture;
  16153. }
  16154. else if (texture.is3D) {
  16155. internalTexture = this.emptyTexture3D;
  16156. }
  16157. else {
  16158. internalTexture = this.emptyTexture;
  16159. }
  16160. if (!isPartOfTextureArray) {
  16161. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16162. }
  16163. var needToBind = true;
  16164. if (this._boundTexturesCache[channel] === internalTexture) {
  16165. this._moveBoundTextureOnTop(internalTexture);
  16166. if (!isPartOfTextureArray) {
  16167. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16168. }
  16169. needToBind = false;
  16170. }
  16171. this._activeChannel = channel;
  16172. if (internalTexture && internalTexture.is3D) {
  16173. if (needToBind) {
  16174. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16175. }
  16176. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16177. internalTexture._cachedWrapU = texture.wrapU;
  16178. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16179. }
  16180. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16181. internalTexture._cachedWrapV = texture.wrapV;
  16182. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16183. }
  16184. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16185. internalTexture._cachedWrapR = texture.wrapR;
  16186. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16187. }
  16188. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16189. }
  16190. else if (internalTexture && internalTexture.isCube) {
  16191. if (needToBind) {
  16192. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16193. }
  16194. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16195. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16196. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16197. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16198. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16199. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16200. }
  16201. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16202. }
  16203. else {
  16204. if (needToBind) {
  16205. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16206. }
  16207. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16208. internalTexture._cachedWrapU = texture.wrapU;
  16209. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16210. }
  16211. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16212. internalTexture._cachedWrapV = texture.wrapV;
  16213. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16214. }
  16215. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16216. }
  16217. return true;
  16218. };
  16219. /**
  16220. * Sets an array of texture to the webGL context
  16221. * @param channel defines the channel where the texture array must be set
  16222. * @param uniform defines the associated uniform location
  16223. * @param textures defines the array of textures to bind
  16224. */
  16225. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16226. if (channel < 0 || !uniform) {
  16227. return;
  16228. }
  16229. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16230. this._textureUnits = new Int32Array(textures.length);
  16231. }
  16232. for (var i = 0; i < textures.length; i++) {
  16233. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16234. }
  16235. this._gl.uniform1iv(uniform, this._textureUnits);
  16236. for (var index = 0; index < textures.length; index++) {
  16237. this._setTexture(this._textureUnits[index], textures[index], true);
  16238. }
  16239. };
  16240. /** @ignore */
  16241. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16242. var internalTexture = texture.getInternalTexture();
  16243. if (!internalTexture) {
  16244. return;
  16245. }
  16246. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16247. var value = texture.anisotropicFilteringLevel;
  16248. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16249. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16250. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16251. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16252. }
  16253. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16254. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16255. internalTexture._cachedAnisotropicFilteringLevel = value;
  16256. }
  16257. };
  16258. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16259. this._bindTextureDirectly(target, texture, true, true);
  16260. this._gl.texParameterf(target, parameter, value);
  16261. };
  16262. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16263. if (texture) {
  16264. this._bindTextureDirectly(target, texture, true, true);
  16265. }
  16266. this._gl.texParameteri(target, parameter, value);
  16267. };
  16268. /**
  16269. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16270. * @param x defines the x coordinate of the rectangle where pixels must be read
  16271. * @param y defines the y coordinate of the rectangle where pixels must be read
  16272. * @param width defines the width of the rectangle where pixels must be read
  16273. * @param height defines the height of the rectangle where pixels must be read
  16274. * @returns a Uint8Array containing RGBA colors
  16275. */
  16276. Engine.prototype.readPixels = function (x, y, width, height) {
  16277. var data = new Uint8Array(height * width * 4);
  16278. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16279. return data;
  16280. };
  16281. /**
  16282. * Add an externaly attached data from its key.
  16283. * This method call will fail and return false, if such key already exists.
  16284. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16285. * @param key the unique key that identifies the data
  16286. * @param data the data object to associate to the key for this Engine instance
  16287. * @return true if no such key were already present and the data was added successfully, false otherwise
  16288. */
  16289. Engine.prototype.addExternalData = function (key, data) {
  16290. if (!this._externalData) {
  16291. this._externalData = new BABYLON.StringDictionary();
  16292. }
  16293. return this._externalData.add(key, data);
  16294. };
  16295. /**
  16296. * Get an externaly attached data from its key
  16297. * @param key the unique key that identifies the data
  16298. * @return the associated data, if present (can be null), or undefined if not present
  16299. */
  16300. Engine.prototype.getExternalData = function (key) {
  16301. if (!this._externalData) {
  16302. this._externalData = new BABYLON.StringDictionary();
  16303. }
  16304. return this._externalData.get(key);
  16305. };
  16306. /**
  16307. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16308. * @param key the unique key that identifies the data
  16309. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16310. * @return the associated data, can be null if the factory returned null.
  16311. */
  16312. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16313. if (!this._externalData) {
  16314. this._externalData = new BABYLON.StringDictionary();
  16315. }
  16316. return this._externalData.getOrAddWithFactory(key, factory);
  16317. };
  16318. /**
  16319. * Remove an externaly attached data from the Engine instance
  16320. * @param key the unique key that identifies the data
  16321. * @return true if the data was successfully removed, false if it doesn't exist
  16322. */
  16323. Engine.prototype.removeExternalData = function (key) {
  16324. if (!this._externalData) {
  16325. this._externalData = new BABYLON.StringDictionary();
  16326. }
  16327. return this._externalData.remove(key);
  16328. };
  16329. /**
  16330. * Unbind all vertex attributes from the webGL context
  16331. */
  16332. Engine.prototype.unbindAllAttributes = function () {
  16333. if (this._mustWipeVertexAttributes) {
  16334. this._mustWipeVertexAttributes = false;
  16335. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16336. this._gl.disableVertexAttribArray(i);
  16337. this._vertexAttribArraysEnabled[i] = false;
  16338. this._currentBufferPointers[i].active = false;
  16339. }
  16340. return;
  16341. }
  16342. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16343. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16344. continue;
  16345. }
  16346. this._gl.disableVertexAttribArray(i);
  16347. this._vertexAttribArraysEnabled[i] = false;
  16348. this._currentBufferPointers[i].active = false;
  16349. }
  16350. };
  16351. /**
  16352. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16353. */
  16354. Engine.prototype.releaseEffects = function () {
  16355. for (var name in this._compiledEffects) {
  16356. this._deleteProgram(this._compiledEffects[name]._program);
  16357. }
  16358. this._compiledEffects = {};
  16359. };
  16360. /**
  16361. * Dispose and release all associated resources
  16362. */
  16363. Engine.prototype.dispose = function () {
  16364. this.hideLoadingUI();
  16365. this.stopRenderLoop();
  16366. // Release postProcesses
  16367. while (this.postProcesses.length) {
  16368. this.postProcesses[0].dispose();
  16369. }
  16370. // Empty texture
  16371. if (this._emptyTexture) {
  16372. this._releaseTexture(this._emptyTexture);
  16373. this._emptyTexture = null;
  16374. }
  16375. if (this._emptyCubeTexture) {
  16376. this._releaseTexture(this._emptyCubeTexture);
  16377. this._emptyCubeTexture = null;
  16378. }
  16379. // Rescale PP
  16380. if (this._rescalePostProcess) {
  16381. this._rescalePostProcess.dispose();
  16382. }
  16383. // Release scenes
  16384. while (this.scenes.length) {
  16385. this.scenes[0].dispose();
  16386. }
  16387. // Release audio engine
  16388. if (Engine.audioEngine) {
  16389. Engine.audioEngine.dispose();
  16390. }
  16391. // Release effects
  16392. this.releaseEffects();
  16393. // Unbind
  16394. this.unbindAllAttributes();
  16395. this._boundUniforms = [];
  16396. if (this._dummyFramebuffer) {
  16397. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16398. }
  16399. //WebVR
  16400. this.disableVR();
  16401. // Events
  16402. if (BABYLON.Tools.IsWindowObjectExist()) {
  16403. window.removeEventListener("blur", this._onBlur);
  16404. window.removeEventListener("focus", this._onFocus);
  16405. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16406. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16407. if (this._renderingCanvas) {
  16408. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16409. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16410. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16411. if (!this._doNotHandleContextLost) {
  16412. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16413. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16414. }
  16415. }
  16416. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16417. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16418. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16419. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16420. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16421. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16422. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16423. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16424. if (this._onVrDisplayConnect) {
  16425. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16426. if (this._onVrDisplayDisconnect) {
  16427. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16428. }
  16429. if (this._onVrDisplayPresentChange) {
  16430. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16431. }
  16432. this._onVrDisplayConnect = null;
  16433. this._onVrDisplayDisconnect = null;
  16434. }
  16435. }
  16436. // Remove from Instances
  16437. var index = Engine.Instances.indexOf(this);
  16438. if (index >= 0) {
  16439. Engine.Instances.splice(index, 1);
  16440. }
  16441. this._workingCanvas = null;
  16442. this._workingContext = null;
  16443. this._currentBufferPointers = [];
  16444. this._renderingCanvas = null;
  16445. this._currentProgram = null;
  16446. this._bindedRenderFunction = null;
  16447. this.onResizeObservable.clear();
  16448. this.onCanvasBlurObservable.clear();
  16449. this.onCanvasFocusObservable.clear();
  16450. this.onCanvasPointerOutObservable.clear();
  16451. this.onBeginFrameObservable.clear();
  16452. this.onEndFrameObservable.clear();
  16453. BABYLON.Effect.ResetCache();
  16454. // Abort active requests
  16455. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16456. var request = _a[_i];
  16457. request.abort();
  16458. }
  16459. };
  16460. // Loading screen
  16461. /**
  16462. * Display the loading screen
  16463. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16464. */
  16465. Engine.prototype.displayLoadingUI = function () {
  16466. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16467. return;
  16468. }
  16469. var loadingScreen = this.loadingScreen;
  16470. if (loadingScreen) {
  16471. loadingScreen.displayLoadingUI();
  16472. }
  16473. };
  16474. /**
  16475. * Hide the loading screen
  16476. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16477. */
  16478. Engine.prototype.hideLoadingUI = function () {
  16479. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16480. return;
  16481. }
  16482. var loadingScreen = this.loadingScreen;
  16483. if (loadingScreen) {
  16484. loadingScreen.hideLoadingUI();
  16485. }
  16486. };
  16487. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16488. /**
  16489. * Gets the current loading screen object
  16490. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16491. */
  16492. get: function () {
  16493. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16494. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16495. return this._loadingScreen;
  16496. },
  16497. /**
  16498. * Sets the current loading screen object
  16499. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16500. */
  16501. set: function (loadingScreen) {
  16502. this._loadingScreen = loadingScreen;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16508. /**
  16509. * Sets the current loading screen text
  16510. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16511. */
  16512. set: function (text) {
  16513. this.loadingScreen.loadingUIText = text;
  16514. },
  16515. enumerable: true,
  16516. configurable: true
  16517. });
  16518. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16519. /**
  16520. * Sets the current loading screen background color
  16521. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16522. */
  16523. set: function (color) {
  16524. this.loadingScreen.loadingUIBackgroundColor = color;
  16525. },
  16526. enumerable: true,
  16527. configurable: true
  16528. });
  16529. /**
  16530. * Attach a new callback raised when context lost event is fired
  16531. * @param callback defines the callback to call
  16532. */
  16533. Engine.prototype.attachContextLostEvent = function (callback) {
  16534. if (this._renderingCanvas) {
  16535. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16536. }
  16537. };
  16538. /**
  16539. * Attach a new callback raised when context restored event is fired
  16540. * @param callback defines the callback to call
  16541. */
  16542. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16543. if (this._renderingCanvas) {
  16544. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16545. }
  16546. };
  16547. /**
  16548. * Gets the source code of the vertex shader associated with a specific webGL program
  16549. * @param program defines the program to use
  16550. * @returns a string containing the source code of the vertex shader associated with the program
  16551. */
  16552. Engine.prototype.getVertexShaderSource = function (program) {
  16553. var shaders = this._gl.getAttachedShaders(program);
  16554. if (!shaders) {
  16555. return null;
  16556. }
  16557. return this._gl.getShaderSource(shaders[0]);
  16558. };
  16559. /**
  16560. * Gets the source code of the fragment shader associated with a specific webGL program
  16561. * @param program defines the program to use
  16562. * @returns a string containing the source code of the fragment shader associated with the program
  16563. */
  16564. Engine.prototype.getFragmentShaderSource = function (program) {
  16565. var shaders = this._gl.getAttachedShaders(program);
  16566. if (!shaders) {
  16567. return null;
  16568. }
  16569. return this._gl.getShaderSource(shaders[1]);
  16570. };
  16571. /**
  16572. * Get the current error code of the webGL context
  16573. * @returns the error code
  16574. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16575. */
  16576. Engine.prototype.getError = function () {
  16577. return this._gl.getError();
  16578. };
  16579. // FPS
  16580. /**
  16581. * Gets the current framerate
  16582. * @returns a number representing the framerate
  16583. */
  16584. Engine.prototype.getFps = function () {
  16585. return this._fps;
  16586. };
  16587. /**
  16588. * Gets the time spent between current and previous frame
  16589. * @returns a number representing the delta time in ms
  16590. */
  16591. Engine.prototype.getDeltaTime = function () {
  16592. return this._deltaTime;
  16593. };
  16594. Engine.prototype._measureFps = function () {
  16595. this._performanceMonitor.sampleFrame();
  16596. this._fps = this._performanceMonitor.averageFPS;
  16597. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16598. };
  16599. /** @ignore */
  16600. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16601. if (faceIndex === void 0) { faceIndex = -1; }
  16602. var gl = this._gl;
  16603. if (!this._dummyFramebuffer) {
  16604. var dummy = gl.createFramebuffer();
  16605. if (!dummy) {
  16606. throw new Error("Unable to create dummy framebuffer");
  16607. }
  16608. this._dummyFramebuffer = dummy;
  16609. }
  16610. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16611. if (faceIndex > -1) {
  16612. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16613. }
  16614. else {
  16615. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16616. }
  16617. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16618. var buffer;
  16619. switch (readType) {
  16620. case gl.UNSIGNED_BYTE:
  16621. buffer = new Uint8Array(4 * width * height);
  16622. readType = gl.UNSIGNED_BYTE;
  16623. break;
  16624. default:
  16625. buffer = new Float32Array(4 * width * height);
  16626. readType = gl.FLOAT;
  16627. break;
  16628. }
  16629. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16630. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16631. return buffer;
  16632. };
  16633. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16634. if (this._webGLVersion > 1) {
  16635. return this._caps.colorBufferFloat;
  16636. }
  16637. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16638. };
  16639. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16640. if (this._webGLVersion > 1) {
  16641. return this._caps.colorBufferFloat;
  16642. }
  16643. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16644. };
  16645. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16646. Engine.prototype._canRenderToFramebuffer = function (type) {
  16647. var gl = this._gl;
  16648. //clear existing errors
  16649. while (gl.getError() !== gl.NO_ERROR) { }
  16650. var successful = true;
  16651. var texture = gl.createTexture();
  16652. gl.bindTexture(gl.TEXTURE_2D, texture);
  16653. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16656. var fb = gl.createFramebuffer();
  16657. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16658. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16659. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16660. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16661. successful = successful && (gl.getError() === gl.NO_ERROR);
  16662. //try render by clearing frame buffer's color buffer
  16663. if (successful) {
  16664. gl.clear(gl.COLOR_BUFFER_BIT);
  16665. successful = successful && (gl.getError() === gl.NO_ERROR);
  16666. }
  16667. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16668. if (successful) {
  16669. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16670. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16671. var readFormat = gl.RGBA;
  16672. var readType = gl.UNSIGNED_BYTE;
  16673. var buffer = new Uint8Array(4);
  16674. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16675. successful = successful && (gl.getError() === gl.NO_ERROR);
  16676. }
  16677. //clean up
  16678. gl.deleteTexture(texture);
  16679. gl.deleteFramebuffer(fb);
  16680. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16681. //clear accumulated errors
  16682. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16683. return successful;
  16684. };
  16685. /** @ignore */
  16686. Engine.prototype._getWebGLTextureType = function (type) {
  16687. if (type === Engine.TEXTURETYPE_FLOAT) {
  16688. return this._gl.FLOAT;
  16689. }
  16690. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16691. // Add Half Float Constant.
  16692. return this._gl.HALF_FLOAT_OES;
  16693. }
  16694. return this._gl.UNSIGNED_BYTE;
  16695. };
  16696. ;
  16697. Engine.prototype._getInternalFormat = function (format) {
  16698. var internalFormat = this._gl.RGBA;
  16699. switch (format) {
  16700. case Engine.TEXTUREFORMAT_ALPHA:
  16701. internalFormat = this._gl.ALPHA;
  16702. break;
  16703. case Engine.TEXTUREFORMAT_LUMINANCE:
  16704. internalFormat = this._gl.LUMINANCE;
  16705. break;
  16706. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16707. internalFormat = this._gl.LUMINANCE_ALPHA;
  16708. break;
  16709. case Engine.TEXTUREFORMAT_RGB:
  16710. case Engine.TEXTUREFORMAT_RGB32F:
  16711. internalFormat = this._gl.RGB;
  16712. break;
  16713. case Engine.TEXTUREFORMAT_RGBA:
  16714. case Engine.TEXTUREFORMAT_RGBA32F:
  16715. internalFormat = this._gl.RGBA;
  16716. break;
  16717. case Engine.TEXTUREFORMAT_R32F:
  16718. internalFormat = this._gl.RED;
  16719. break;
  16720. case Engine.TEXTUREFORMAT_RG32F:
  16721. internalFormat = this._gl.RG;
  16722. break;
  16723. }
  16724. return internalFormat;
  16725. };
  16726. /** @ignore */
  16727. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16728. if (this._webGLVersion === 1) {
  16729. if (format) {
  16730. switch (format) {
  16731. case Engine.TEXTUREFORMAT_LUMINANCE:
  16732. return this._gl.LUMINANCE;
  16733. }
  16734. }
  16735. return this._gl.RGBA;
  16736. }
  16737. if (type === Engine.TEXTURETYPE_FLOAT) {
  16738. if (format) {
  16739. switch (format) {
  16740. case Engine.TEXTUREFORMAT_R32F:
  16741. return this._gl.R32F;
  16742. case Engine.TEXTUREFORMAT_RG32F:
  16743. return this._gl.RG32F;
  16744. case Engine.TEXTUREFORMAT_RGB32F:
  16745. return this._gl.RGB32F;
  16746. }
  16747. }
  16748. return this._gl.RGBA32F;
  16749. }
  16750. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16751. return this._gl.RGBA16F;
  16752. }
  16753. if (format) {
  16754. switch (format) {
  16755. case Engine.TEXTUREFORMAT_LUMINANCE:
  16756. return this._gl.LUMINANCE;
  16757. }
  16758. }
  16759. return this._gl.RGBA;
  16760. };
  16761. ;
  16762. /** @ignore */
  16763. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16764. if (type === Engine.TEXTURETYPE_FLOAT) {
  16765. return this._gl.RGBA32F;
  16766. }
  16767. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16768. return this._gl.RGBA16F;
  16769. }
  16770. return this._gl.RGBA8;
  16771. };
  16772. ;
  16773. /**
  16774. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16775. * @return the new query
  16776. */
  16777. Engine.prototype.createQuery = function () {
  16778. return this._gl.createQuery();
  16779. };
  16780. /**
  16781. * Delete and release a webGL query
  16782. * @param query defines the query to delete
  16783. * @return the current engine
  16784. */
  16785. Engine.prototype.deleteQuery = function (query) {
  16786. this._gl.deleteQuery(query);
  16787. return this;
  16788. };
  16789. /**
  16790. * Check if a given query has resolved and got its value
  16791. * @param query defines the query to check
  16792. * @returns true if the query got its value
  16793. */
  16794. Engine.prototype.isQueryResultAvailable = function (query) {
  16795. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16796. };
  16797. /**
  16798. * Gets the value of a given query
  16799. * @param query defines the query to check
  16800. * @returns the value of the query
  16801. */
  16802. Engine.prototype.getQueryResult = function (query) {
  16803. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16804. };
  16805. /**
  16806. * Initiates an occlusion query
  16807. * @param algorithmType defines the algorithm to use
  16808. * @param query defines the query to use
  16809. * @returns the current engine
  16810. * @see http://doc.babylonjs.com/features/occlusionquery
  16811. */
  16812. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16813. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16814. this._gl.beginQuery(glAlgorithm, query);
  16815. return this;
  16816. };
  16817. /**
  16818. * Ends an occlusion query
  16819. * @see http://doc.babylonjs.com/features/occlusionquery
  16820. * @param algorithmType defines the algorithm to use
  16821. * @returns the current engine
  16822. */
  16823. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16824. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16825. this._gl.endQuery(glAlgorithm);
  16826. return this;
  16827. };
  16828. /* Time queries */
  16829. Engine.prototype._createTimeQuery = function () {
  16830. var timerQuery = this._caps.timerQuery;
  16831. if (timerQuery.createQueryEXT) {
  16832. return timerQuery.createQueryEXT();
  16833. }
  16834. return this.createQuery();
  16835. };
  16836. Engine.prototype._deleteTimeQuery = function (query) {
  16837. var timerQuery = this._caps.timerQuery;
  16838. if (timerQuery.deleteQueryEXT) {
  16839. timerQuery.deleteQueryEXT(query);
  16840. return;
  16841. }
  16842. this.deleteQuery(query);
  16843. };
  16844. Engine.prototype._getTimeQueryResult = function (query) {
  16845. var timerQuery = this._caps.timerQuery;
  16846. if (timerQuery.getQueryObjectEXT) {
  16847. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16848. }
  16849. return this.getQueryResult(query);
  16850. };
  16851. Engine.prototype._getTimeQueryAvailability = function (query) {
  16852. var timerQuery = this._caps.timerQuery;
  16853. if (timerQuery.getQueryObjectEXT) {
  16854. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16855. }
  16856. return this.isQueryResultAvailable(query);
  16857. };
  16858. /**
  16859. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16860. * Please note that only one query can be issued at a time
  16861. * @returns a time token used to track the time span
  16862. */
  16863. Engine.prototype.startTimeQuery = function () {
  16864. var timerQuery = this._caps.timerQuery;
  16865. if (!timerQuery) {
  16866. return null;
  16867. }
  16868. var token = new BABYLON._TimeToken();
  16869. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16870. if (this._caps.canUseTimestampForTimerQuery) {
  16871. token._startTimeQuery = this._createTimeQuery();
  16872. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16873. }
  16874. else {
  16875. if (this._currentNonTimestampToken) {
  16876. return this._currentNonTimestampToken;
  16877. }
  16878. token._timeElapsedQuery = this._createTimeQuery();
  16879. if (timerQuery.beginQueryEXT) {
  16880. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16881. }
  16882. else {
  16883. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16884. }
  16885. this._currentNonTimestampToken = token;
  16886. }
  16887. return token;
  16888. };
  16889. /**
  16890. * Ends a time query
  16891. * @param token defines the token used to measure the time span
  16892. * @returns the time spent (in ns)
  16893. */
  16894. Engine.prototype.endTimeQuery = function (token) {
  16895. var timerQuery = this._caps.timerQuery;
  16896. if (!timerQuery || !token) {
  16897. return -1;
  16898. }
  16899. if (this._caps.canUseTimestampForTimerQuery) {
  16900. if (!token._startTimeQuery) {
  16901. return -1;
  16902. }
  16903. if (!token._endTimeQuery) {
  16904. token._endTimeQuery = this._createTimeQuery();
  16905. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16906. }
  16907. }
  16908. else if (!token._timeElapsedQueryEnded) {
  16909. if (!token._timeElapsedQuery) {
  16910. return -1;
  16911. }
  16912. if (timerQuery.endQueryEXT) {
  16913. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16914. }
  16915. else {
  16916. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16917. }
  16918. token._timeElapsedQueryEnded = true;
  16919. }
  16920. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16921. var available = false;
  16922. if (token._endTimeQuery) {
  16923. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16924. }
  16925. else if (token._timeElapsedQuery) {
  16926. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16927. }
  16928. if (available && !disjoint) {
  16929. var result = 0;
  16930. if (this._caps.canUseTimestampForTimerQuery) {
  16931. if (!token._startTimeQuery || !token._endTimeQuery) {
  16932. return -1;
  16933. }
  16934. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16935. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16936. result = timeEnd - timeStart;
  16937. this._deleteTimeQuery(token._startTimeQuery);
  16938. this._deleteTimeQuery(token._endTimeQuery);
  16939. token._startTimeQuery = null;
  16940. token._endTimeQuery = null;
  16941. }
  16942. else {
  16943. if (!token._timeElapsedQuery) {
  16944. return -1;
  16945. }
  16946. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16947. this._deleteTimeQuery(token._timeElapsedQuery);
  16948. token._timeElapsedQuery = null;
  16949. token._timeElapsedQueryEnded = false;
  16950. this._currentNonTimestampToken = null;
  16951. }
  16952. return result;
  16953. }
  16954. return -1;
  16955. };
  16956. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16957. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16958. };
  16959. // Transform feedback
  16960. /**
  16961. * Creates a webGL transform feedback object
  16962. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16963. * @returns the webGL transform feedback object
  16964. */
  16965. Engine.prototype.createTransformFeedback = function () {
  16966. return this._gl.createTransformFeedback();
  16967. };
  16968. /**
  16969. * Delete a webGL transform feedback object
  16970. * @param value defines the webGL transform feedback object to delete
  16971. */
  16972. Engine.prototype.deleteTransformFeedback = function (value) {
  16973. this._gl.deleteTransformFeedback(value);
  16974. };
  16975. /**
  16976. * Bind a webGL transform feedback object to the webgl context
  16977. * @param value defines the webGL transform feedback object to bind
  16978. */
  16979. Engine.prototype.bindTransformFeedback = function (value) {
  16980. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16981. };
  16982. /**
  16983. * Begins a transform feedback operation
  16984. * @param usePoints defines if points or triangles must be used
  16985. */
  16986. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16987. if (usePoints === void 0) { usePoints = true; }
  16988. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16989. };
  16990. /**
  16991. * Ends a transform feedback operation
  16992. */
  16993. Engine.prototype.endTransformFeedback = function () {
  16994. this._gl.endTransformFeedback();
  16995. };
  16996. /**
  16997. * Specify the varyings to use with transform feedback
  16998. * @param program defines the associated webGL program
  16999. * @param value defines the list of strings representing the varying names
  17000. */
  17001. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17002. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17003. };
  17004. /**
  17005. * Bind a webGL buffer for a transform feedback operation
  17006. * @param value defines the webGL buffer to bind
  17007. */
  17008. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17009. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17010. };
  17011. /** @ignore */
  17012. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17013. var _this = this;
  17014. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17015. this._activeRequests.push(request);
  17016. request.onCompleteObservable.add(function (request) {
  17017. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17018. });
  17019. return request;
  17020. };
  17021. /** @ignore */
  17022. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17023. var _this = this;
  17024. return new Promise(function (resolve, reject) {
  17025. _this._loadFile(url, function (data) {
  17026. resolve(data);
  17027. }, undefined, database, useArrayBuffer, function (request, exception) {
  17028. reject(exception);
  17029. });
  17030. });
  17031. };
  17032. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17033. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17034. var onload = function (data) {
  17035. loadedFiles[index] = data;
  17036. loadedFiles._internalCount++;
  17037. if (loadedFiles._internalCount === 6) {
  17038. onfinish(loadedFiles);
  17039. }
  17040. };
  17041. var onerror = function (request, exception) {
  17042. if (onErrorCallBack && request) {
  17043. onErrorCallBack(request.status + " " + request.statusText, exception);
  17044. }
  17045. };
  17046. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17047. };
  17048. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17049. if (onError === void 0) { onError = null; }
  17050. var loadedFiles = [];
  17051. loadedFiles._internalCount = 0;
  17052. for (var index = 0; index < 6; index++) {
  17053. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17054. }
  17055. };
  17056. // Statics
  17057. /**
  17058. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17059. * @returns true if the engine can be created
  17060. * @ignoreNaming
  17061. */
  17062. Engine.isSupported = function () {
  17063. try {
  17064. var tempcanvas = document.createElement("canvas");
  17065. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17066. return gl != null && !!window.WebGLRenderingContext;
  17067. }
  17068. catch (e) {
  17069. return false;
  17070. }
  17071. };
  17072. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17073. Engine.ExceptionList = [
  17074. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17075. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17076. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17077. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17078. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17079. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17080. ];
  17081. /** Gets the list of created engines */
  17082. Engine.Instances = new Array();
  17083. // Const statics
  17084. Engine._ALPHA_DISABLE = 0;
  17085. Engine._ALPHA_ADD = 1;
  17086. Engine._ALPHA_COMBINE = 2;
  17087. Engine._ALPHA_SUBTRACT = 3;
  17088. Engine._ALPHA_MULTIPLY = 4;
  17089. Engine._ALPHA_MAXIMIZED = 5;
  17090. Engine._ALPHA_ONEONE = 6;
  17091. Engine._ALPHA_PREMULTIPLIED = 7;
  17092. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17093. Engine._ALPHA_INTERPOLATE = 9;
  17094. Engine._ALPHA_SCREENMODE = 10;
  17095. Engine._DELAYLOADSTATE_NONE = 0;
  17096. Engine._DELAYLOADSTATE_LOADED = 1;
  17097. Engine._DELAYLOADSTATE_LOADING = 2;
  17098. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17099. Engine._TEXTUREFORMAT_ALPHA = 0;
  17100. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17101. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17102. Engine._TEXTUREFORMAT_RGB = 4;
  17103. Engine._TEXTUREFORMAT_RGBA = 5;
  17104. Engine._TEXTUREFORMAT_R32F = 6;
  17105. Engine._TEXTUREFORMAT_RG32F = 7;
  17106. Engine._TEXTUREFORMAT_RGB32F = 8;
  17107. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17108. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17109. Engine._TEXTURETYPE_FLOAT = 1;
  17110. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17111. // Depht or Stencil test Constants.
  17112. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17113. 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.
  17114. 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.
  17115. 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.
  17116. 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.
  17117. 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.
  17118. 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.
  17119. 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.
  17120. // Stencil Actions Constants.
  17121. Engine._KEEP = 0x1E00;
  17122. Engine._REPLACE = 0x1E01;
  17123. Engine._INCR = 0x1E02;
  17124. Engine._DECR = 0x1E03;
  17125. Engine._INVERT = 0x150A;
  17126. Engine._INCR_WRAP = 0x8507;
  17127. Engine._DECR_WRAP = 0x8508;
  17128. // Texture rescaling mode
  17129. Engine._SCALEMODE_FLOOR = 1;
  17130. Engine._SCALEMODE_NEAREST = 2;
  17131. Engine._SCALEMODE_CEILING = 3;
  17132. // Updatable statics so stick with vars here
  17133. /**
  17134. * Gets or sets the epsilon value used by collision engine
  17135. */
  17136. Engine.CollisionsEpsilon = 0.001;
  17137. /**
  17138. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17139. */
  17140. Engine.CodeRepository = "src/";
  17141. /**
  17142. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17143. */
  17144. Engine.ShadersRepository = "src/Shaders/";
  17145. return Engine;
  17146. }());
  17147. BABYLON.Engine = Engine;
  17148. })(BABYLON || (BABYLON = {}));
  17149. //# sourceMappingURL=babylon.engine.js.map
  17150. var BABYLON;
  17151. (function (BABYLON) {
  17152. /**
  17153. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17154. */
  17155. var Node = /** @class */ (function () {
  17156. /**
  17157. * Creates a new Node
  17158. * @param {string} name - the name and id to be given to this node
  17159. * @param {BABYLON.Scene} the scene this node will be added to
  17160. */
  17161. function Node(name, scene) {
  17162. if (scene === void 0) { scene = null; }
  17163. /**
  17164. * Gets or sets a string used to store user defined state for the node
  17165. */
  17166. this.state = "";
  17167. /**
  17168. * Gets or sets an object used to store user defined information for the node
  17169. */
  17170. this.metadata = null;
  17171. /**
  17172. * Gets or sets a boolean used to define if the node must be serialized
  17173. */
  17174. this.doNotSerialize = false;
  17175. /** @ignore */
  17176. this._isDisposed = false;
  17177. /**
  17178. * Gets a list of Animations associated with the node
  17179. */
  17180. this.animations = new Array();
  17181. this._ranges = {};
  17182. this._isEnabled = true;
  17183. this._isReady = true;
  17184. /** @ignore */
  17185. this._currentRenderId = -1;
  17186. this._parentRenderId = -1;
  17187. this._childRenderId = -1;
  17188. this._animationPropertiesOverride = null;
  17189. /**
  17190. * An event triggered when the mesh is disposed
  17191. */
  17192. this.onDisposeObservable = new BABYLON.Observable();
  17193. // Behaviors
  17194. this._behaviors = new Array();
  17195. this.name = name;
  17196. this.id = name;
  17197. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17198. this.uniqueId = this._scene.getUniqueId();
  17199. this._initCache();
  17200. }
  17201. /**
  17202. * Gets a boolean indicating if the node has been disposed
  17203. * @returns true if the node was disposed
  17204. */
  17205. Node.prototype.isDisposed = function () {
  17206. return this._isDisposed;
  17207. };
  17208. Object.defineProperty(Node.prototype, "parent", {
  17209. get: function () {
  17210. return this._parentNode;
  17211. },
  17212. /**
  17213. * Gets or sets the parent of the node
  17214. */
  17215. set: function (parent) {
  17216. if (this._parentNode === parent) {
  17217. return;
  17218. }
  17219. // Remove self from list of children of parent
  17220. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17221. var index = this._parentNode._children.indexOf(this);
  17222. if (index !== -1) {
  17223. this._parentNode._children.splice(index, 1);
  17224. }
  17225. }
  17226. // Store new parent
  17227. this._parentNode = parent;
  17228. // Add as child to new parent
  17229. if (this._parentNode) {
  17230. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17231. this._parentNode._children = new Array();
  17232. }
  17233. this._parentNode._children.push(this);
  17234. }
  17235. },
  17236. enumerable: true,
  17237. configurable: true
  17238. });
  17239. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17240. /**
  17241. * Gets or sets the animation properties override
  17242. */
  17243. get: function () {
  17244. if (!this._animationPropertiesOverride) {
  17245. return this._scene.animationPropertiesOverride;
  17246. }
  17247. return this._animationPropertiesOverride;
  17248. },
  17249. set: function (value) {
  17250. this._animationPropertiesOverride = value;
  17251. },
  17252. enumerable: true,
  17253. configurable: true
  17254. });
  17255. /**
  17256. * Gets a string idenfifying the name of the class
  17257. * @returns "Node" string
  17258. */
  17259. Node.prototype.getClassName = function () {
  17260. return "Node";
  17261. };
  17262. Object.defineProperty(Node.prototype, "onDispose", {
  17263. /**
  17264. * Sets a callback that will be raised when the node will be disposed
  17265. */
  17266. set: function (callback) {
  17267. if (this._onDisposeObserver) {
  17268. this.onDisposeObservable.remove(this._onDisposeObserver);
  17269. }
  17270. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17271. },
  17272. enumerable: true,
  17273. configurable: true
  17274. });
  17275. /**
  17276. * Gets the scene of the node
  17277. * @returns a {BABYLON.Scene}
  17278. */
  17279. Node.prototype.getScene = function () {
  17280. return this._scene;
  17281. };
  17282. /**
  17283. * Gets the engine of the node
  17284. * @returns a {BABYLON.Engine}
  17285. */
  17286. Node.prototype.getEngine = function () {
  17287. return this._scene.getEngine();
  17288. };
  17289. /**
  17290. * Attach a behavior to the node
  17291. * @see http://doc.babylonjs.com/features/behaviour
  17292. * @param behavior defines the behavior to attach
  17293. * @returns the current Node
  17294. */
  17295. Node.prototype.addBehavior = function (behavior) {
  17296. var _this = this;
  17297. var index = this._behaviors.indexOf(behavior);
  17298. if (index !== -1) {
  17299. return this;
  17300. }
  17301. behavior.init();
  17302. if (this._scene.isLoading) {
  17303. // We defer the attach when the scene will be loaded
  17304. var observer = this._scene.onDataLoadedObservable.add(function () {
  17305. behavior.attach(_this);
  17306. setTimeout(function () {
  17307. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17308. _this._scene.onDataLoadedObservable.remove(observer);
  17309. }, 0);
  17310. });
  17311. }
  17312. else {
  17313. behavior.attach(this);
  17314. }
  17315. this._behaviors.push(behavior);
  17316. return this;
  17317. };
  17318. /**
  17319. * Remove an attached behavior
  17320. * @see http://doc.babylonjs.com/features/behaviour
  17321. * @param behavior defines the behavior to attach
  17322. * @returns the current Node
  17323. */
  17324. Node.prototype.removeBehavior = function (behavior) {
  17325. var index = this._behaviors.indexOf(behavior);
  17326. if (index === -1) {
  17327. return this;
  17328. }
  17329. this._behaviors[index].detach();
  17330. this._behaviors.splice(index, 1);
  17331. return this;
  17332. };
  17333. Object.defineProperty(Node.prototype, "behaviors", {
  17334. /**
  17335. * Gets the list of attached behaviors
  17336. * @see http://doc.babylonjs.com/features/behaviour
  17337. */
  17338. get: function () {
  17339. return this._behaviors;
  17340. },
  17341. enumerable: true,
  17342. configurable: true
  17343. });
  17344. /**
  17345. * Gets an attached behavior by name
  17346. * @param name defines the name of the behavior to look for
  17347. * @see http://doc.babylonjs.com/features/behaviour
  17348. * @returns null if behavior was not found else the requested behavior
  17349. */
  17350. Node.prototype.getBehaviorByName = function (name) {
  17351. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17352. var behavior = _a[_i];
  17353. if (behavior.name === name) {
  17354. return behavior;
  17355. }
  17356. }
  17357. return null;
  17358. };
  17359. /**
  17360. * Returns the world matrix of the node
  17361. * @returns a matrix containing the node's world matrix
  17362. */
  17363. Node.prototype.getWorldMatrix = function () {
  17364. return BABYLON.Matrix.Identity();
  17365. };
  17366. // override it in derived class if you add new variables to the cache
  17367. // and call the parent class method
  17368. /** @ignore */
  17369. Node.prototype._initCache = function () {
  17370. this._cache = {};
  17371. this._cache.parent = undefined;
  17372. };
  17373. /** @ignore */
  17374. Node.prototype.updateCache = function (force) {
  17375. if (!force && this.isSynchronized())
  17376. return;
  17377. this._cache.parent = this.parent;
  17378. this._updateCache();
  17379. };
  17380. // override it in derived class if you add new variables to the cache
  17381. // and call the parent class method if !ignoreParentClass
  17382. /** @ignore */
  17383. Node.prototype._updateCache = function (ignoreParentClass) {
  17384. };
  17385. // override it in derived class if you add new variables to the cache
  17386. /** @ignore */
  17387. Node.prototype._isSynchronized = function () {
  17388. return true;
  17389. };
  17390. /** @ignore */
  17391. Node.prototype._markSyncedWithParent = function () {
  17392. if (this.parent) {
  17393. this._parentRenderId = this.parent._childRenderId;
  17394. }
  17395. };
  17396. /** @ignore */
  17397. Node.prototype.isSynchronizedWithParent = function () {
  17398. if (!this.parent) {
  17399. return true;
  17400. }
  17401. if (this._parentRenderId !== this.parent._childRenderId) {
  17402. return false;
  17403. }
  17404. return this.parent.isSynchronized();
  17405. };
  17406. /** @ignore */
  17407. Node.prototype.isSynchronized = function (updateCache) {
  17408. var check = this.hasNewParent();
  17409. check = check || !this.isSynchronizedWithParent();
  17410. check = check || !this._isSynchronized();
  17411. if (updateCache)
  17412. this.updateCache(true);
  17413. return !check;
  17414. };
  17415. /** @ignore */
  17416. Node.prototype.hasNewParent = function (update) {
  17417. if (this._cache.parent === this.parent)
  17418. return false;
  17419. if (update)
  17420. this._cache.parent = this.parent;
  17421. return true;
  17422. };
  17423. /**
  17424. * Is this node ready to be used/rendered
  17425. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17426. * @return true if the node is ready
  17427. */
  17428. Node.prototype.isReady = function (completeCheck) {
  17429. if (completeCheck === void 0) { completeCheck = false; }
  17430. return this._isReady;
  17431. };
  17432. /**
  17433. * Is this node enabled?
  17434. * 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
  17435. * @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
  17436. * @return whether this node (and its parent) is enabled
  17437. */
  17438. Node.prototype.isEnabled = function (checkAncestors) {
  17439. if (checkAncestors === void 0) { checkAncestors = true; }
  17440. if (checkAncestors === false) {
  17441. return this._isEnabled;
  17442. }
  17443. if (this._isEnabled === false) {
  17444. return false;
  17445. }
  17446. if (this.parent !== undefined && this.parent !== null) {
  17447. return this.parent.isEnabled(checkAncestors);
  17448. }
  17449. return true;
  17450. };
  17451. /**
  17452. * Set the enabled state of this node
  17453. * @param value defines the new enabled state
  17454. */
  17455. Node.prototype.setEnabled = function (value) {
  17456. this._isEnabled = value;
  17457. };
  17458. /**
  17459. * Is this node a descendant of the given node?
  17460. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17461. * @param ancestor defines the parent node to inspect
  17462. * @returns a boolean indicating if this node is a descendant of the given node
  17463. */
  17464. Node.prototype.isDescendantOf = function (ancestor) {
  17465. if (this.parent) {
  17466. if (this.parent === ancestor) {
  17467. return true;
  17468. }
  17469. return this.parent.isDescendantOf(ancestor);
  17470. }
  17471. return false;
  17472. };
  17473. /** @ignore */
  17474. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17475. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17476. if (!this._children) {
  17477. return;
  17478. }
  17479. for (var index = 0; index < this._children.length; index++) {
  17480. var item = this._children[index];
  17481. if (!predicate || predicate(item)) {
  17482. results.push(item);
  17483. }
  17484. if (!directDescendantsOnly) {
  17485. item._getDescendants(results, false, predicate);
  17486. }
  17487. }
  17488. };
  17489. /**
  17490. * Will return all nodes that have this node as ascendant
  17491. * @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
  17492. * @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
  17493. * @return all children nodes of all types
  17494. */
  17495. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17496. var results = new Array();
  17497. this._getDescendants(results, directDescendantsOnly, predicate);
  17498. return results;
  17499. };
  17500. /**
  17501. * Get all child-meshes of this node
  17502. * @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
  17503. * @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
  17504. * @returns an array of {BABYLON.AbstractMesh}
  17505. */
  17506. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17507. var results = [];
  17508. this._getDescendants(results, directDescendantsOnly, function (node) {
  17509. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17510. });
  17511. return results;
  17512. };
  17513. /**
  17514. * Get all child-transformNodes of this node
  17515. * @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
  17516. * @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
  17517. * @returns an array of {BABYLON.TransformNode}
  17518. */
  17519. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17520. var results = [];
  17521. this._getDescendants(results, directDescendantsOnly, function (node) {
  17522. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17523. });
  17524. return results;
  17525. };
  17526. /**
  17527. * Get all direct children of this node
  17528. * @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
  17529. * @returns an array of {BABYLON.Node}
  17530. */
  17531. Node.prototype.getChildren = function (predicate) {
  17532. return this.getDescendants(true, predicate);
  17533. };
  17534. /** @ignore */
  17535. Node.prototype._setReady = function (state) {
  17536. if (state === this._isReady) {
  17537. return;
  17538. }
  17539. if (!state) {
  17540. this._isReady = false;
  17541. return;
  17542. }
  17543. if (this.onReady) {
  17544. this.onReady(this);
  17545. }
  17546. this._isReady = true;
  17547. };
  17548. /**
  17549. * Get an animation by name
  17550. * @param name defines the name of the animation to look for
  17551. * @returns null if not found else the requested animation
  17552. */
  17553. Node.prototype.getAnimationByName = function (name) {
  17554. for (var i = 0; i < this.animations.length; i++) {
  17555. var animation = this.animations[i];
  17556. if (animation.name === name) {
  17557. return animation;
  17558. }
  17559. }
  17560. return null;
  17561. };
  17562. /**
  17563. * Creates an animation range for this node
  17564. * @param name defines the name of the range
  17565. * @param from defines the starting key
  17566. * @param to defines the end key
  17567. */
  17568. Node.prototype.createAnimationRange = function (name, from, to) {
  17569. // check name not already in use
  17570. if (!this._ranges[name]) {
  17571. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17572. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17573. if (this.animations[i]) {
  17574. this.animations[i].createRange(name, from, to);
  17575. }
  17576. }
  17577. }
  17578. };
  17579. /**
  17580. * Delete a specific animation range
  17581. * @param name defines the name of the range to delete
  17582. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17583. */
  17584. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17585. if (deleteFrames === void 0) { deleteFrames = true; }
  17586. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17587. if (this.animations[i]) {
  17588. this.animations[i].deleteRange(name, deleteFrames);
  17589. }
  17590. }
  17591. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17592. };
  17593. /**
  17594. * Get an animation range by name
  17595. * @param name defines the name of the animation range to look for
  17596. * @returns null if not found else the requested animation range
  17597. */
  17598. Node.prototype.getAnimationRange = function (name) {
  17599. return this._ranges[name];
  17600. };
  17601. /**
  17602. * Will start the animation sequence
  17603. * @param name defines the range frames for animation sequence
  17604. * @param loop defines if the animation should loop (false by default)
  17605. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17606. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17607. * @returns the object created for this animation. If range does not exist, it will return null
  17608. */
  17609. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17610. var range = this.getAnimationRange(name);
  17611. if (!range) {
  17612. return null;
  17613. }
  17614. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17615. };
  17616. /**
  17617. * Serialize animation ranges into a JSON compatible object
  17618. * @returns serialization object
  17619. */
  17620. Node.prototype.serializeAnimationRanges = function () {
  17621. var serializationRanges = [];
  17622. for (var name in this._ranges) {
  17623. var localRange = this._ranges[name];
  17624. if (!localRange) {
  17625. continue;
  17626. }
  17627. var range = {};
  17628. range.name = name;
  17629. range.from = localRange.from;
  17630. range.to = localRange.to;
  17631. serializationRanges.push(range);
  17632. }
  17633. return serializationRanges;
  17634. };
  17635. /**
  17636. * Computes the world matrix of the node
  17637. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17638. * @returns the world matrix
  17639. */
  17640. Node.prototype.computeWorldMatrix = function (force) {
  17641. return BABYLON.Matrix.Identity();
  17642. };
  17643. /**
  17644. * Releases resources associated with this node.
  17645. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17646. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17647. */
  17648. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17649. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17650. if (!doNotRecurse) {
  17651. var nodes = this.getDescendants(true);
  17652. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17653. var node = nodes_1[_i];
  17654. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17655. }
  17656. }
  17657. else {
  17658. var transformNodes = this.getChildTransformNodes(true);
  17659. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17660. var transformNode = transformNodes_1[_a];
  17661. transformNode.parent = null;
  17662. transformNode.computeWorldMatrix(true);
  17663. }
  17664. }
  17665. this.parent = null;
  17666. // Callback
  17667. this.onDisposeObservable.notifyObservers(this);
  17668. this.onDisposeObservable.clear();
  17669. // Behaviors
  17670. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17671. var behavior = _c[_b];
  17672. behavior.detach();
  17673. }
  17674. this._behaviors = [];
  17675. this._isDisposed = true;
  17676. };
  17677. /**
  17678. * Parse animation range data from a serialization object and store them into a given node
  17679. * @param node defines where to store the animation ranges
  17680. * @param parsedNode defines the serialization object to read data from
  17681. * @param scene defines the hosting scene
  17682. */
  17683. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17684. if (parsedNode.ranges) {
  17685. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17686. var data = parsedNode.ranges[index];
  17687. node.createAnimationRange(data.name, data.from, data.to);
  17688. }
  17689. }
  17690. };
  17691. __decorate([
  17692. BABYLON.serialize()
  17693. ], Node.prototype, "name", void 0);
  17694. __decorate([
  17695. BABYLON.serialize()
  17696. ], Node.prototype, "id", void 0);
  17697. __decorate([
  17698. BABYLON.serialize()
  17699. ], Node.prototype, "uniqueId", void 0);
  17700. __decorate([
  17701. BABYLON.serialize()
  17702. ], Node.prototype, "state", void 0);
  17703. __decorate([
  17704. BABYLON.serialize()
  17705. ], Node.prototype, "metadata", void 0);
  17706. return Node;
  17707. }());
  17708. BABYLON.Node = Node;
  17709. })(BABYLON || (BABYLON = {}));
  17710. //# sourceMappingURL=babylon.node.js.map
  17711. var BABYLON;
  17712. (function (BABYLON) {
  17713. var BoundingSphere = /** @class */ (function () {
  17714. /**
  17715. * Creates a new bounding sphere
  17716. * @param min defines the minimum vector (in local space)
  17717. * @param max defines the maximum vector (in local space)
  17718. */
  17719. function BoundingSphere(min, max) {
  17720. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17721. this.reConstruct(min, max);
  17722. }
  17723. /**
  17724. * Recreates the entire bounding sphere from scratch
  17725. * @param min defines the new minimum vector (in local space)
  17726. * @param max defines the new maximum vector (in local space)
  17727. */
  17728. BoundingSphere.prototype.reConstruct = function (min, max) {
  17729. this.minimum = min.clone();
  17730. this.maximum = max.clone();
  17731. var distance = BABYLON.Vector3.Distance(min, max);
  17732. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17733. this.radius = distance * 0.5;
  17734. this.centerWorld = BABYLON.Vector3.Zero();
  17735. this._update(BABYLON.Matrix.Identity());
  17736. };
  17737. // Methods
  17738. BoundingSphere.prototype._update = function (world) {
  17739. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17740. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17741. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17742. };
  17743. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17744. for (var i = 0; i < 6; i++) {
  17745. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17746. return false;
  17747. }
  17748. return true;
  17749. };
  17750. BoundingSphere.prototype.intersectsPoint = function (point) {
  17751. var x = this.centerWorld.x - point.x;
  17752. var y = this.centerWorld.y - point.y;
  17753. var z = this.centerWorld.z - point.z;
  17754. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17755. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17756. return false;
  17757. return true;
  17758. };
  17759. // Statics
  17760. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17761. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17762. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17763. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17764. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17765. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17766. return false;
  17767. return true;
  17768. };
  17769. return BoundingSphere;
  17770. }());
  17771. BABYLON.BoundingSphere = BoundingSphere;
  17772. })(BABYLON || (BABYLON = {}));
  17773. //# sourceMappingURL=babylon.boundingSphere.js.map
  17774. var BABYLON;
  17775. (function (BABYLON) {
  17776. var BoundingBox = /** @class */ (function () {
  17777. /**
  17778. * Creates a new bounding box
  17779. * @param min defines the minimum vector (in local space)
  17780. * @param max defines the maximum vector (in local space)
  17781. */
  17782. function BoundingBox(min, max) {
  17783. this.vectorsWorld = new Array();
  17784. this.reConstruct(min, max);
  17785. }
  17786. // Methods
  17787. /**
  17788. * Recreates the entire bounding box from scratch
  17789. * @param min defines the new minimum vector (in local space)
  17790. * @param max defines the new maximum vector (in local space)
  17791. */
  17792. BoundingBox.prototype.reConstruct = function (min, max) {
  17793. this.minimum = min.clone();
  17794. this.maximum = max.clone();
  17795. // Bounding vectors
  17796. this.vectors = new Array();
  17797. this.vectors.push(this.minimum.clone());
  17798. this.vectors.push(this.maximum.clone());
  17799. this.vectors.push(this.minimum.clone());
  17800. this.vectors[2].x = this.maximum.x;
  17801. this.vectors.push(this.minimum.clone());
  17802. this.vectors[3].y = this.maximum.y;
  17803. this.vectors.push(this.minimum.clone());
  17804. this.vectors[4].z = this.maximum.z;
  17805. this.vectors.push(this.maximum.clone());
  17806. this.vectors[5].z = this.minimum.z;
  17807. this.vectors.push(this.maximum.clone());
  17808. this.vectors[6].x = this.minimum.x;
  17809. this.vectors.push(this.maximum.clone());
  17810. this.vectors[7].y = this.minimum.y;
  17811. // OBB
  17812. this.center = this.maximum.add(this.minimum).scale(0.5);
  17813. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17814. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17815. // World
  17816. for (var index = 0; index < this.vectors.length; index++) {
  17817. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17818. }
  17819. this.minimumWorld = BABYLON.Vector3.Zero();
  17820. this.maximumWorld = BABYLON.Vector3.Zero();
  17821. this.centerWorld = BABYLON.Vector3.Zero();
  17822. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17823. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17824. };
  17825. BoundingBox.prototype.getWorldMatrix = function () {
  17826. return this._worldMatrix;
  17827. };
  17828. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17829. this._worldMatrix.copyFrom(matrix);
  17830. return this;
  17831. };
  17832. BoundingBox.prototype._update = function (world) {
  17833. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17834. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17835. for (var index = 0; index < this.vectors.length; index++) {
  17836. var v = this.vectorsWorld[index];
  17837. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17838. if (v.x < this.minimumWorld.x)
  17839. this.minimumWorld.x = v.x;
  17840. if (v.y < this.minimumWorld.y)
  17841. this.minimumWorld.y = v.y;
  17842. if (v.z < this.minimumWorld.z)
  17843. this.minimumWorld.z = v.z;
  17844. if (v.x > this.maximumWorld.x)
  17845. this.maximumWorld.x = v.x;
  17846. if (v.y > this.maximumWorld.y)
  17847. this.maximumWorld.y = v.y;
  17848. if (v.z > this.maximumWorld.z)
  17849. this.maximumWorld.z = v.z;
  17850. }
  17851. // Extend
  17852. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17853. this.extendSizeWorld.scaleInPlace(0.5);
  17854. // OBB
  17855. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17856. this.centerWorld.scaleInPlace(0.5);
  17857. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17858. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17859. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17860. this._worldMatrix = world;
  17861. };
  17862. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17863. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17864. };
  17865. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17866. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17867. };
  17868. BoundingBox.prototype.intersectsPoint = function (point) {
  17869. var delta = -BABYLON.Epsilon;
  17870. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17871. return false;
  17872. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17873. return false;
  17874. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17875. return false;
  17876. return true;
  17877. };
  17878. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17879. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17880. };
  17881. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17882. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17883. return false;
  17884. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17885. return false;
  17886. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17887. return false;
  17888. return true;
  17889. };
  17890. // Statics
  17891. BoundingBox.Intersects = function (box0, box1) {
  17892. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17893. return false;
  17894. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17895. return false;
  17896. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17897. return false;
  17898. return true;
  17899. };
  17900. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17901. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17902. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17903. return (num <= (sphereRadius * sphereRadius));
  17904. };
  17905. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17906. for (var p = 0; p < 6; p++) {
  17907. for (var i = 0; i < 8; i++) {
  17908. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17909. return false;
  17910. }
  17911. }
  17912. }
  17913. return true;
  17914. };
  17915. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17916. for (var p = 0; p < 6; p++) {
  17917. var inCount = 8;
  17918. for (var i = 0; i < 8; i++) {
  17919. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17920. --inCount;
  17921. }
  17922. else {
  17923. break;
  17924. }
  17925. }
  17926. if (inCount === 0)
  17927. return false;
  17928. }
  17929. return true;
  17930. };
  17931. return BoundingBox;
  17932. }());
  17933. BABYLON.BoundingBox = BoundingBox;
  17934. })(BABYLON || (BABYLON = {}));
  17935. //# sourceMappingURL=babylon.boundingBox.js.map
  17936. var BABYLON;
  17937. (function (BABYLON) {
  17938. var computeBoxExtents = function (axis, box) {
  17939. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17940. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17941. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17942. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17943. var r = r0 + r1 + r2;
  17944. return {
  17945. min: p - r,
  17946. max: p + r
  17947. };
  17948. };
  17949. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17950. var axisOverlap = function (axis, box0, box1) {
  17951. var result0 = computeBoxExtents(axis, box0);
  17952. var result1 = computeBoxExtents(axis, box1);
  17953. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17954. };
  17955. var BoundingInfo = /** @class */ (function () {
  17956. function BoundingInfo(minimum, maximum) {
  17957. this.minimum = minimum;
  17958. this.maximum = maximum;
  17959. this._isLocked = false;
  17960. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17961. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17962. }
  17963. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17964. get: function () {
  17965. return this._isLocked;
  17966. },
  17967. set: function (value) {
  17968. this._isLocked = value;
  17969. },
  17970. enumerable: true,
  17971. configurable: true
  17972. });
  17973. // Methods
  17974. BoundingInfo.prototype.update = function (world) {
  17975. if (this._isLocked) {
  17976. return;
  17977. }
  17978. this.boundingBox._update(world);
  17979. this.boundingSphere._update(world);
  17980. };
  17981. /**
  17982. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17983. * @param center New center of the bounding info
  17984. * @param extend New extend of the bounding info
  17985. */
  17986. BoundingInfo.prototype.centerOn = function (center, extend) {
  17987. this.minimum = center.subtract(extend);
  17988. this.maximum = center.add(extend);
  17989. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17990. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17991. return this;
  17992. };
  17993. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17994. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17995. return false;
  17996. return this.boundingBox.isInFrustum(frustumPlanes);
  17997. };
  17998. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17999. /**
  18000. * Gets the world distance between the min and max points of the bounding box
  18001. */
  18002. get: function () {
  18003. var boundingBox = this.boundingBox;
  18004. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18005. return size.length();
  18006. },
  18007. enumerable: true,
  18008. configurable: true
  18009. });
  18010. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18011. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18012. };
  18013. BoundingInfo.prototype._checkCollision = function (collider) {
  18014. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18015. };
  18016. BoundingInfo.prototype.intersectsPoint = function (point) {
  18017. if (!this.boundingSphere.centerWorld) {
  18018. return false;
  18019. }
  18020. if (!this.boundingSphere.intersectsPoint(point)) {
  18021. return false;
  18022. }
  18023. if (!this.boundingBox.intersectsPoint(point)) {
  18024. return false;
  18025. }
  18026. return true;
  18027. };
  18028. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18029. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18030. return false;
  18031. }
  18032. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18033. return false;
  18034. }
  18035. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18036. return false;
  18037. }
  18038. if (!precise) {
  18039. return true;
  18040. }
  18041. var box0 = this.boundingBox;
  18042. var box1 = boundingInfo.boundingBox;
  18043. if (!axisOverlap(box0.directions[0], box0, box1))
  18044. return false;
  18045. if (!axisOverlap(box0.directions[1], box0, box1))
  18046. return false;
  18047. if (!axisOverlap(box0.directions[2], box0, box1))
  18048. return false;
  18049. if (!axisOverlap(box1.directions[0], box0, box1))
  18050. return false;
  18051. if (!axisOverlap(box1.directions[1], box0, box1))
  18052. return false;
  18053. if (!axisOverlap(box1.directions[2], box0, box1))
  18054. return false;
  18055. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18056. return false;
  18057. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18058. return false;
  18059. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18060. return false;
  18061. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18062. return false;
  18063. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18064. return false;
  18065. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18066. return false;
  18067. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18068. return false;
  18069. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18070. return false;
  18071. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18072. return false;
  18073. return true;
  18074. };
  18075. return BoundingInfo;
  18076. }());
  18077. BABYLON.BoundingInfo = BoundingInfo;
  18078. })(BABYLON || (BABYLON = {}));
  18079. //# sourceMappingURL=babylon.boundingInfo.js.map
  18080. var BABYLON;
  18081. (function (BABYLON) {
  18082. var TransformNode = /** @class */ (function (_super) {
  18083. __extends(TransformNode, _super);
  18084. function TransformNode(name, scene, isPure) {
  18085. if (scene === void 0) { scene = null; }
  18086. if (isPure === void 0) { isPure = true; }
  18087. var _this = _super.call(this, name, scene) || this;
  18088. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18089. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18090. _this._up = new BABYLON.Vector3(0, 1, 0);
  18091. _this._right = new BABYLON.Vector3(1, 0, 0);
  18092. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18093. // Properties
  18094. _this._rotation = BABYLON.Vector3.Zero();
  18095. _this._scaling = BABYLON.Vector3.One();
  18096. _this._isDirty = false;
  18097. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18098. _this.scalingDeterminant = 1;
  18099. _this.infiniteDistance = false;
  18100. _this.position = BABYLON.Vector3.Zero();
  18101. _this._localWorld = BABYLON.Matrix.Zero();
  18102. _this._worldMatrix = BABYLON.Matrix.Zero();
  18103. _this._worldMatrixDeterminant = 0;
  18104. _this._absolutePosition = BABYLON.Vector3.Zero();
  18105. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18106. _this._postMultiplyPivotMatrix = false;
  18107. _this._isWorldMatrixFrozen = false;
  18108. /**
  18109. * An event triggered after the world matrix is updated
  18110. */
  18111. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18112. _this._nonUniformScaling = false;
  18113. if (isPure) {
  18114. _this.getScene().addTransformNode(_this);
  18115. }
  18116. return _this;
  18117. }
  18118. /**
  18119. * Gets a string idenfifying the name of the class
  18120. * @returns "TransformNode" string
  18121. */
  18122. TransformNode.prototype.getClassName = function () {
  18123. return "TransformNode";
  18124. };
  18125. Object.defineProperty(TransformNode.prototype, "rotation", {
  18126. /**
  18127. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18128. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18129. * Default : (0.0, 0.0, 0.0)
  18130. */
  18131. get: function () {
  18132. return this._rotation;
  18133. },
  18134. set: function (newRotation) {
  18135. this._rotation = newRotation;
  18136. },
  18137. enumerable: true,
  18138. configurable: true
  18139. });
  18140. Object.defineProperty(TransformNode.prototype, "scaling", {
  18141. /**
  18142. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18143. * Default : (1.0, 1.0, 1.0)
  18144. */
  18145. get: function () {
  18146. return this._scaling;
  18147. },
  18148. /**
  18149. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18150. * Default : (1.0, 1.0, 1.0)
  18151. */
  18152. set: function (newScaling) {
  18153. this._scaling = newScaling;
  18154. },
  18155. enumerable: true,
  18156. configurable: true
  18157. });
  18158. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18159. /**
  18160. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18161. * It's null by default.
  18162. * 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)
  18163. */
  18164. get: function () {
  18165. return this._rotationQuaternion;
  18166. },
  18167. set: function (quaternion) {
  18168. this._rotationQuaternion = quaternion;
  18169. //reset the rotation vector.
  18170. if (quaternion && this.rotation.length()) {
  18171. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18172. }
  18173. },
  18174. enumerable: true,
  18175. configurable: true
  18176. });
  18177. Object.defineProperty(TransformNode.prototype, "forward", {
  18178. /**
  18179. * The forward direction of that transform in world space.
  18180. */
  18181. get: function () {
  18182. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18183. },
  18184. enumerable: true,
  18185. configurable: true
  18186. });
  18187. Object.defineProperty(TransformNode.prototype, "up", {
  18188. /**
  18189. * The up direction of that transform in world space.
  18190. */
  18191. get: function () {
  18192. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18193. },
  18194. enumerable: true,
  18195. configurable: true
  18196. });
  18197. Object.defineProperty(TransformNode.prototype, "right", {
  18198. /**
  18199. * The right direction of that transform in world space.
  18200. */
  18201. get: function () {
  18202. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18203. },
  18204. enumerable: true,
  18205. configurable: true
  18206. });
  18207. /**
  18208. * Returns the latest update of the World matrix
  18209. * Returns a Matrix.
  18210. */
  18211. TransformNode.prototype.getWorldMatrix = function () {
  18212. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18213. this.computeWorldMatrix();
  18214. }
  18215. return this._worldMatrix;
  18216. };
  18217. /**
  18218. * Returns the latest update of the World matrix determinant.
  18219. */
  18220. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18221. return this._worldMatrixDeterminant;
  18222. };
  18223. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18224. /**
  18225. * Returns directly the latest state of the mesh World matrix.
  18226. * A Matrix is returned.
  18227. */
  18228. get: function () {
  18229. return this._worldMatrix;
  18230. },
  18231. enumerable: true,
  18232. configurable: true
  18233. });
  18234. /**
  18235. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18236. * Returns the TransformNode.
  18237. */
  18238. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18239. this._poseMatrix.copyFrom(matrix);
  18240. return this;
  18241. };
  18242. /**
  18243. * Returns the mesh Pose matrix.
  18244. * Returned object : Matrix
  18245. */
  18246. TransformNode.prototype.getPoseMatrix = function () {
  18247. return this._poseMatrix;
  18248. };
  18249. TransformNode.prototype._isSynchronized = function () {
  18250. if (this._isDirty) {
  18251. return false;
  18252. }
  18253. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18254. return false;
  18255. if (this._cache.pivotMatrixUpdated) {
  18256. return false;
  18257. }
  18258. if (this.infiniteDistance) {
  18259. return false;
  18260. }
  18261. if (!this._cache.position.equals(this.position))
  18262. return false;
  18263. if (this.rotationQuaternion) {
  18264. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18265. return false;
  18266. }
  18267. if (!this._cache.rotation.equals(this.rotation))
  18268. return false;
  18269. if (!this._cache.scaling.equals(this.scaling))
  18270. return false;
  18271. return true;
  18272. };
  18273. TransformNode.prototype._initCache = function () {
  18274. _super.prototype._initCache.call(this);
  18275. this._cache.localMatrixUpdated = false;
  18276. this._cache.position = BABYLON.Vector3.Zero();
  18277. this._cache.scaling = BABYLON.Vector3.Zero();
  18278. this._cache.rotation = BABYLON.Vector3.Zero();
  18279. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18280. this._cache.billboardMode = -1;
  18281. };
  18282. TransformNode.prototype.markAsDirty = function (property) {
  18283. if (property === "rotation") {
  18284. this.rotationQuaternion = null;
  18285. }
  18286. this._currentRenderId = Number.MAX_VALUE;
  18287. this._isDirty = true;
  18288. return this;
  18289. };
  18290. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18291. /**
  18292. * Returns the current mesh absolute position.
  18293. * Retuns a Vector3.
  18294. */
  18295. get: function () {
  18296. return this._absolutePosition;
  18297. },
  18298. enumerable: true,
  18299. configurable: true
  18300. });
  18301. /**
  18302. * Sets a new matrix to apply before all other transformation
  18303. * @param matrix defines the transform matrix
  18304. * @returns the current TransformNode
  18305. */
  18306. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18307. return this.setPivotMatrix(matrix, false);
  18308. };
  18309. /**
  18310. * Sets a new pivot matrix to the current node
  18311. * @param matrix defines the new pivot matrix to use
  18312. * @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
  18313. * @returns the current TransformNode
  18314. */
  18315. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18316. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18317. this._pivotMatrix = matrix.clone();
  18318. this._cache.pivotMatrixUpdated = true;
  18319. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18320. if (this._postMultiplyPivotMatrix) {
  18321. if (!this._pivotMatrixInverse) {
  18322. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18323. }
  18324. else {
  18325. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18326. }
  18327. }
  18328. return this;
  18329. };
  18330. /**
  18331. * Returns the mesh pivot matrix.
  18332. * Default : Identity.
  18333. * A Matrix is returned.
  18334. */
  18335. TransformNode.prototype.getPivotMatrix = function () {
  18336. return this._pivotMatrix;
  18337. };
  18338. /**
  18339. * Prevents the World matrix to be computed any longer.
  18340. * Returns the TransformNode.
  18341. */
  18342. TransformNode.prototype.freezeWorldMatrix = function () {
  18343. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18344. this.computeWorldMatrix(true);
  18345. this._isWorldMatrixFrozen = true;
  18346. return this;
  18347. };
  18348. /**
  18349. * Allows back the World matrix computation.
  18350. * Returns the TransformNode.
  18351. */
  18352. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18353. this._isWorldMatrixFrozen = false;
  18354. this.computeWorldMatrix(true);
  18355. return this;
  18356. };
  18357. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18358. /**
  18359. * True if the World matrix has been frozen.
  18360. * Returns a boolean.
  18361. */
  18362. get: function () {
  18363. return this._isWorldMatrixFrozen;
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. /**
  18369. * Retuns the mesh absolute position in the World.
  18370. * Returns a Vector3.
  18371. */
  18372. TransformNode.prototype.getAbsolutePosition = function () {
  18373. this.computeWorldMatrix();
  18374. return this._absolutePosition;
  18375. };
  18376. /**
  18377. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18378. * Returns the TransformNode.
  18379. */
  18380. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18381. if (!absolutePosition) {
  18382. return this;
  18383. }
  18384. var absolutePositionX;
  18385. var absolutePositionY;
  18386. var absolutePositionZ;
  18387. if (absolutePosition.x === undefined) {
  18388. if (arguments.length < 3) {
  18389. return this;
  18390. }
  18391. absolutePositionX = arguments[0];
  18392. absolutePositionY = arguments[1];
  18393. absolutePositionZ = arguments[2];
  18394. }
  18395. else {
  18396. absolutePositionX = absolutePosition.x;
  18397. absolutePositionY = absolutePosition.y;
  18398. absolutePositionZ = absolutePosition.z;
  18399. }
  18400. if (this.parent) {
  18401. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18402. invertParentWorldMatrix.invert();
  18403. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18404. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18405. }
  18406. else {
  18407. this.position.x = absolutePositionX;
  18408. this.position.y = absolutePositionY;
  18409. this.position.z = absolutePositionZ;
  18410. }
  18411. return this;
  18412. };
  18413. /**
  18414. * Sets the mesh position in its local space.
  18415. * Returns the TransformNode.
  18416. */
  18417. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18418. this.computeWorldMatrix();
  18419. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18420. return this;
  18421. };
  18422. /**
  18423. * Returns the mesh position in the local space from the current World matrix values.
  18424. * Returns a new Vector3.
  18425. */
  18426. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18427. this.computeWorldMatrix();
  18428. var invLocalWorldMatrix = this._localWorld.clone();
  18429. invLocalWorldMatrix.invert();
  18430. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18431. };
  18432. /**
  18433. * Translates the mesh along the passed Vector3 in its local space.
  18434. * Returns the TransformNode.
  18435. */
  18436. TransformNode.prototype.locallyTranslate = function (vector3) {
  18437. this.computeWorldMatrix(true);
  18438. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18439. return this;
  18440. };
  18441. /**
  18442. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18443. * @param targetPoint the position (must be in same space as current mesh) to look at
  18444. * @param yawCor optional yaw (y-axis) correction in radians
  18445. * @param pitchCor optional pitch (x-axis) correction in radians
  18446. * @param rollCor optional roll (z-axis) correction in radians
  18447. * @param space the choosen space of the target
  18448. * @returns the TransformNode.
  18449. */
  18450. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18451. if (yawCor === void 0) { yawCor = 0; }
  18452. if (pitchCor === void 0) { pitchCor = 0; }
  18453. if (rollCor === void 0) { rollCor = 0; }
  18454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18455. var dv = TransformNode._lookAtVectorCache;
  18456. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18457. targetPoint.subtractToRef(pos, dv);
  18458. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18459. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18460. var pitch = Math.atan2(dv.y, len);
  18461. if (this.rotationQuaternion) {
  18462. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18463. }
  18464. else {
  18465. this.rotation.x = pitch + pitchCor;
  18466. this.rotation.y = yaw + yawCor;
  18467. this.rotation.z = rollCor;
  18468. }
  18469. return this;
  18470. };
  18471. /**
  18472. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18473. * This Vector3 is expressed in the World space.
  18474. */
  18475. TransformNode.prototype.getDirection = function (localAxis) {
  18476. var result = BABYLON.Vector3.Zero();
  18477. this.getDirectionToRef(localAxis, result);
  18478. return result;
  18479. };
  18480. /**
  18481. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18482. * localAxis is expressed in the mesh local space.
  18483. * result is computed in the Wordl space from the mesh World matrix.
  18484. * Returns the TransformNode.
  18485. */
  18486. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18487. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18488. return this;
  18489. };
  18490. /**
  18491. * Sets a new pivot point to the current node
  18492. * @param point defines the new pivot point to use
  18493. * @param space defines if the point is in world or local space (local by default)
  18494. * @returns the current TransformNode
  18495. */
  18496. TransformNode.prototype.setPivotPoint = function (point, space) {
  18497. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18498. if (this.getScene().getRenderId() == 0) {
  18499. this.computeWorldMatrix(true);
  18500. }
  18501. var wm = this.getWorldMatrix();
  18502. if (space == BABYLON.Space.WORLD) {
  18503. var tmat = BABYLON.Tmp.Matrix[0];
  18504. wm.invertToRef(tmat);
  18505. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18506. }
  18507. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18508. };
  18509. /**
  18510. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18511. */
  18512. TransformNode.prototype.getPivotPoint = function () {
  18513. var point = BABYLON.Vector3.Zero();
  18514. this.getPivotPointToRef(point);
  18515. return point;
  18516. };
  18517. /**
  18518. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18519. * Returns the TransformNode.
  18520. */
  18521. TransformNode.prototype.getPivotPointToRef = function (result) {
  18522. result.x = -this._pivotMatrix.m[12];
  18523. result.y = -this._pivotMatrix.m[13];
  18524. result.z = -this._pivotMatrix.m[14];
  18525. return this;
  18526. };
  18527. /**
  18528. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18529. */
  18530. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18531. var point = BABYLON.Vector3.Zero();
  18532. this.getAbsolutePivotPointToRef(point);
  18533. return point;
  18534. };
  18535. /**
  18536. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18537. * Returns the TransformNode.
  18538. */
  18539. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18540. result.x = this._pivotMatrix.m[12];
  18541. result.y = this._pivotMatrix.m[13];
  18542. result.z = this._pivotMatrix.m[14];
  18543. this.getPivotPointToRef(result);
  18544. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18545. return this;
  18546. };
  18547. /**
  18548. * Defines the passed node as the parent of the current node.
  18549. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18550. * Returns the TransformNode.
  18551. */
  18552. TransformNode.prototype.setParent = function (node) {
  18553. if (node === null) {
  18554. var rotation = BABYLON.Tmp.Quaternion[0];
  18555. var position = BABYLON.Tmp.Vector3[0];
  18556. var scale = BABYLON.Tmp.Vector3[1];
  18557. if (this.parent && this.parent.computeWorldMatrix) {
  18558. this.parent.computeWorldMatrix(true);
  18559. }
  18560. this.computeWorldMatrix(true);
  18561. this.getWorldMatrix().decompose(scale, rotation, position);
  18562. if (this.rotationQuaternion) {
  18563. this.rotationQuaternion.copyFrom(rotation);
  18564. }
  18565. else {
  18566. rotation.toEulerAnglesToRef(this.rotation);
  18567. }
  18568. this.scaling.x = scale.x;
  18569. this.scaling.y = scale.y;
  18570. this.scaling.z = scale.z;
  18571. this.position.x = position.x;
  18572. this.position.y = position.y;
  18573. this.position.z = position.z;
  18574. }
  18575. else {
  18576. var rotation = BABYLON.Tmp.Quaternion[0];
  18577. var position = BABYLON.Tmp.Vector3[0];
  18578. var scale = BABYLON.Tmp.Vector3[1];
  18579. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18580. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18581. this.computeWorldMatrix(true);
  18582. node.computeWorldMatrix(true);
  18583. node.getWorldMatrix().invertToRef(invParentMatrix);
  18584. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18585. diffMatrix.decompose(scale, rotation, position);
  18586. if (this.rotationQuaternion) {
  18587. this.rotationQuaternion.copyFrom(rotation);
  18588. }
  18589. else {
  18590. rotation.toEulerAnglesToRef(this.rotation);
  18591. }
  18592. this.position.x = position.x;
  18593. this.position.y = position.y;
  18594. this.position.z = position.z;
  18595. this.scaling.x = scale.x;
  18596. this.scaling.y = scale.y;
  18597. this.scaling.z = scale.z;
  18598. }
  18599. this.parent = node;
  18600. return this;
  18601. };
  18602. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18603. get: function () {
  18604. return this._nonUniformScaling;
  18605. },
  18606. enumerable: true,
  18607. configurable: true
  18608. });
  18609. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18610. if (this._nonUniformScaling === value) {
  18611. return false;
  18612. }
  18613. this._nonUniformScaling = true;
  18614. return true;
  18615. };
  18616. /**
  18617. * Attach the current TransformNode to another TransformNode associated with a bone
  18618. * @param bone Bone affecting the TransformNode
  18619. * @param affectedTransformNode TransformNode associated with the bone
  18620. */
  18621. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18622. this._transformToBoneReferal = affectedTransformNode;
  18623. this.parent = bone;
  18624. if (bone.getWorldMatrix().determinant() < 0) {
  18625. this.scalingDeterminant *= -1;
  18626. }
  18627. return this;
  18628. };
  18629. TransformNode.prototype.detachFromBone = function () {
  18630. if (!this.parent) {
  18631. return this;
  18632. }
  18633. if (this.parent.getWorldMatrix().determinant() < 0) {
  18634. this.scalingDeterminant *= -1;
  18635. }
  18636. this._transformToBoneReferal = null;
  18637. this.parent = null;
  18638. return this;
  18639. };
  18640. /**
  18641. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18642. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18643. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18644. * The passed axis is also normalized.
  18645. * Returns the TransformNode.
  18646. */
  18647. TransformNode.prototype.rotate = function (axis, amount, space) {
  18648. axis.normalize();
  18649. if (!this.rotationQuaternion) {
  18650. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18651. this.rotation = BABYLON.Vector3.Zero();
  18652. }
  18653. var rotationQuaternion;
  18654. if (!space || space === BABYLON.Space.LOCAL) {
  18655. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18656. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18657. }
  18658. else {
  18659. if (this.parent) {
  18660. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18661. invertParentWorldMatrix.invert();
  18662. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18663. }
  18664. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18665. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18666. }
  18667. return this;
  18668. };
  18669. /**
  18670. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18671. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18672. * The passed axis is also normalized.
  18673. * Returns the TransformNode.
  18674. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18675. */
  18676. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18677. axis.normalize();
  18678. if (!this.rotationQuaternion) {
  18679. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18680. this.rotation.copyFromFloats(0, 0, 0);
  18681. }
  18682. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18683. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18684. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18685. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18686. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18687. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18688. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18689. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18690. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18691. return this;
  18692. };
  18693. /**
  18694. * Translates the mesh along the axis vector for the passed distance in the given space.
  18695. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18696. * Returns the TransformNode.
  18697. */
  18698. TransformNode.prototype.translate = function (axis, distance, space) {
  18699. var displacementVector = axis.scale(distance);
  18700. if (!space || space === BABYLON.Space.LOCAL) {
  18701. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18702. this.setPositionWithLocalVector(tempV3);
  18703. }
  18704. else {
  18705. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18706. }
  18707. return this;
  18708. };
  18709. /**
  18710. * Adds a rotation step to the mesh current rotation.
  18711. * x, y, z are Euler angles expressed in radians.
  18712. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18713. * This means this rotation is made in the mesh local space only.
  18714. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18715. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18716. * ```javascript
  18717. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18718. * ```
  18719. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18720. * 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.
  18721. * Returns the TransformNode.
  18722. */
  18723. TransformNode.prototype.addRotation = function (x, y, z) {
  18724. var rotationQuaternion;
  18725. if (this.rotationQuaternion) {
  18726. rotationQuaternion = this.rotationQuaternion;
  18727. }
  18728. else {
  18729. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18730. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18731. }
  18732. var accumulation = BABYLON.Tmp.Quaternion[0];
  18733. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18734. rotationQuaternion.multiplyInPlace(accumulation);
  18735. if (!this.rotationQuaternion) {
  18736. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18737. }
  18738. return this;
  18739. };
  18740. /**
  18741. * Computes the mesh World matrix and returns it.
  18742. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18743. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18744. * If the parameter `force`is set to `true`, the actual computation is done.
  18745. * Returns the mesh World Matrix.
  18746. */
  18747. TransformNode.prototype.computeWorldMatrix = function (force) {
  18748. if (this._isWorldMatrixFrozen) {
  18749. return this._worldMatrix;
  18750. }
  18751. if (!force && this.isSynchronized(true)) {
  18752. this._currentRenderId = this.getScene().getRenderId();
  18753. return this._worldMatrix;
  18754. }
  18755. this._cache.position.copyFrom(this.position);
  18756. this._cache.scaling.copyFrom(this.scaling);
  18757. this._cache.pivotMatrixUpdated = false;
  18758. this._cache.billboardMode = this.billboardMode;
  18759. this._currentRenderId = this.getScene().getRenderId();
  18760. this._childRenderId = this.getScene().getRenderId();
  18761. this._isDirty = false;
  18762. // Scaling
  18763. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18764. // Rotation
  18765. //rotate, if quaternion is set and rotation was used
  18766. if (this.rotationQuaternion) {
  18767. var len = this.rotation.length();
  18768. if (len) {
  18769. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18770. this.rotation.copyFromFloats(0, 0, 0);
  18771. }
  18772. }
  18773. if (this.rotationQuaternion) {
  18774. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18775. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18776. }
  18777. else {
  18778. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18779. this._cache.rotation.copyFrom(this.rotation);
  18780. }
  18781. // Translation
  18782. var camera = this.getScene().activeCamera;
  18783. if (this.infiniteDistance && !this.parent && camera) {
  18784. var cameraWorldMatrix = camera.getWorldMatrix();
  18785. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18786. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18787. }
  18788. else {
  18789. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18790. }
  18791. // Composing transformations
  18792. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18793. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18794. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18795. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18796. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18797. // Need to decompose each rotation here
  18798. var currentPosition = BABYLON.Tmp.Vector3[3];
  18799. if (this.parent && this.parent.getWorldMatrix) {
  18800. if (this._transformToBoneReferal) {
  18801. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18802. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18803. }
  18804. else {
  18805. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18806. }
  18807. }
  18808. else {
  18809. currentPosition.copyFrom(this.position);
  18810. }
  18811. currentPosition.subtractInPlace(camera.globalPosition);
  18812. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18813. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18814. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18815. }
  18816. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18817. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18818. }
  18819. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18820. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18821. }
  18822. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18823. }
  18824. else {
  18825. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18826. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18827. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18828. }
  18829. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18830. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18831. }
  18832. // Local world
  18833. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18834. // Parent
  18835. if (this.parent && this.parent.getWorldMatrix) {
  18836. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18837. if (this._transformToBoneReferal) {
  18838. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18839. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18840. }
  18841. else {
  18842. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18843. }
  18844. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18845. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18846. this._worldMatrix.copyFrom(this._localWorld);
  18847. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18848. }
  18849. else {
  18850. if (this._transformToBoneReferal) {
  18851. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18852. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18853. }
  18854. else {
  18855. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18856. }
  18857. }
  18858. this._markSyncedWithParent();
  18859. }
  18860. else {
  18861. this._worldMatrix.copyFrom(this._localWorld);
  18862. }
  18863. // Post multiply inverse of pivotMatrix
  18864. if (this._postMultiplyPivotMatrix) {
  18865. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18866. }
  18867. // Normal matrix
  18868. if (this.scaling.isNonUniform) {
  18869. this._updateNonUniformScalingState(true);
  18870. }
  18871. else if (this.parent && this.parent._nonUniformScaling) {
  18872. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18873. }
  18874. else {
  18875. this._updateNonUniformScalingState(false);
  18876. }
  18877. this._afterComputeWorldMatrix();
  18878. // Absolute position
  18879. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18880. // Callbacks
  18881. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18882. if (!this._poseMatrix) {
  18883. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18884. }
  18885. // Cache the determinant
  18886. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18887. return this._worldMatrix;
  18888. };
  18889. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18890. };
  18891. /**
  18892. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18893. * @param func: callback function to add
  18894. *
  18895. * Returns the TransformNode.
  18896. */
  18897. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18898. this.onAfterWorldMatrixUpdateObservable.add(func);
  18899. return this;
  18900. };
  18901. /**
  18902. * Removes a registered callback function.
  18903. * Returns the TransformNode.
  18904. */
  18905. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18906. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18907. return this;
  18908. };
  18909. /**
  18910. * Clone the current transform node
  18911. * Returns the new transform node
  18912. * @param name Name of the new clone
  18913. * @param newParent New parent for the clone
  18914. * @param doNotCloneChildren Do not clone children hierarchy
  18915. */
  18916. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18917. var _this = this;
  18918. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18919. result.name = name;
  18920. result.id = name;
  18921. if (newParent) {
  18922. result.parent = newParent;
  18923. }
  18924. if (!doNotCloneChildren) {
  18925. // Children
  18926. var directDescendants = this.getDescendants(true);
  18927. for (var index = 0; index < directDescendants.length; index++) {
  18928. var child = directDescendants[index];
  18929. if (child.clone) {
  18930. child.clone(name + "." + child.name, result);
  18931. }
  18932. }
  18933. }
  18934. return result;
  18935. };
  18936. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18937. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18938. serializationObject.type = this.getClassName();
  18939. // Parent
  18940. if (this.parent) {
  18941. serializationObject.parentId = this.parent.id;
  18942. }
  18943. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18944. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18945. }
  18946. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18947. serializationObject.isEnabled = this.isEnabled();
  18948. // Parent
  18949. if (this.parent) {
  18950. serializationObject.parentId = this.parent.id;
  18951. }
  18952. return serializationObject;
  18953. };
  18954. // Statics
  18955. /**
  18956. * Returns a new TransformNode object parsed from the source provided.
  18957. * The parameter `parsedMesh` is the source.
  18958. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18959. */
  18960. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18961. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18962. if (BABYLON.Tags) {
  18963. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18964. }
  18965. if (parsedTransformNode.localMatrix) {
  18966. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18967. }
  18968. else if (parsedTransformNode.pivotMatrix) {
  18969. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18970. }
  18971. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18972. // Parent
  18973. if (parsedTransformNode.parentId) {
  18974. transformNode._waitingParentId = parsedTransformNode.parentId;
  18975. }
  18976. return transformNode;
  18977. };
  18978. /**
  18979. * Releases resources associated with this transform node.
  18980. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18981. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18982. */
  18983. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18984. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18985. // Animations
  18986. this.getScene().stopAnimation(this);
  18987. // Remove from scene
  18988. this.getScene().removeTransformNode(this);
  18989. this.onAfterWorldMatrixUpdateObservable.clear();
  18990. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18991. };
  18992. // Statics
  18993. TransformNode.BILLBOARDMODE_NONE = 0;
  18994. TransformNode.BILLBOARDMODE_X = 1;
  18995. TransformNode.BILLBOARDMODE_Y = 2;
  18996. TransformNode.BILLBOARDMODE_Z = 4;
  18997. TransformNode.BILLBOARDMODE_ALL = 7;
  18998. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18999. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19000. __decorate([
  19001. BABYLON.serializeAsVector3()
  19002. ], TransformNode.prototype, "_rotation", void 0);
  19003. __decorate([
  19004. BABYLON.serializeAsQuaternion()
  19005. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19006. __decorate([
  19007. BABYLON.serializeAsVector3()
  19008. ], TransformNode.prototype, "_scaling", void 0);
  19009. __decorate([
  19010. BABYLON.serialize()
  19011. ], TransformNode.prototype, "billboardMode", void 0);
  19012. __decorate([
  19013. BABYLON.serialize()
  19014. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19015. __decorate([
  19016. BABYLON.serialize()
  19017. ], TransformNode.prototype, "infiniteDistance", void 0);
  19018. __decorate([
  19019. BABYLON.serializeAsVector3()
  19020. ], TransformNode.prototype, "position", void 0);
  19021. return TransformNode;
  19022. }(BABYLON.Node));
  19023. BABYLON.TransformNode = TransformNode;
  19024. })(BABYLON || (BABYLON = {}));
  19025. //# sourceMappingURL=babylon.transformNode.js.map
  19026. var BABYLON;
  19027. (function (BABYLON) {
  19028. /**
  19029. * Class used to store all common mesh properties
  19030. */
  19031. var AbstractMesh = /** @class */ (function (_super) {
  19032. __extends(AbstractMesh, _super);
  19033. // Constructor
  19034. /**
  19035. * Creates a new AbstractMesh
  19036. * @param name defines the name of the mesh
  19037. * @param scene defines the hosting scene
  19038. */
  19039. function AbstractMesh(name, scene) {
  19040. if (scene === void 0) { scene = null; }
  19041. var _this = _super.call(this, name, scene, false) || this;
  19042. _this._facetNb = 0; // facet number
  19043. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19044. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19045. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19046. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19047. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19048. _this._subDiv = {
  19049. max: 1,
  19050. X: 1,
  19051. Y: 1,
  19052. Z: 1
  19053. };
  19054. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19055. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19056. // Events
  19057. /**
  19058. * An event triggered when this mesh collides with another one
  19059. */
  19060. _this.onCollideObservable = new BABYLON.Observable();
  19061. /**
  19062. * An event triggered when the collision's position changes
  19063. */
  19064. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19065. /**
  19066. * An event triggered when material is changed
  19067. */
  19068. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19069. // Properties
  19070. /**
  19071. * Gets or sets the orientation for POV movement & rotation
  19072. */
  19073. _this.definedFacingForward = true;
  19074. /**
  19075. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19076. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19077. * * 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.
  19078. * @see http://doc.babylonjs.com/features/occlusionquery
  19079. */
  19080. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19081. /**
  19082. * 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:
  19083. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19084. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19085. * * 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.
  19086. * @see http://doc.babylonjs.com/features/occlusionquery
  19087. */
  19088. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19089. /**
  19090. * 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.
  19091. * The default value is -1 which means don't break the query and wait till the result
  19092. * @see http://doc.babylonjs.com/features/occlusionquery
  19093. */
  19094. _this.occlusionRetryCount = -1;
  19095. _this._occlusionInternalRetryCounter = 0;
  19096. _this._isOccluded = false;
  19097. _this._isOcclusionQueryInProgress = false;
  19098. _this._visibility = 1.0;
  19099. /** Gets or sets the alpha index used to sort transparent meshes
  19100. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19101. */
  19102. _this.alphaIndex = Number.MAX_VALUE;
  19103. /**
  19104. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19105. */
  19106. _this.isVisible = true;
  19107. /**
  19108. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19109. */
  19110. _this.isPickable = true;
  19111. /**
  19112. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19113. */
  19114. _this.showBoundingBox = false;
  19115. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19116. _this.showSubMeshesBoundingBox = false;
  19117. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19118. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19119. */
  19120. _this.isBlocker = false;
  19121. /**
  19122. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19123. */
  19124. _this.enablePointerMoveEvents = false;
  19125. /**
  19126. * Specifies the rendering group id for this mesh (0 by default)
  19127. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19128. */
  19129. _this.renderingGroupId = 0;
  19130. _this._receiveShadows = false;
  19131. /**
  19132. * Gets or sets a boolean indicating if the outline must be rendered as well
  19133. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19134. */
  19135. _this.renderOutline = false;
  19136. /** Defines color to use when rendering outline */
  19137. _this.outlineColor = BABYLON.Color3.Red();
  19138. /** Define width to use when rendering outline */
  19139. _this.outlineWidth = 0.02;
  19140. /**
  19141. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19142. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19143. */
  19144. _this.renderOverlay = false;
  19145. /** Defines color to use when rendering overlay */
  19146. _this.overlayColor = BABYLON.Color3.Red();
  19147. /** Defines alpha to use when rendering overlay */
  19148. _this.overlayAlpha = 0.5;
  19149. _this._hasVertexAlpha = false;
  19150. _this._useVertexColors = true;
  19151. _this._computeBonesUsingShaders = true;
  19152. _this._numBoneInfluencers = 4;
  19153. _this._applyFog = true;
  19154. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19155. _this.useOctreeForRenderingSelection = true;
  19156. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19157. _this.useOctreeForPicking = true;
  19158. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19159. _this.useOctreeForCollisions = true;
  19160. _this._layerMask = 0x0FFFFFFF;
  19161. /**
  19162. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19163. */
  19164. _this.alwaysSelectAsActiveMesh = false;
  19165. /**
  19166. * Gets or sets the current action manager
  19167. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19168. */
  19169. _this.actionManager = null;
  19170. /**
  19171. * Gets or sets impostor used for physic simulation
  19172. * @see http://doc.babylonjs.com/features/physics_engine
  19173. */
  19174. _this.physicsImpostor = null;
  19175. // Collisions
  19176. _this._checkCollisions = false;
  19177. _this._collisionMask = -1;
  19178. _this._collisionGroup = -1;
  19179. /**
  19180. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19181. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19182. */
  19183. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19184. /**
  19185. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19186. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19187. */
  19188. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19189. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19190. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19191. // Edges
  19192. /**
  19193. * Defines edge width used when edgesRenderer is enabled
  19194. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19195. */
  19196. _this.edgesWidth = 1;
  19197. /**
  19198. * Defines edge color used when edgesRenderer is enabled
  19199. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19200. */
  19201. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19202. // Cache
  19203. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19204. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19205. /** @ignore */
  19206. _this._renderId = 0;
  19207. /** @ignore */
  19208. _this._intersectionsInProgress = new Array();
  19209. /** @ignore */
  19210. _this._unIndexed = false;
  19211. /** @ignore */
  19212. _this._lightSources = new Array();
  19213. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19214. if (collidedMesh === void 0) { collidedMesh = null; }
  19215. //TODO move this to the collision coordinator!
  19216. if (_this.getScene().workerCollisions)
  19217. newPosition.multiplyInPlace(_this._collider._radius);
  19218. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19219. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19220. _this.position.addInPlace(_this._diffPositionForCollisions);
  19221. }
  19222. if (collidedMesh) {
  19223. _this.onCollideObservable.notifyObservers(collidedMesh);
  19224. }
  19225. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19226. };
  19227. _this.getScene().addMesh(_this);
  19228. _this._resyncLightSources();
  19229. return _this;
  19230. }
  19231. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19232. /**
  19233. * No billboard
  19234. */
  19235. get: function () {
  19236. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19237. },
  19238. enumerable: true,
  19239. configurable: true
  19240. });
  19241. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19242. /** Billboard on X axis */
  19243. get: function () {
  19244. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19250. /** Billboard on Y axis */
  19251. get: function () {
  19252. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19253. },
  19254. enumerable: true,
  19255. configurable: true
  19256. });
  19257. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19258. /** Billboard on Z axis */
  19259. get: function () {
  19260. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19261. },
  19262. enumerable: true,
  19263. configurable: true
  19264. });
  19265. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19266. /** Billboard on all axes */
  19267. get: function () {
  19268. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19269. },
  19270. enumerable: true,
  19271. configurable: true
  19272. });
  19273. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19274. /**
  19275. * Gets the number of facets in the mesh
  19276. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19277. */
  19278. get: function () {
  19279. return this._facetNb;
  19280. },
  19281. enumerable: true,
  19282. configurable: true
  19283. });
  19284. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19285. /**
  19286. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19287. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19288. */
  19289. get: function () {
  19290. return this._partitioningSubdivisions;
  19291. },
  19292. set: function (nb) {
  19293. this._partitioningSubdivisions = nb;
  19294. },
  19295. enumerable: true,
  19296. configurable: true
  19297. });
  19298. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19299. /**
  19300. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19301. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19302. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19303. */
  19304. get: function () {
  19305. return this._partitioningBBoxRatio;
  19306. },
  19307. set: function (ratio) {
  19308. this._partitioningBBoxRatio = ratio;
  19309. },
  19310. enumerable: true,
  19311. configurable: true
  19312. });
  19313. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19314. /**
  19315. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19316. * Works only for updatable meshes.
  19317. * Doesn't work with multi-materials
  19318. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19319. */
  19320. get: function () {
  19321. return this._facetDepthSort;
  19322. },
  19323. set: function (sort) {
  19324. this._facetDepthSort = sort;
  19325. },
  19326. enumerable: true,
  19327. configurable: true
  19328. });
  19329. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19330. /**
  19331. * The location (Vector3) where the facet depth sort must be computed from.
  19332. * By default, the active camera position.
  19333. * Used only when facet depth sort is enabled
  19334. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19335. */
  19336. get: function () {
  19337. return this._facetDepthSortFrom;
  19338. },
  19339. set: function (location) {
  19340. this._facetDepthSortFrom = location;
  19341. },
  19342. enumerable: true,
  19343. configurable: true
  19344. });
  19345. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19346. /**
  19347. * gets a boolean indicating if facetData is enabled
  19348. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19349. */
  19350. get: function () {
  19351. return this._facetDataEnabled;
  19352. },
  19353. enumerable: true,
  19354. configurable: true
  19355. });
  19356. /** @ignore */
  19357. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19358. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19359. return false;
  19360. }
  19361. this._markSubMeshesAsMiscDirty();
  19362. return true;
  19363. };
  19364. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19365. /** Set a function to call when this mesh collides with another one */
  19366. set: function (callback) {
  19367. if (this._onCollideObserver) {
  19368. this.onCollideObservable.remove(this._onCollideObserver);
  19369. }
  19370. this._onCollideObserver = this.onCollideObservable.add(callback);
  19371. },
  19372. enumerable: true,
  19373. configurable: true
  19374. });
  19375. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19376. /** Set a function to call when the collision's position changes */
  19377. set: function (callback) {
  19378. if (this._onCollisionPositionChangeObserver) {
  19379. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19380. }
  19381. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19382. },
  19383. enumerable: true,
  19384. configurable: true
  19385. });
  19386. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19387. /**
  19388. * 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
  19389. * @see http://doc.babylonjs.com/features/occlusionquery
  19390. */
  19391. get: function () {
  19392. return this._isOccluded;
  19393. },
  19394. set: function (value) {
  19395. this._isOccluded = value;
  19396. },
  19397. enumerable: true,
  19398. configurable: true
  19399. });
  19400. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19401. /**
  19402. * Flag to check the progress status of the query
  19403. * @see http://doc.babylonjs.com/features/occlusionquery
  19404. */
  19405. get: function () {
  19406. return this._isOcclusionQueryInProgress;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19412. /**
  19413. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19414. */
  19415. get: function () {
  19416. return this._visibility;
  19417. },
  19418. /**
  19419. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19420. */
  19421. set: function (value) {
  19422. if (this._visibility === value) {
  19423. return;
  19424. }
  19425. this._visibility = value;
  19426. this._markSubMeshesAsMiscDirty();
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(AbstractMesh.prototype, "material", {
  19432. /** Gets or sets current material */
  19433. get: function () {
  19434. return this._material;
  19435. },
  19436. set: function (value) {
  19437. if (this._material === value) {
  19438. return;
  19439. }
  19440. this._material = value;
  19441. if (this.onMaterialChangedObservable.hasObservers) {
  19442. this.onMaterialChangedObservable.notifyObservers(this);
  19443. }
  19444. if (!this.subMeshes) {
  19445. return;
  19446. }
  19447. this._unBindEffect();
  19448. },
  19449. enumerable: true,
  19450. configurable: true
  19451. });
  19452. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19453. /**
  19454. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19455. * @see http://doc.babylonjs.com/babylon101/shadows
  19456. */
  19457. get: function () {
  19458. return this._receiveShadows;
  19459. },
  19460. set: function (value) {
  19461. if (this._receiveShadows === value) {
  19462. return;
  19463. }
  19464. this._receiveShadows = value;
  19465. this._markSubMeshesAsLightDirty();
  19466. },
  19467. enumerable: true,
  19468. configurable: true
  19469. });
  19470. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19471. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19472. get: function () {
  19473. return this._hasVertexAlpha;
  19474. },
  19475. set: function (value) {
  19476. if (this._hasVertexAlpha === value) {
  19477. return;
  19478. }
  19479. this._hasVertexAlpha = value;
  19480. this._markSubMeshesAsAttributesDirty();
  19481. this._markSubMeshesAsMiscDirty();
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19487. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19488. get: function () {
  19489. return this._useVertexColors;
  19490. },
  19491. set: function (value) {
  19492. if (this._useVertexColors === value) {
  19493. return;
  19494. }
  19495. this._useVertexColors = value;
  19496. this._markSubMeshesAsAttributesDirty();
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19502. /**
  19503. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19504. */
  19505. get: function () {
  19506. return this._computeBonesUsingShaders;
  19507. },
  19508. set: function (value) {
  19509. if (this._computeBonesUsingShaders === value) {
  19510. return;
  19511. }
  19512. this._computeBonesUsingShaders = value;
  19513. this._markSubMeshesAsAttributesDirty();
  19514. },
  19515. enumerable: true,
  19516. configurable: true
  19517. });
  19518. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19519. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19520. get: function () {
  19521. return this._numBoneInfluencers;
  19522. },
  19523. set: function (value) {
  19524. if (this._numBoneInfluencers === value) {
  19525. return;
  19526. }
  19527. this._numBoneInfluencers = value;
  19528. this._markSubMeshesAsAttributesDirty();
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19534. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19535. get: function () {
  19536. return this._applyFog;
  19537. },
  19538. set: function (value) {
  19539. if (this._applyFog === value) {
  19540. return;
  19541. }
  19542. this._applyFog = value;
  19543. this._markSubMeshesAsMiscDirty();
  19544. },
  19545. enumerable: true,
  19546. configurable: true
  19547. });
  19548. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19549. /**
  19550. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19551. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19552. */
  19553. get: function () {
  19554. return this._layerMask;
  19555. },
  19556. set: function (value) {
  19557. if (value === this._layerMask) {
  19558. return;
  19559. }
  19560. this._layerMask = value;
  19561. this._resyncLightSources();
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19567. /**
  19568. * Gets or sets a collision mask used to mask collisions (default is -1).
  19569. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19570. */
  19571. get: function () {
  19572. return this._collisionMask;
  19573. },
  19574. set: function (mask) {
  19575. this._collisionMask = !isNaN(mask) ? mask : -1;
  19576. },
  19577. enumerable: true,
  19578. configurable: true
  19579. });
  19580. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19581. /**
  19582. * Gets or sets the current collision group mask (-1 by default).
  19583. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19584. */
  19585. get: function () {
  19586. return this._collisionGroup;
  19587. },
  19588. set: function (mask) {
  19589. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19590. },
  19591. enumerable: true,
  19592. configurable: true
  19593. });
  19594. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19595. /** @ignore */
  19596. get: function () {
  19597. return null;
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19603. get: function () {
  19604. return this._skeleton;
  19605. },
  19606. /**
  19607. * Gets or sets a skeleton to apply skining transformations
  19608. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19609. */
  19610. set: function (value) {
  19611. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19612. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19613. }
  19614. if (value && value.needInitialSkinMatrix) {
  19615. value._registerMeshWithPoseMatrix(this);
  19616. }
  19617. this._skeleton = value;
  19618. if (!this._skeleton) {
  19619. this._bonesTransformMatrices = null;
  19620. }
  19621. this._markSubMeshesAsAttributesDirty();
  19622. },
  19623. enumerable: true,
  19624. configurable: true
  19625. });
  19626. /**
  19627. * Returns the string "AbstractMesh"
  19628. * @returns "AbstractMesh"
  19629. */
  19630. AbstractMesh.prototype.getClassName = function () {
  19631. return "AbstractMesh";
  19632. };
  19633. /**
  19634. * Gets a string representation of the current mesh
  19635. * @param fullDetails defines a boolean indicating if full details must be included
  19636. * @returns a string representation of the current mesh
  19637. */
  19638. AbstractMesh.prototype.toString = function (fullDetails) {
  19639. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19640. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19641. if (this._skeleton) {
  19642. ret += ", skeleton: " + this._skeleton.name;
  19643. }
  19644. if (fullDetails) {
  19645. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19646. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19647. }
  19648. return ret;
  19649. };
  19650. /** @ignore */
  19651. AbstractMesh.prototype._rebuild = function () {
  19652. if (this._occlusionQuery) {
  19653. this._occlusionQuery = null;
  19654. }
  19655. if (this._edgesRenderer) {
  19656. this._edgesRenderer._rebuild();
  19657. }
  19658. if (!this.subMeshes) {
  19659. return;
  19660. }
  19661. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19662. var subMesh = _a[_i];
  19663. subMesh._rebuild();
  19664. }
  19665. };
  19666. /** @ignore */
  19667. AbstractMesh.prototype._resyncLightSources = function () {
  19668. this._lightSources.length = 0;
  19669. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19670. var light = _a[_i];
  19671. if (!light.isEnabled()) {
  19672. continue;
  19673. }
  19674. if (light.canAffectMesh(this)) {
  19675. this._lightSources.push(light);
  19676. }
  19677. }
  19678. this._markSubMeshesAsLightDirty();
  19679. };
  19680. /** @ignore */
  19681. AbstractMesh.prototype._resyncLighSource = function (light) {
  19682. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19683. var index = this._lightSources.indexOf(light);
  19684. if (index === -1) {
  19685. if (!isIn) {
  19686. return;
  19687. }
  19688. this._lightSources.push(light);
  19689. }
  19690. else {
  19691. if (isIn) {
  19692. return;
  19693. }
  19694. this._lightSources.splice(index, 1);
  19695. }
  19696. this._markSubMeshesAsLightDirty();
  19697. };
  19698. /** @ignore */
  19699. AbstractMesh.prototype._unBindEffect = function () {
  19700. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19701. var subMesh = _a[_i];
  19702. subMesh.setEffect(null);
  19703. }
  19704. };
  19705. /** @ignore */
  19706. AbstractMesh.prototype._removeLightSource = function (light) {
  19707. var index = this._lightSources.indexOf(light);
  19708. if (index === -1) {
  19709. return;
  19710. }
  19711. this._lightSources.splice(index, 1);
  19712. this._markSubMeshesAsLightDirty();
  19713. };
  19714. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19715. if (!this.subMeshes) {
  19716. return;
  19717. }
  19718. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19719. var subMesh = _a[_i];
  19720. if (subMesh._materialDefines) {
  19721. func(subMesh._materialDefines);
  19722. }
  19723. }
  19724. };
  19725. /** @ignore */
  19726. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19727. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19728. };
  19729. /** @ignore */
  19730. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19731. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19732. };
  19733. /** @ignore */
  19734. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19735. if (!this.subMeshes) {
  19736. return;
  19737. }
  19738. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19739. var subMesh = _a[_i];
  19740. var material = subMesh.getMaterial();
  19741. if (material) {
  19742. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19743. }
  19744. }
  19745. };
  19746. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19747. /**
  19748. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19749. */
  19750. get: function () {
  19751. return this._scaling;
  19752. },
  19753. set: function (newScaling) {
  19754. this._scaling = newScaling;
  19755. if (this.physicsImpostor) {
  19756. this.physicsImpostor.forceUpdate();
  19757. }
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. // Methods
  19763. /**
  19764. * Disables the mesh edge rendering mode
  19765. * @returns the currentAbstractMesh
  19766. */
  19767. AbstractMesh.prototype.disableEdgesRendering = function () {
  19768. if (this._edgesRenderer) {
  19769. this._edgesRenderer.dispose();
  19770. this._edgesRenderer = null;
  19771. }
  19772. return this;
  19773. };
  19774. /**
  19775. * Enables the edge rendering mode on the mesh.
  19776. * This mode makes the mesh edges visible
  19777. * @param epsilon defines the maximal distance between two angles to detect a face
  19778. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19779. * @returns the currentAbstractMesh
  19780. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19781. */
  19782. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19783. if (epsilon === void 0) { epsilon = 0.95; }
  19784. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19785. this.disableEdgesRendering();
  19786. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19787. return this;
  19788. };
  19789. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19790. /**
  19791. * Returns true if the mesh is blocked. Implemented by child classes
  19792. */
  19793. get: function () {
  19794. return false;
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. /**
  19800. * Returns the mesh itself by default. Implemented by child classes
  19801. * @param camera defines the camera to use to pick the right LOD level
  19802. * @returns the currentAbstractMesh
  19803. */
  19804. AbstractMesh.prototype.getLOD = function (camera) {
  19805. return this;
  19806. };
  19807. /**
  19808. * Returns 0 by default. Implemented by child classes
  19809. * @returns an integer
  19810. */
  19811. AbstractMesh.prototype.getTotalVertices = function () {
  19812. return 0;
  19813. };
  19814. /**
  19815. * Returns null by default. Implemented by child classes
  19816. * @returns null
  19817. */
  19818. AbstractMesh.prototype.getIndices = function () {
  19819. return null;
  19820. };
  19821. /**
  19822. * Returns the array of the requested vertex data kind. Implemented by child classes
  19823. * @param kind defines the vertex data kind to use
  19824. * @returns null
  19825. */
  19826. AbstractMesh.prototype.getVerticesData = function (kind) {
  19827. return null;
  19828. };
  19829. /**
  19830. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19831. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19832. * Note that a new underlying VertexBuffer object is created each call.
  19833. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19834. * @param kind defines vertex data kind:
  19835. * * BABYLON.VertexBuffer.PositionKind
  19836. * * BABYLON.VertexBuffer.UVKind
  19837. * * BABYLON.VertexBuffer.UV2Kind
  19838. * * BABYLON.VertexBuffer.UV3Kind
  19839. * * BABYLON.VertexBuffer.UV4Kind
  19840. * * BABYLON.VertexBuffer.UV5Kind
  19841. * * BABYLON.VertexBuffer.UV6Kind
  19842. * * BABYLON.VertexBuffer.ColorKind
  19843. * * BABYLON.VertexBuffer.MatricesIndicesKind
  19844. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19845. * * BABYLON.VertexBuffer.MatricesWeightsKind
  19846. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19847. * @param data defines the data source
  19848. * @param updatable defines if the data must be flagged as updatable (or static)
  19849. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  19850. * @returns the current mesh
  19851. */
  19852. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19853. return this;
  19854. };
  19855. /**
  19856. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19857. * If the mesh has no geometry, it is simply returned as it is.
  19858. * @param kind defines vertex data kind:
  19859. * * BABYLON.VertexBuffer.PositionKind
  19860. * * BABYLON.VertexBuffer.UVKind
  19861. * * BABYLON.VertexBuffer.UV2Kind
  19862. * * BABYLON.VertexBuffer.UV3Kind
  19863. * * BABYLON.VertexBuffer.UV4Kind
  19864. * * BABYLON.VertexBuffer.UV5Kind
  19865. * * BABYLON.VertexBuffer.UV6Kind
  19866. * * BABYLON.VertexBuffer.ColorKind
  19867. * * BABYLON.VertexBuffer.MatricesIndicesKind
  19868. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19869. * * BABYLON.VertexBuffer.MatricesWeightsKind
  19870. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19871. * @param data defines the data source
  19872. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  19873. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  19874. * @returns the current mesh
  19875. */
  19876. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19877. return this;
  19878. };
  19879. /**
  19880. * Sets the mesh indices,
  19881. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19882. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  19883. * @param totalVertices Defines the total number of vertices
  19884. * @returns the current mesh
  19885. */
  19886. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19887. return this;
  19888. };
  19889. /**
  19890. * Gets a boolean indicating if specific vertex data is present
  19891. * @param kind defines the vertex data kind to use
  19892. * @returns true is data kind is present
  19893. */
  19894. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19895. return false;
  19896. };
  19897. /**
  19898. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  19899. * @returns a BoundingInfo
  19900. */
  19901. AbstractMesh.prototype.getBoundingInfo = function () {
  19902. if (this._masterMesh) {
  19903. return this._masterMesh.getBoundingInfo();
  19904. }
  19905. if (!this._boundingInfo) {
  19906. // this._boundingInfo is being created here
  19907. this._updateBoundingInfo();
  19908. }
  19909. // cannot be null.
  19910. return this._boundingInfo;
  19911. };
  19912. /**
  19913. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  19914. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  19915. * @returns the current mesh
  19916. */
  19917. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19918. if (includeDescendants === void 0) { includeDescendants = true; }
  19919. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19920. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19921. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19922. if (maxDimension === 0) {
  19923. return this;
  19924. }
  19925. var scale = 1 / maxDimension;
  19926. this.scaling.scaleInPlace(scale);
  19927. return this;
  19928. };
  19929. /**
  19930. * Overwrite the current bounding info
  19931. * @param boundingInfo defines the new bounding info
  19932. * @returns the current mesh
  19933. */
  19934. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19935. this._boundingInfo = boundingInfo;
  19936. return this;
  19937. };
  19938. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19939. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  19940. get: function () {
  19941. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19942. },
  19943. enumerable: true,
  19944. configurable: true
  19945. });
  19946. /** @ignore */
  19947. AbstractMesh.prototype._preActivate = function () {
  19948. };
  19949. /** @ignore */
  19950. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19951. };
  19952. /** @ignore */
  19953. AbstractMesh.prototype._activate = function (renderId) {
  19954. this._renderId = renderId;
  19955. };
  19956. /**
  19957. * Gets the current world matrix
  19958. * @returns a Matrix
  19959. */
  19960. AbstractMesh.prototype.getWorldMatrix = function () {
  19961. if (this._masterMesh) {
  19962. return this._masterMesh.getWorldMatrix();
  19963. }
  19964. return _super.prototype.getWorldMatrix.call(this);
  19965. };
  19966. /** @ignore */
  19967. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19968. if (this._masterMesh) {
  19969. return this._masterMesh._getWorldMatrixDeterminant();
  19970. }
  19971. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19972. };
  19973. // ================================== Point of View Movement =================================
  19974. /**
  19975. * Perform relative position change from the point of view of behind the front of the mesh.
  19976. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19977. * Supports definition of mesh facing forward or backward
  19978. * @param amountRight defines the distance on the right axis
  19979. * @param amountUp defines the distance on the up axis
  19980. * @param amountForward defines the distance on the forward axis
  19981. * @returns the current mesh
  19982. */
  19983. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19984. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19985. return this;
  19986. };
  19987. /**
  19988. * Calculate relative position change from the point of view of behind the front of the mesh.
  19989. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19990. * Supports definition of mesh facing forward or backward
  19991. * @param amountRight defines the distance on the right axis
  19992. * @param amountUp defines the distance on the up axis
  19993. * @param amountForward defines the distance on the forward axis
  19994. * @returns the new displacement vector
  19995. */
  19996. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19997. var rotMatrix = new BABYLON.Matrix();
  19998. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19999. rotQuaternion.toRotationMatrix(rotMatrix);
  20000. var translationDelta = BABYLON.Vector3.Zero();
  20001. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20003. return translationDelta;
  20004. };
  20005. // ================================== Point of View Rotation =================================
  20006. /**
  20007. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20008. * Supports definition of mesh facing forward or backward
  20009. * @param flipBack defines the flip
  20010. * @param twirlClockwise defines the twirl
  20011. * @param tiltRight defines the tilt
  20012. * @returns the current mesh
  20013. */
  20014. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20015. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20016. return this;
  20017. };
  20018. /**
  20019. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20020. * Supports definition of mesh facing forward or backward.
  20021. * @param flipBack defines the flip
  20022. * @param twirlClockwise defines the twirl
  20023. * @param tiltRight defines the tilt
  20024. * @returns the new rotation vector
  20025. */
  20026. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20027. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20028. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20029. };
  20030. /**
  20031. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20032. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20033. * @returns the new bounding vectors
  20034. */
  20035. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20036. if (includeDescendants === void 0) { includeDescendants = true; }
  20037. this.computeWorldMatrix(true);
  20038. var min;
  20039. var max;
  20040. var boundingInfo = this.getBoundingInfo();
  20041. if (!this.subMeshes) {
  20042. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20043. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20044. }
  20045. else {
  20046. min = boundingInfo.boundingBox.minimumWorld;
  20047. max = boundingInfo.boundingBox.maximumWorld;
  20048. }
  20049. if (includeDescendants) {
  20050. var descendants = this.getDescendants(false);
  20051. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20052. var descendant = descendants_1[_i];
  20053. var childMesh = descendant;
  20054. childMesh.computeWorldMatrix(true);
  20055. //make sure we have the needed params to get mix and max
  20056. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20057. continue;
  20058. }
  20059. var childBoundingInfo = childMesh.getBoundingInfo();
  20060. var boundingBox = childBoundingInfo.boundingBox;
  20061. var minBox = boundingBox.minimumWorld;
  20062. var maxBox = boundingBox.maximumWorld;
  20063. BABYLON.Tools.CheckExtends(minBox, min, max);
  20064. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20065. }
  20066. }
  20067. return {
  20068. min: min,
  20069. max: max
  20070. };
  20071. };
  20072. /** @ignore */
  20073. AbstractMesh.prototype._updateBoundingInfo = function () {
  20074. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20075. this._boundingInfo.update(this.worldMatrixFromCache);
  20076. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20077. return this;
  20078. };
  20079. /** @ignore */
  20080. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20081. if (!this.subMeshes) {
  20082. return this;
  20083. }
  20084. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20085. var subMesh = this.subMeshes[subIndex];
  20086. if (!subMesh.IsGlobal) {
  20087. subMesh.updateBoundingInfo(matrix);
  20088. }
  20089. }
  20090. return this;
  20091. };
  20092. /** @ignore */
  20093. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20094. // Bounding info
  20095. this._updateBoundingInfo();
  20096. };
  20097. /**
  20098. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20099. * A mesh is in the frustum if its bounding box intersects the frustum
  20100. * @param frustumPlanes defines the frustum to test
  20101. * @returns true if the mesh is in the frustum planes
  20102. */
  20103. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20104. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20105. };
  20106. /**
  20107. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20108. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20109. * @param frustumPlanes defines the frustum to test
  20110. * @returns true if the mesh is completely in the frustum planes
  20111. */
  20112. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20113. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20114. ;
  20115. };
  20116. /**
  20117. * True if the mesh intersects another mesh or a SolidParticle object
  20118. * @param mesh defines a target mesh or SolidParticle to test
  20119. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20120. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20121. * @returns true if there is an intersection
  20122. */
  20123. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20124. if (precise === void 0) { precise = false; }
  20125. if (!this._boundingInfo || !mesh._boundingInfo) {
  20126. return false;
  20127. }
  20128. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20129. return true;
  20130. }
  20131. if (includeDescendants) {
  20132. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20133. var child = _a[_i];
  20134. if (child.intersectsMesh(mesh, precise, true)) {
  20135. return true;
  20136. }
  20137. }
  20138. }
  20139. return false;
  20140. };
  20141. /**
  20142. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20143. * @param point defines the point to test
  20144. * @returns true if there is an intersection
  20145. */
  20146. AbstractMesh.prototype.intersectsPoint = function (point) {
  20147. if (!this._boundingInfo) {
  20148. return false;
  20149. }
  20150. return this._boundingInfo.intersectsPoint(point);
  20151. };
  20152. /**
  20153. * Gets the current physics impostor
  20154. * @see http://doc.babylonjs.com/features/physics_engine
  20155. * @returns a physics impostor or null
  20156. */
  20157. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20158. return this.physicsImpostor;
  20159. };
  20160. /**
  20161. * Gets the position of the current mesh in camera space
  20162. * @param camera defines the camera to use
  20163. * @returns a position
  20164. */
  20165. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20166. if (camera === void 0) { camera = null; }
  20167. if (!camera) {
  20168. camera = this.getScene().activeCamera;
  20169. }
  20170. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20171. };
  20172. /**
  20173. * Returns the distance from the mesh to the active camera
  20174. * @param camera defines the camera to use
  20175. * @returns the distance
  20176. */
  20177. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20178. if (camera === void 0) { camera = null; }
  20179. if (!camera) {
  20180. camera = this.getScene().activeCamera;
  20181. }
  20182. return this.absolutePosition.subtract(camera.position).length();
  20183. };
  20184. /**
  20185. * Apply a physic impulse to the mesh
  20186. * @param force defines the force to apply
  20187. * @param contactPoint defines where to apply the force
  20188. * @returns the current mesh
  20189. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20190. */
  20191. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20192. if (!this.physicsImpostor) {
  20193. return this;
  20194. }
  20195. this.physicsImpostor.applyImpulse(force, contactPoint);
  20196. return this;
  20197. };
  20198. /**
  20199. * Creates a physic joint between two meshes
  20200. * @param otherMesh defines the other mesh to use
  20201. * @param pivot1 defines the pivot to use on this mesh
  20202. * @param pivot2 defines the pivot to use on the other mesh
  20203. * @param options defines additional options (can be plugin dependent)
  20204. * @returns the current mesh
  20205. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20206. */
  20207. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20208. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20209. return this;
  20210. }
  20211. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20212. mainPivot: pivot1,
  20213. connectedPivot: pivot2,
  20214. nativeParams: options
  20215. });
  20216. return this;
  20217. };
  20218. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20219. // Collisions
  20220. /**
  20221. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20222. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20223. */
  20224. get: function () {
  20225. return this._checkCollisions;
  20226. },
  20227. set: function (collisionEnabled) {
  20228. this._checkCollisions = collisionEnabled;
  20229. if (this.getScene().workerCollisions) {
  20230. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20231. }
  20232. },
  20233. enumerable: true,
  20234. configurable: true
  20235. });
  20236. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20237. /**
  20238. * Gets Collider object used to compute collisions (not physics)
  20239. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20240. */
  20241. get: function () {
  20242. return this._collider;
  20243. },
  20244. enumerable: true,
  20245. configurable: true
  20246. });
  20247. /**
  20248. * Move the mesh using collision engine
  20249. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20250. * @param displacement defines the requested displacement vector
  20251. * @returns the current mesh
  20252. */
  20253. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20254. var globalPosition = this.getAbsolutePosition();
  20255. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20256. if (!this._collider) {
  20257. this._collider = new BABYLON.Collider();
  20258. }
  20259. this._collider._radius = this.ellipsoid;
  20260. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20261. return this;
  20262. };
  20263. // Submeshes octree
  20264. /**
  20265. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20266. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20267. * @param maxCapacity defines the maximum size of each block (64 by default)
  20268. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20269. * @returns the new octree
  20270. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20271. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20272. */
  20273. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20274. if (maxCapacity === void 0) { maxCapacity = 64; }
  20275. if (maxDepth === void 0) { maxDepth = 2; }
  20276. if (!this._submeshesOctree) {
  20277. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20278. }
  20279. this.computeWorldMatrix(true);
  20280. var boundingInfo = this.getBoundingInfo();
  20281. // Update octree
  20282. var bbox = boundingInfo.boundingBox;
  20283. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20284. return this._submeshesOctree;
  20285. };
  20286. // Collisions
  20287. /** @ignore */
  20288. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20289. this._generatePointsArray();
  20290. if (!this._positions) {
  20291. return this;
  20292. }
  20293. // Transformation
  20294. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20295. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20296. subMesh._lastColliderWorldVertices = [];
  20297. subMesh._trianglePlanes = [];
  20298. var start = subMesh.verticesStart;
  20299. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20300. for (var i = start; i < end; i++) {
  20301. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20302. }
  20303. }
  20304. // Collide
  20305. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20306. if (collider.collisionFound) {
  20307. collider.collidedMesh = this;
  20308. }
  20309. return this;
  20310. };
  20311. /** @ignore */
  20312. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20313. var subMeshes;
  20314. var len;
  20315. // Octrees
  20316. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20317. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20318. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20319. len = intersections.length;
  20320. subMeshes = intersections.data;
  20321. }
  20322. else {
  20323. subMeshes = this.subMeshes;
  20324. len = subMeshes.length;
  20325. }
  20326. for (var index = 0; index < len; index++) {
  20327. var subMesh = subMeshes[index];
  20328. // Bounding test
  20329. if (len > 1 && !subMesh._checkCollision(collider))
  20330. continue;
  20331. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20332. }
  20333. return this;
  20334. };
  20335. /** @ignore */
  20336. AbstractMesh.prototype._checkCollision = function (collider) {
  20337. // Bounding box test
  20338. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20339. return this;
  20340. // Transformation matrix
  20341. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20342. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20343. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20344. return this;
  20345. };
  20346. // Picking
  20347. /** @ignore */
  20348. AbstractMesh.prototype._generatePointsArray = function () {
  20349. return false;
  20350. };
  20351. /**
  20352. * Checks if the passed Ray intersects with the mesh
  20353. * @param ray defines the ray to use
  20354. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20355. * @returns the picking info
  20356. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20357. */
  20358. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20359. var pickingInfo = new BABYLON.PickingInfo();
  20360. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20361. return pickingInfo;
  20362. }
  20363. if (!this._generatePointsArray()) {
  20364. return pickingInfo;
  20365. }
  20366. var intersectInfo = null;
  20367. // Octrees
  20368. var subMeshes;
  20369. var len;
  20370. if (this._submeshesOctree && this.useOctreeForPicking) {
  20371. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20372. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20373. len = intersections.length;
  20374. subMeshes = intersections.data;
  20375. }
  20376. else {
  20377. subMeshes = this.subMeshes;
  20378. len = subMeshes.length;
  20379. }
  20380. for (var index = 0; index < len; index++) {
  20381. var subMesh = subMeshes[index];
  20382. // Bounding test
  20383. if (len > 1 && !subMesh.canIntersects(ray))
  20384. continue;
  20385. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20386. if (currentIntersectInfo) {
  20387. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20388. intersectInfo = currentIntersectInfo;
  20389. intersectInfo.subMeshId = index;
  20390. if (fastCheck) {
  20391. break;
  20392. }
  20393. }
  20394. }
  20395. }
  20396. if (intersectInfo) {
  20397. // Get picked point
  20398. var world = this.getWorldMatrix();
  20399. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20400. var direction = ray.direction.clone();
  20401. direction = direction.scale(intersectInfo.distance);
  20402. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20403. var pickedPoint = worldOrigin.add(worldDirection);
  20404. // Return result
  20405. pickingInfo.hit = true;
  20406. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20407. pickingInfo.pickedPoint = pickedPoint;
  20408. pickingInfo.pickedMesh = this;
  20409. pickingInfo.bu = intersectInfo.bu || 0;
  20410. pickingInfo.bv = intersectInfo.bv || 0;
  20411. pickingInfo.faceId = intersectInfo.faceId;
  20412. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20413. return pickingInfo;
  20414. }
  20415. return pickingInfo;
  20416. };
  20417. /**
  20418. * Clones the current mesh
  20419. * @param name defines the mesh name
  20420. * @param newParent defines the new mesh parent
  20421. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20422. * @returns the new mesh
  20423. */
  20424. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20425. return null;
  20426. };
  20427. /**
  20428. * Disposes all the submeshes of the current meshnp
  20429. * @returns the current mesh
  20430. */
  20431. AbstractMesh.prototype.releaseSubMeshes = function () {
  20432. if (this.subMeshes) {
  20433. while (this.subMeshes.length) {
  20434. this.subMeshes[0].dispose();
  20435. }
  20436. }
  20437. else {
  20438. this.subMeshes = new Array();
  20439. }
  20440. return this;
  20441. };
  20442. /**
  20443. * Releases resources associated with this abstract mesh.
  20444. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20445. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20446. */
  20447. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20448. var _this = this;
  20449. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20450. var index;
  20451. // Smart Array Retainers.
  20452. this.getScene().freeActiveMeshes();
  20453. this.getScene().freeRenderingGroups();
  20454. // Action manager
  20455. if (this.actionManager !== undefined && this.actionManager !== null) {
  20456. this.actionManager.dispose();
  20457. this.actionManager = null;
  20458. }
  20459. // Skeleton
  20460. this._skeleton = null;
  20461. // Physics
  20462. if (this.physicsImpostor) {
  20463. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20464. }
  20465. // Intersections in progress
  20466. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20467. var other = this._intersectionsInProgress[index];
  20468. var pos = other._intersectionsInProgress.indexOf(this);
  20469. other._intersectionsInProgress.splice(pos, 1);
  20470. }
  20471. this._intersectionsInProgress = [];
  20472. // Lights
  20473. var lights = this.getScene().lights;
  20474. lights.forEach(function (light) {
  20475. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20476. if (meshIndex !== -1) {
  20477. light.includedOnlyMeshes.splice(meshIndex, 1);
  20478. }
  20479. meshIndex = light.excludedMeshes.indexOf(_this);
  20480. if (meshIndex !== -1) {
  20481. light.excludedMeshes.splice(meshIndex, 1);
  20482. }
  20483. // Shadow generators
  20484. var generator = light.getShadowGenerator();
  20485. if (generator) {
  20486. var shadowMap = generator.getShadowMap();
  20487. if (shadowMap && shadowMap.renderList) {
  20488. meshIndex = shadowMap.renderList.indexOf(_this);
  20489. if (meshIndex !== -1) {
  20490. shadowMap.renderList.splice(meshIndex, 1);
  20491. }
  20492. }
  20493. }
  20494. });
  20495. // Edges
  20496. if (this._edgesRenderer) {
  20497. this._edgesRenderer.dispose();
  20498. this._edgesRenderer = null;
  20499. }
  20500. // SubMeshes
  20501. if (this.getClassName() !== "InstancedMesh") {
  20502. this.releaseSubMeshes();
  20503. }
  20504. // Octree
  20505. var sceneOctree = this.getScene().selectionOctree;
  20506. if (sceneOctree !== undefined && sceneOctree !== null) {
  20507. var index = sceneOctree.dynamicContent.indexOf(this);
  20508. if (index !== -1) {
  20509. sceneOctree.dynamicContent.splice(index, 1);
  20510. }
  20511. }
  20512. // Query
  20513. var engine = this.getScene().getEngine();
  20514. if (this._occlusionQuery) {
  20515. this._isOcclusionQueryInProgress = false;
  20516. engine.deleteQuery(this._occlusionQuery);
  20517. this._occlusionQuery = null;
  20518. }
  20519. // Engine
  20520. engine.wipeCaches();
  20521. // Remove from scene
  20522. this.getScene().removeMesh(this);
  20523. if (disposeMaterialAndTextures) {
  20524. if (this.material) {
  20525. this.material.dispose(false, true);
  20526. }
  20527. }
  20528. if (!doNotRecurse) {
  20529. // Particles
  20530. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20531. if (this.getScene().particleSystems[index].emitter === this) {
  20532. this.getScene().particleSystems[index].dispose();
  20533. index--;
  20534. }
  20535. }
  20536. }
  20537. // facet data
  20538. if (this._facetDataEnabled) {
  20539. this.disableFacetData();
  20540. }
  20541. this.onAfterWorldMatrixUpdateObservable.clear();
  20542. this.onCollideObservable.clear();
  20543. this.onCollisionPositionChangeObservable.clear();
  20544. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20545. };
  20546. /**
  20547. * Adds the passed mesh as a child to the current mesh
  20548. * @param mesh defines the child mesh
  20549. * @returns the current mesh
  20550. */
  20551. AbstractMesh.prototype.addChild = function (mesh) {
  20552. mesh.setParent(this);
  20553. return this;
  20554. };
  20555. /**
  20556. * Removes the passed mesh from the current mesh children list
  20557. * @param mesh defines the child mesh
  20558. * @returns the current mesh
  20559. */
  20560. AbstractMesh.prototype.removeChild = function (mesh) {
  20561. mesh.setParent(null);
  20562. return this;
  20563. };
  20564. // Facet data
  20565. /** @ignore */
  20566. AbstractMesh.prototype._initFacetData = function () {
  20567. if (!this._facetNormals) {
  20568. this._facetNormals = new Array();
  20569. }
  20570. if (!this._facetPositions) {
  20571. this._facetPositions = new Array();
  20572. }
  20573. if (!this._facetPartitioning) {
  20574. this._facetPartitioning = new Array();
  20575. }
  20576. this._facetNb = (this.getIndices().length / 3) | 0;
  20577. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20578. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20579. for (var f = 0; f < this._facetNb; f++) {
  20580. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20581. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20582. }
  20583. this._facetDataEnabled = true;
  20584. return this;
  20585. };
  20586. /**
  20587. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20588. * This method can be called within the render loop.
  20589. * 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
  20590. * @returns the current mesh
  20591. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20592. */
  20593. AbstractMesh.prototype.updateFacetData = function () {
  20594. if (!this._facetDataEnabled) {
  20595. this._initFacetData();
  20596. }
  20597. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20598. var indices = this.getIndices();
  20599. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20600. var bInfo = this.getBoundingInfo();
  20601. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20602. // init arrays, matrix and sort function on first call
  20603. this._facetDepthSortEnabled = true;
  20604. if (indices instanceof Uint16Array) {
  20605. this._depthSortedIndices = new Uint16Array(indices);
  20606. }
  20607. else if (indices instanceof Uint32Array) {
  20608. this._depthSortedIndices = new Uint32Array(indices);
  20609. }
  20610. else {
  20611. var needs32bits = false;
  20612. for (var i = 0; i < indices.length; i++) {
  20613. if (indices[i] > 65535) {
  20614. needs32bits = true;
  20615. break;
  20616. }
  20617. }
  20618. if (needs32bits) {
  20619. this._depthSortedIndices = new Uint32Array(indices);
  20620. }
  20621. else {
  20622. this._depthSortedIndices = new Uint16Array(indices);
  20623. }
  20624. }
  20625. this._facetDepthSortFunction = function (f1, f2) {
  20626. return (f2.sqDistance - f1.sqDistance);
  20627. };
  20628. if (!this._facetDepthSortFrom) {
  20629. var camera = this.getScene().activeCamera;
  20630. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20631. }
  20632. this._depthSortedFacets = [];
  20633. for (var f = 0; f < this._facetNb; f++) {
  20634. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20635. this._depthSortedFacets.push(depthSortedFacet);
  20636. }
  20637. this._invertedMatrix = BABYLON.Matrix.Identity();
  20638. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20639. }
  20640. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20641. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20642. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20643. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20644. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20645. this._subDiv.max = this._partitioningSubdivisions;
  20646. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20647. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20648. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20649. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20650. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20651. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20652. // set the parameters for ComputeNormals()
  20653. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20654. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20655. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20656. this._facetParameters.bInfo = bInfo;
  20657. this._facetParameters.bbSize = this._bbSize;
  20658. this._facetParameters.subDiv = this._subDiv;
  20659. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20660. this._facetParameters.depthSort = this._facetDepthSort;
  20661. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20662. this.computeWorldMatrix(true);
  20663. this._worldMatrix.invertToRef(this._invertedMatrix);
  20664. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20665. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20666. }
  20667. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20668. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20669. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20670. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20671. var l = (this._depthSortedIndices.length / 3) | 0;
  20672. for (var f = 0; f < l; f++) {
  20673. var sind = this._depthSortedFacets[f].ind;
  20674. this._depthSortedIndices[f * 3] = indices[sind];
  20675. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20676. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20677. }
  20678. this.updateIndices(this._depthSortedIndices);
  20679. }
  20680. return this;
  20681. };
  20682. /**
  20683. * Returns the facetLocalNormals array.
  20684. * The normals are expressed in the mesh local spac
  20685. * @returns an array of Vector3
  20686. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20687. */
  20688. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20689. if (!this._facetNormals) {
  20690. this.updateFacetData();
  20691. }
  20692. return this._facetNormals;
  20693. };
  20694. /**
  20695. * Returns the facetLocalPositions array.
  20696. * The facet positions are expressed in the mesh local space
  20697. * @returns an array of Vector3
  20698. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20699. */
  20700. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20701. if (!this._facetPositions) {
  20702. this.updateFacetData();
  20703. }
  20704. return this._facetPositions;
  20705. };
  20706. /**
  20707. * Returns the facetLocalPartioning array
  20708. * @returns an array of array of numbers
  20709. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20710. */
  20711. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20712. if (!this._facetPartitioning) {
  20713. this.updateFacetData();
  20714. }
  20715. return this._facetPartitioning;
  20716. };
  20717. /**
  20718. * Returns the i-th facet position in the world system.
  20719. * This method allocates a new Vector3 per call
  20720. * @param i defines the facet index
  20721. * @returns a new Vector3
  20722. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20723. */
  20724. AbstractMesh.prototype.getFacetPosition = function (i) {
  20725. var pos = BABYLON.Vector3.Zero();
  20726. this.getFacetPositionToRef(i, pos);
  20727. return pos;
  20728. };
  20729. /**
  20730. * Sets the reference Vector3 with the i-th facet position in the world system
  20731. * @param i defines the facet index
  20732. * @param ref defines the target vector
  20733. * @returns the current mesh
  20734. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20735. */
  20736. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20737. var localPos = (this.getFacetLocalPositions())[i];
  20738. var world = this.getWorldMatrix();
  20739. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20740. return this;
  20741. };
  20742. /**
  20743. * Returns the i-th facet normal in the world system.
  20744. * This method allocates a new Vector3 per call
  20745. * @param i defines the facet index
  20746. * @returns a new Vector3
  20747. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20748. */
  20749. AbstractMesh.prototype.getFacetNormal = function (i) {
  20750. var norm = BABYLON.Vector3.Zero();
  20751. this.getFacetNormalToRef(i, norm);
  20752. return norm;
  20753. };
  20754. /**
  20755. * Sets the reference Vector3 with the i-th facet normal in the world system
  20756. * @param i defines the facet index
  20757. * @param ref defines the target vector
  20758. * @returns the current mesh
  20759. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20760. */
  20761. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20762. var localNorm = (this.getFacetLocalNormals())[i];
  20763. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20764. return this;
  20765. };
  20766. /**
  20767. * 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)
  20768. * @param x defines x coordinate
  20769. * @param y defines y coordinate
  20770. * @param z defines z coordinate
  20771. * @returns the array of facet indexes
  20772. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20773. */
  20774. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20775. var bInfo = this.getBoundingInfo();
  20776. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20777. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20778. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20779. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20780. return null;
  20781. }
  20782. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20783. };
  20784. /**
  20785. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20786. * @param projected sets as the (x,y,z) world projection on the facet
  20787. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  20788. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  20789. * @param x defines x coordinate
  20790. * @param y defines y coordinate
  20791. * @param z defines z coordinate
  20792. * @returns the face index if found (or null instead)
  20793. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20794. */
  20795. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20796. if (checkFace === void 0) { checkFace = false; }
  20797. if (facing === void 0) { facing = true; }
  20798. var world = this.getWorldMatrix();
  20799. var invMat = BABYLON.Tmp.Matrix[5];
  20800. world.invertToRef(invMat);
  20801. var invVect = BABYLON.Tmp.Vector3[8];
  20802. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20803. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20804. if (projected) {
  20805. // tranform the local computed projected vector to world coordinates
  20806. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20807. }
  20808. return closest;
  20809. };
  20810. /**
  20811. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  20812. * @param projected sets as the (x,y,z) local projection on the facet
  20813. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  20814. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  20815. * @param x defines x coordinate
  20816. * @param y defines y coordinate
  20817. * @param z defines z coordinate
  20818. * @returns the face index if found (or null instead)
  20819. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20820. */
  20821. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20822. if (checkFace === void 0) { checkFace = false; }
  20823. if (facing === void 0) { facing = true; }
  20824. var closest = null;
  20825. var tmpx = 0.0;
  20826. var tmpy = 0.0;
  20827. var tmpz = 0.0;
  20828. var d = 0.0; // tmp dot facet normal * facet position
  20829. var t0 = 0.0;
  20830. var projx = 0.0;
  20831. var projy = 0.0;
  20832. var projz = 0.0;
  20833. // Get all the facets in the same partitioning block than (x, y, z)
  20834. var facetPositions = this.getFacetLocalPositions();
  20835. var facetNormals = this.getFacetLocalNormals();
  20836. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20837. if (!facetsInBlock) {
  20838. return null;
  20839. }
  20840. // Get the closest facet to (x, y, z)
  20841. var shortest = Number.MAX_VALUE; // init distance vars
  20842. var tmpDistance = shortest;
  20843. var fib; // current facet in the block
  20844. var norm; // current facet normal
  20845. var p0; // current facet barycenter position
  20846. // loop on all the facets in the current partitioning block
  20847. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20848. fib = facetsInBlock[idx];
  20849. norm = facetNormals[fib];
  20850. p0 = facetPositions[fib];
  20851. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20852. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20853. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20854. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20855. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20856. projx = x + norm.x * t0;
  20857. projy = y + norm.y * t0;
  20858. projz = z + norm.z * t0;
  20859. tmpx = projx - x;
  20860. tmpy = projy - y;
  20861. tmpz = projz - z;
  20862. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20863. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  20864. shortest = tmpDistance;
  20865. closest = fib;
  20866. if (projected) {
  20867. projected.x = projx;
  20868. projected.y = projy;
  20869. projected.z = projz;
  20870. }
  20871. }
  20872. }
  20873. }
  20874. return closest;
  20875. };
  20876. /**
  20877. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20878. * @returns the parameters
  20879. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20880. */
  20881. AbstractMesh.prototype.getFacetDataParameters = function () {
  20882. return this._facetParameters;
  20883. };
  20884. /**
  20885. * Disables the feature FacetData and frees the related memory
  20886. * @returns the current mesh
  20887. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20888. */
  20889. AbstractMesh.prototype.disableFacetData = function () {
  20890. if (this._facetDataEnabled) {
  20891. this._facetDataEnabled = false;
  20892. this._facetPositions = new Array();
  20893. this._facetNormals = new Array();
  20894. this._facetPartitioning = new Array();
  20895. this._facetParameters = null;
  20896. this._depthSortedIndices = new Uint32Array(0);
  20897. }
  20898. return this;
  20899. };
  20900. /**
  20901. * Updates the AbstractMesh indices array
  20902. * @param indices defines the data source
  20903. * @returns the current mesh
  20904. */
  20905. AbstractMesh.prototype.updateIndices = function (indices) {
  20906. return this;
  20907. };
  20908. /**
  20909. * Creates new normals data for the mesh
  20910. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  20911. * @returns the current mesh
  20912. */
  20913. AbstractMesh.prototype.createNormals = function (updatable) {
  20914. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20915. var indices = this.getIndices();
  20916. var normals;
  20917. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20918. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20919. }
  20920. else {
  20921. normals = [];
  20922. }
  20923. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20924. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20925. return this;
  20926. };
  20927. /**
  20928. * Align the mesh with a normal
  20929. * @param normal defines the normal to use
  20930. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  20931. * @returns the current mesh
  20932. */
  20933. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20934. if (!upDirection) {
  20935. upDirection = BABYLON.Axis.Y;
  20936. }
  20937. var axisX = BABYLON.Tmp.Vector3[0];
  20938. var axisZ = BABYLON.Tmp.Vector3[1];
  20939. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20940. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20941. if (this.rotationQuaternion) {
  20942. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20943. }
  20944. else {
  20945. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20946. }
  20947. return this;
  20948. };
  20949. /** @ignore */
  20950. AbstractMesh.prototype._checkOcclusionQuery = function () {
  20951. var engine = this.getEngine();
  20952. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20953. this._isOccluded = false;
  20954. return;
  20955. }
  20956. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20957. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20958. if (isOcclusionQueryAvailable) {
  20959. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20960. this._isOcclusionQueryInProgress = false;
  20961. this._occlusionInternalRetryCounter = 0;
  20962. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20963. }
  20964. else {
  20965. this._occlusionInternalRetryCounter++;
  20966. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20967. this._isOcclusionQueryInProgress = false;
  20968. this._occlusionInternalRetryCounter = 0;
  20969. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20970. // if strict continue the last state of the object.
  20971. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20972. }
  20973. else {
  20974. return;
  20975. }
  20976. }
  20977. }
  20978. var scene = this.getScene();
  20979. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20980. if (!this._occlusionQuery) {
  20981. this._occlusionQuery = engine.createQuery();
  20982. }
  20983. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20984. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20985. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20986. this._isOcclusionQueryInProgress = true;
  20987. };
  20988. /** No occlusion */
  20989. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20990. /** Occlusion set to optimisitic */
  20991. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20992. /** Occlusion set to strict */
  20993. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20994. /** Use an accurante occlusion algorithm */
  20995. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20996. /** Use a conservative occlusion algorithm */
  20997. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20998. return AbstractMesh;
  20999. }(BABYLON.TransformNode));
  21000. BABYLON.AbstractMesh = AbstractMesh;
  21001. })(BABYLON || (BABYLON = {}));
  21002. //# sourceMappingURL=babylon.abstractMesh.js.map
  21003. var BABYLON;
  21004. (function (BABYLON) {
  21005. /**
  21006. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21007. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21008. * 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.
  21009. */
  21010. var Light = /** @class */ (function (_super) {
  21011. __extends(Light, _super);
  21012. /**
  21013. * Creates a Light object in the scene.
  21014. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21015. * @param name The firendly name of the light
  21016. * @param scene The scene the light belongs too
  21017. */
  21018. function Light(name, scene) {
  21019. var _this = _super.call(this, name, scene) || this;
  21020. /**
  21021. * Diffuse gives the basic color to an object.
  21022. */
  21023. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21024. /**
  21025. * Specular produces a highlight color on an object.
  21026. * Note: This is note affecting PBR materials.
  21027. */
  21028. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21029. /**
  21030. * Strength of the light.
  21031. * Note: By default it is define in the framework own unit.
  21032. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21033. */
  21034. _this.intensity = 1.0;
  21035. /**
  21036. * Defines how far from the source the light is impacting in scene units.
  21037. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21038. */
  21039. _this.range = Number.MAX_VALUE;
  21040. /**
  21041. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21042. * of light.
  21043. */
  21044. _this._photometricScale = 1.0;
  21045. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21046. _this._radius = 0.00001;
  21047. /**
  21048. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21049. * exceeding the number allowed of the materials.
  21050. */
  21051. _this.renderPriority = 0;
  21052. /**
  21053. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21054. * the current shadow generator.
  21055. */
  21056. _this.shadowEnabled = true;
  21057. _this._excludeWithLayerMask = 0;
  21058. _this._includeOnlyWithLayerMask = 0;
  21059. _this._lightmapMode = 0;
  21060. /**
  21061. * @ignore Internal use only.
  21062. */
  21063. _this._excludedMeshesIds = new Array();
  21064. /**
  21065. * @ignore Internal use only.
  21066. */
  21067. _this._includedOnlyMeshesIds = new Array();
  21068. _this.getScene().addLight(_this);
  21069. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21070. _this._buildUniformLayout();
  21071. _this.includedOnlyMeshes = new Array();
  21072. _this.excludedMeshes = new Array();
  21073. _this._resyncMeshes();
  21074. return _this;
  21075. }
  21076. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21077. /**
  21078. * If every light affecting the material is in this lightmapMode,
  21079. * material.lightmapTexture adds or multiplies
  21080. * (depends on material.useLightmapAsShadowmap)
  21081. * after every other light calculations.
  21082. */
  21083. get: function () {
  21084. return Light._LIGHTMAP_DEFAULT;
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21090. /**
  21091. * material.lightmapTexture as only diffuse lighting from this light
  21092. * adds only specular lighting from this light
  21093. * adds dynamic shadows
  21094. */
  21095. get: function () {
  21096. return Light._LIGHTMAP_SPECULAR;
  21097. },
  21098. enumerable: true,
  21099. configurable: true
  21100. });
  21101. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21102. /**
  21103. * material.lightmapTexture as only lighting
  21104. * no light calculation from this light
  21105. * only adds dynamic shadows from this light
  21106. */
  21107. get: function () {
  21108. return Light._LIGHTMAP_SHADOWSONLY;
  21109. },
  21110. enumerable: true,
  21111. configurable: true
  21112. });
  21113. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21114. /**
  21115. * Each light type uses the default quantity according to its type:
  21116. * point/spot lights use luminous intensity
  21117. * directional lights use illuminance
  21118. */
  21119. get: function () {
  21120. return Light._INTENSITYMODE_AUTOMATIC;
  21121. },
  21122. enumerable: true,
  21123. configurable: true
  21124. });
  21125. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21126. /**
  21127. * lumen (lm)
  21128. */
  21129. get: function () {
  21130. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21131. },
  21132. enumerable: true,
  21133. configurable: true
  21134. });
  21135. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21136. /**
  21137. * candela (lm/sr)
  21138. */
  21139. get: function () {
  21140. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21141. },
  21142. enumerable: true,
  21143. configurable: true
  21144. });
  21145. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21146. /**
  21147. * lux (lm/m^2)
  21148. */
  21149. get: function () {
  21150. return Light._INTENSITYMODE_ILLUMINANCE;
  21151. },
  21152. enumerable: true,
  21153. configurable: true
  21154. });
  21155. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21156. /**
  21157. * nit (cd/m^2)
  21158. */
  21159. get: function () {
  21160. return Light._INTENSITYMODE_LUMINANCE;
  21161. },
  21162. enumerable: true,
  21163. configurable: true
  21164. });
  21165. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21166. /**
  21167. * Light type const id of the point light.
  21168. */
  21169. get: function () {
  21170. return Light._LIGHTTYPEID_POINTLIGHT;
  21171. },
  21172. enumerable: true,
  21173. configurable: true
  21174. });
  21175. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21176. /**
  21177. * Light type const id of the directional light.
  21178. */
  21179. get: function () {
  21180. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21186. /**
  21187. * Light type const id of the spot light.
  21188. */
  21189. get: function () {
  21190. return Light._LIGHTTYPEID_SPOTLIGHT;
  21191. },
  21192. enumerable: true,
  21193. configurable: true
  21194. });
  21195. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21196. /**
  21197. * Light type const id of the hemispheric light.
  21198. */
  21199. get: function () {
  21200. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21201. },
  21202. enumerable: true,
  21203. configurable: true
  21204. });
  21205. Object.defineProperty(Light.prototype, "intensityMode", {
  21206. /**
  21207. * Gets the photometric scale used to interpret the intensity.
  21208. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21209. */
  21210. get: function () {
  21211. return this._intensityMode;
  21212. },
  21213. /**
  21214. * Sets the photometric scale used to interpret the intensity.
  21215. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21216. */
  21217. set: function (value) {
  21218. this._intensityMode = value;
  21219. this._computePhotometricScale();
  21220. },
  21221. enumerable: true,
  21222. configurable: true
  21223. });
  21224. ;
  21225. ;
  21226. Object.defineProperty(Light.prototype, "radius", {
  21227. /**
  21228. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21229. */
  21230. get: function () {
  21231. return this._radius;
  21232. },
  21233. /**
  21234. * sets the light radius used by PBR Materials to simulate soft area lights.
  21235. */
  21236. set: function (value) {
  21237. this._radius = value;
  21238. this._computePhotometricScale();
  21239. },
  21240. enumerable: true,
  21241. configurable: true
  21242. });
  21243. ;
  21244. ;
  21245. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21246. /**
  21247. * Gets the only meshes impacted by this light.
  21248. */
  21249. get: function () {
  21250. return this._includedOnlyMeshes;
  21251. },
  21252. /**
  21253. * Sets the only meshes impacted by this light.
  21254. */
  21255. set: function (value) {
  21256. this._includedOnlyMeshes = value;
  21257. this._hookArrayForIncludedOnly(value);
  21258. },
  21259. enumerable: true,
  21260. configurable: true
  21261. });
  21262. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21263. /**
  21264. * Gets the meshes not impacted by this light.
  21265. */
  21266. get: function () {
  21267. return this._excludedMeshes;
  21268. },
  21269. /**
  21270. * Sets the meshes not impacted by this light.
  21271. */
  21272. set: function (value) {
  21273. this._excludedMeshes = value;
  21274. this._hookArrayForExcluded(value);
  21275. },
  21276. enumerable: true,
  21277. configurable: true
  21278. });
  21279. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21280. /**
  21281. * Gets the layer id use to find what meshes are not impacted by the light.
  21282. * Inactive if 0
  21283. */
  21284. get: function () {
  21285. return this._excludeWithLayerMask;
  21286. },
  21287. /**
  21288. * Sets the layer id use to find what meshes are not impacted by the light.
  21289. * Inactive if 0
  21290. */
  21291. set: function (value) {
  21292. this._excludeWithLayerMask = value;
  21293. this._resyncMeshes();
  21294. },
  21295. enumerable: true,
  21296. configurable: true
  21297. });
  21298. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21299. /**
  21300. * Gets the layer id use to find what meshes are impacted by the light.
  21301. * Inactive if 0
  21302. */
  21303. get: function () {
  21304. return this._includeOnlyWithLayerMask;
  21305. },
  21306. /**
  21307. * Sets the layer id use to find what meshes are impacted by the light.
  21308. * Inactive if 0
  21309. */
  21310. set: function (value) {
  21311. this._includeOnlyWithLayerMask = value;
  21312. this._resyncMeshes();
  21313. },
  21314. enumerable: true,
  21315. configurable: true
  21316. });
  21317. Object.defineProperty(Light.prototype, "lightmapMode", {
  21318. /**
  21319. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21320. */
  21321. get: function () {
  21322. return this._lightmapMode;
  21323. },
  21324. /**
  21325. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21326. */
  21327. set: function (value) {
  21328. if (this._lightmapMode === value) {
  21329. return;
  21330. }
  21331. this._lightmapMode = value;
  21332. this._markMeshesAsLightDirty();
  21333. },
  21334. enumerable: true,
  21335. configurable: true
  21336. });
  21337. /**
  21338. * Returns the string "Light".
  21339. * @returns the class name
  21340. */
  21341. Light.prototype.getClassName = function () {
  21342. return "Light";
  21343. };
  21344. /**
  21345. * Converts the light information to a readable string for debug purpose.
  21346. * @param fullDetails Supports for multiple levels of logging within scene loading
  21347. * @returns the human readable light info
  21348. */
  21349. Light.prototype.toString = function (fullDetails) {
  21350. var ret = "Name: " + this.name;
  21351. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21352. if (this.animations) {
  21353. for (var i = 0; i < this.animations.length; i++) {
  21354. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21355. }
  21356. }
  21357. if (fullDetails) {
  21358. }
  21359. return ret;
  21360. };
  21361. /**
  21362. * Set the enabled state of this node.
  21363. * @param value - the new enabled state
  21364. */
  21365. Light.prototype.setEnabled = function (value) {
  21366. _super.prototype.setEnabled.call(this, value);
  21367. this._resyncMeshes();
  21368. };
  21369. /**
  21370. * Returns the Light associated shadow generator if any.
  21371. * @return the associated shadow generator.
  21372. */
  21373. Light.prototype.getShadowGenerator = function () {
  21374. return this._shadowGenerator;
  21375. };
  21376. /**
  21377. * Returns a Vector3, the absolute light position in the World.
  21378. * @returns the world space position of the light
  21379. */
  21380. Light.prototype.getAbsolutePosition = function () {
  21381. return BABYLON.Vector3.Zero();
  21382. };
  21383. /**
  21384. * Specifies if the light will affect the passed mesh.
  21385. * @param mesh The mesh to test against the light
  21386. * @return true the mesh is affected otherwise, false.
  21387. */
  21388. Light.prototype.canAffectMesh = function (mesh) {
  21389. if (!mesh) {
  21390. return true;
  21391. }
  21392. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21393. return false;
  21394. }
  21395. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21396. return false;
  21397. }
  21398. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21399. return false;
  21400. }
  21401. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21402. return false;
  21403. }
  21404. return true;
  21405. };
  21406. /**
  21407. * Computes and Returns the light World matrix.
  21408. * @returns the world matrix
  21409. */
  21410. Light.prototype.getWorldMatrix = function () {
  21411. this._currentRenderId = this.getScene().getRenderId();
  21412. this._childRenderId = this._currentRenderId;
  21413. var worldMatrix = this._getWorldMatrix();
  21414. if (this.parent && this.parent.getWorldMatrix) {
  21415. if (!this._parentedWorldMatrix) {
  21416. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21417. }
  21418. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21419. this._markSyncedWithParent();
  21420. return this._parentedWorldMatrix;
  21421. }
  21422. return worldMatrix;
  21423. };
  21424. /**
  21425. * Sort function to order lights for rendering.
  21426. * @param a First Light object to compare to second.
  21427. * @param b Second Light object to compare first.
  21428. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21429. */
  21430. Light.CompareLightsPriority = function (a, b) {
  21431. //shadow-casting lights have priority over non-shadow-casting lights
  21432. //the renderPrioirty is a secondary sort criterion
  21433. if (a.shadowEnabled !== b.shadowEnabled) {
  21434. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21435. }
  21436. return b.renderPriority - a.renderPriority;
  21437. };
  21438. /**
  21439. * Releases resources associated with this node.
  21440. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21441. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21442. */
  21443. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21444. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21445. if (this._shadowGenerator) {
  21446. this._shadowGenerator.dispose();
  21447. this._shadowGenerator = null;
  21448. }
  21449. // Animations
  21450. this.getScene().stopAnimation(this);
  21451. // Remove from meshes
  21452. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21453. var mesh = _a[_i];
  21454. mesh._removeLightSource(this);
  21455. }
  21456. this._uniformBuffer.dispose();
  21457. // Remove from scene
  21458. this.getScene().removeLight(this);
  21459. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21460. };
  21461. /**
  21462. * Returns the light type ID (integer).
  21463. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21464. */
  21465. Light.prototype.getTypeID = function () {
  21466. return 0;
  21467. };
  21468. /**
  21469. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21470. * @returns the scaled intensity in intensity mode unit
  21471. */
  21472. Light.prototype.getScaledIntensity = function () {
  21473. return this._photometricScale * this.intensity;
  21474. };
  21475. /**
  21476. * Returns a new Light object, named "name", from the current one.
  21477. * @param name The name of the cloned light
  21478. * @returns the new created light
  21479. */
  21480. Light.prototype.clone = function (name) {
  21481. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21482. if (!constructor) {
  21483. return null;
  21484. }
  21485. return BABYLON.SerializationHelper.Clone(constructor, this);
  21486. };
  21487. /**
  21488. * Serializes the current light into a Serialization object.
  21489. * @returns the serialized object.
  21490. */
  21491. Light.prototype.serialize = function () {
  21492. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21493. // Type
  21494. serializationObject.type = this.getTypeID();
  21495. // Parent
  21496. if (this.parent) {
  21497. serializationObject.parentId = this.parent.id;
  21498. }
  21499. // Inclusion / exclusions
  21500. if (this.excludedMeshes.length > 0) {
  21501. serializationObject.excludedMeshesIds = [];
  21502. this.excludedMeshes.forEach(function (mesh) {
  21503. serializationObject.excludedMeshesIds.push(mesh.id);
  21504. });
  21505. }
  21506. if (this.includedOnlyMeshes.length > 0) {
  21507. serializationObject.includedOnlyMeshesIds = [];
  21508. this.includedOnlyMeshes.forEach(function (mesh) {
  21509. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21510. });
  21511. }
  21512. // Animations
  21513. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21514. serializationObject.ranges = this.serializeAnimationRanges();
  21515. return serializationObject;
  21516. };
  21517. /**
  21518. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21519. * This new light is named "name" and added to the passed scene.
  21520. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21521. * @param name The friendly name of the light
  21522. * @param scene The scene the new light will belong to
  21523. * @returns the constructor function
  21524. */
  21525. Light.GetConstructorFromName = function (type, name, scene) {
  21526. switch (type) {
  21527. case 0:
  21528. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21529. case 1:
  21530. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21531. case 2:
  21532. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21533. case 3:
  21534. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21535. }
  21536. return null;
  21537. };
  21538. /**
  21539. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21540. * @param parsedLight The JSON representation of the light
  21541. * @param scene The scene to create the parsed light in
  21542. * @returns the created light after parsing
  21543. */
  21544. Light.Parse = function (parsedLight, scene) {
  21545. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21546. if (!constructor) {
  21547. return null;
  21548. }
  21549. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21550. // Inclusion / exclusions
  21551. if (parsedLight.excludedMeshesIds) {
  21552. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21553. }
  21554. if (parsedLight.includedOnlyMeshesIds) {
  21555. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21556. }
  21557. // Parent
  21558. if (parsedLight.parentId) {
  21559. light._waitingParentId = parsedLight.parentId;
  21560. }
  21561. // Animations
  21562. if (parsedLight.animations) {
  21563. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21564. var parsedAnimation = parsedLight.animations[animationIndex];
  21565. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21566. }
  21567. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21568. }
  21569. if (parsedLight.autoAnimate) {
  21570. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21571. }
  21572. return light;
  21573. };
  21574. Light.prototype._hookArrayForExcluded = function (array) {
  21575. var _this = this;
  21576. var oldPush = array.push;
  21577. array.push = function () {
  21578. var items = [];
  21579. for (var _i = 0; _i < arguments.length; _i++) {
  21580. items[_i] = arguments[_i];
  21581. }
  21582. var result = oldPush.apply(array, items);
  21583. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21584. var item = items_1[_a];
  21585. item._resyncLighSource(_this);
  21586. }
  21587. return result;
  21588. };
  21589. var oldSplice = array.splice;
  21590. array.splice = function (index, deleteCount) {
  21591. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21592. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21593. var item = deleted_1[_i];
  21594. item._resyncLighSource(_this);
  21595. }
  21596. return deleted;
  21597. };
  21598. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21599. var item = array_1[_i];
  21600. item._resyncLighSource(this);
  21601. }
  21602. };
  21603. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21604. var _this = this;
  21605. var oldPush = array.push;
  21606. array.push = function () {
  21607. var items = [];
  21608. for (var _i = 0; _i < arguments.length; _i++) {
  21609. items[_i] = arguments[_i];
  21610. }
  21611. var result = oldPush.apply(array, items);
  21612. _this._resyncMeshes();
  21613. return result;
  21614. };
  21615. var oldSplice = array.splice;
  21616. array.splice = function (index, deleteCount) {
  21617. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21618. _this._resyncMeshes();
  21619. return deleted;
  21620. };
  21621. this._resyncMeshes();
  21622. };
  21623. Light.prototype._resyncMeshes = function () {
  21624. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21625. var mesh = _a[_i];
  21626. mesh._resyncLighSource(this);
  21627. }
  21628. };
  21629. /**
  21630. * Forces the meshes to update their light related information in their rendering used effects
  21631. * @ignore Internal Use Only
  21632. */
  21633. Light.prototype._markMeshesAsLightDirty = function () {
  21634. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21635. var mesh = _a[_i];
  21636. if (mesh._lightSources.indexOf(this) !== -1) {
  21637. mesh._markSubMeshesAsLightDirty();
  21638. }
  21639. }
  21640. };
  21641. /**
  21642. * Recomputes the cached photometric scale if needed.
  21643. */
  21644. Light.prototype._computePhotometricScale = function () {
  21645. this._photometricScale = this._getPhotometricScale();
  21646. this.getScene().resetCachedMaterial();
  21647. };
  21648. /**
  21649. * Returns the Photometric Scale according to the light type and intensity mode.
  21650. */
  21651. Light.prototype._getPhotometricScale = function () {
  21652. var photometricScale = 0.0;
  21653. var lightTypeID = this.getTypeID();
  21654. //get photometric mode
  21655. var photometricMode = this.intensityMode;
  21656. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21657. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21658. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21659. }
  21660. else {
  21661. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21662. }
  21663. }
  21664. //compute photometric scale
  21665. switch (lightTypeID) {
  21666. case Light.LIGHTTYPEID_POINTLIGHT:
  21667. case Light.LIGHTTYPEID_SPOTLIGHT:
  21668. switch (photometricMode) {
  21669. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21670. photometricScale = 1.0 / (4.0 * Math.PI);
  21671. break;
  21672. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21673. photometricScale = 1.0;
  21674. break;
  21675. case Light.INTENSITYMODE_LUMINANCE:
  21676. photometricScale = this.radius * this.radius;
  21677. break;
  21678. }
  21679. break;
  21680. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21681. switch (photometricMode) {
  21682. case Light.INTENSITYMODE_ILLUMINANCE:
  21683. photometricScale = 1.0;
  21684. break;
  21685. case Light.INTENSITYMODE_LUMINANCE:
  21686. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21687. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21688. var apexAngleRadians = this.radius;
  21689. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21690. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21691. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21692. photometricScale = solidAngle;
  21693. break;
  21694. }
  21695. break;
  21696. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21697. // No fall off in hemisperic light.
  21698. photometricScale = 1.0;
  21699. break;
  21700. }
  21701. return photometricScale;
  21702. };
  21703. /**
  21704. * Reorder the light in the scene according to their defined priority.
  21705. * @ignore Internal Use Only
  21706. */
  21707. Light.prototype._reorderLightsInScene = function () {
  21708. var scene = this.getScene();
  21709. if (this._renderPriority != 0) {
  21710. scene.requireLightSorting = true;
  21711. }
  21712. this.getScene().sortLightsByPriority();
  21713. };
  21714. //lightmapMode Consts
  21715. Light._LIGHTMAP_DEFAULT = 0;
  21716. Light._LIGHTMAP_SPECULAR = 1;
  21717. Light._LIGHTMAP_SHADOWSONLY = 2;
  21718. // Intensity Mode Consts
  21719. Light._INTENSITYMODE_AUTOMATIC = 0;
  21720. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21721. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21722. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21723. Light._INTENSITYMODE_LUMINANCE = 4;
  21724. // Light types ids const.
  21725. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21726. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21727. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21728. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21729. __decorate([
  21730. BABYLON.serializeAsColor3()
  21731. ], Light.prototype, "diffuse", void 0);
  21732. __decorate([
  21733. BABYLON.serializeAsColor3()
  21734. ], Light.prototype, "specular", void 0);
  21735. __decorate([
  21736. BABYLON.serialize()
  21737. ], Light.prototype, "intensity", void 0);
  21738. __decorate([
  21739. BABYLON.serialize()
  21740. ], Light.prototype, "range", void 0);
  21741. __decorate([
  21742. BABYLON.serialize()
  21743. ], Light.prototype, "intensityMode", null);
  21744. __decorate([
  21745. BABYLON.serialize()
  21746. ], Light.prototype, "radius", null);
  21747. __decorate([
  21748. BABYLON.serialize()
  21749. ], Light.prototype, "_renderPriority", void 0);
  21750. __decorate([
  21751. BABYLON.expandToProperty("_reorderLightsInScene")
  21752. ], Light.prototype, "renderPriority", void 0);
  21753. __decorate([
  21754. BABYLON.serialize()
  21755. ], Light.prototype, "shadowEnabled", void 0);
  21756. __decorate([
  21757. BABYLON.serialize("excludeWithLayerMask")
  21758. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21759. __decorate([
  21760. BABYLON.serialize("includeOnlyWithLayerMask")
  21761. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21762. __decorate([
  21763. BABYLON.serialize("lightmapMode")
  21764. ], Light.prototype, "_lightmapMode", void 0);
  21765. return Light;
  21766. }(BABYLON.Node));
  21767. BABYLON.Light = Light;
  21768. })(BABYLON || (BABYLON = {}));
  21769. //# sourceMappingURL=babylon.light.js.map
  21770. var BABYLON;
  21771. (function (BABYLON) {
  21772. var Camera = /** @class */ (function (_super) {
  21773. __extends(Camera, _super);
  21774. function Camera(name, position, scene) {
  21775. var _this = _super.call(this, name, scene) || this;
  21776. /**
  21777. * The vector the camera should consider as up.
  21778. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21779. */
  21780. _this.upVector = BABYLON.Vector3.Up();
  21781. _this.orthoLeft = null;
  21782. _this.orthoRight = null;
  21783. _this.orthoBottom = null;
  21784. _this.orthoTop = null;
  21785. /**
  21786. * FOV is set in Radians. (default is 0.8)
  21787. */
  21788. _this.fov = 0.8;
  21789. _this.minZ = 1;
  21790. _this.maxZ = 10000.0;
  21791. _this.inertia = 0.9;
  21792. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21793. _this.isIntermediate = false;
  21794. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21795. /**
  21796. * Restricts the camera to viewing objects with the same layerMask.
  21797. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21798. */
  21799. _this.layerMask = 0x0FFFFFFF;
  21800. /**
  21801. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21802. */
  21803. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21804. // Camera rig members
  21805. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21806. _this._rigCameras = new Array();
  21807. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21808. _this._skipRendering = false;
  21809. _this.customRenderTargets = new Array();
  21810. // Observables
  21811. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21812. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21813. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21814. _this.onRestoreStateObservable = new BABYLON.Observable();
  21815. // Cache
  21816. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21817. _this._projectionMatrix = new BABYLON.Matrix();
  21818. _this._doNotComputeProjectionMatrix = false;
  21819. _this._postProcesses = new Array();
  21820. _this._transformMatrix = BABYLON.Matrix.Zero();
  21821. _this._activeMeshes = new BABYLON.SmartArray(256);
  21822. _this._globalPosition = BABYLON.Vector3.Zero();
  21823. _this._refreshFrustumPlanes = true;
  21824. _this.getScene().addCamera(_this);
  21825. if (!_this.getScene().activeCamera) {
  21826. _this.getScene().activeCamera = _this;
  21827. }
  21828. _this.position = position;
  21829. return _this;
  21830. }
  21831. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21832. get: function () {
  21833. return Camera._PERSPECTIVE_CAMERA;
  21834. },
  21835. enumerable: true,
  21836. configurable: true
  21837. });
  21838. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21839. get: function () {
  21840. return Camera._ORTHOGRAPHIC_CAMERA;
  21841. },
  21842. enumerable: true,
  21843. configurable: true
  21844. });
  21845. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21846. /**
  21847. * This is the default FOV mode for perspective cameras.
  21848. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21849. *
  21850. */
  21851. get: function () {
  21852. return Camera._FOVMODE_VERTICAL_FIXED;
  21853. },
  21854. enumerable: true,
  21855. configurable: true
  21856. });
  21857. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21858. /**
  21859. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21860. *
  21861. */
  21862. get: function () {
  21863. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21864. },
  21865. enumerable: true,
  21866. configurable: true
  21867. });
  21868. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21869. get: function () {
  21870. return Camera._RIG_MODE_NONE;
  21871. },
  21872. enumerable: true,
  21873. configurable: true
  21874. });
  21875. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21876. get: function () {
  21877. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21878. },
  21879. enumerable: true,
  21880. configurable: true
  21881. });
  21882. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21883. get: function () {
  21884. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21885. },
  21886. enumerable: true,
  21887. configurable: true
  21888. });
  21889. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21890. get: function () {
  21891. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21892. },
  21893. enumerable: true,
  21894. configurable: true
  21895. });
  21896. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21897. get: function () {
  21898. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21899. },
  21900. enumerable: true,
  21901. configurable: true
  21902. });
  21903. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21904. get: function () {
  21905. return Camera._RIG_MODE_VR;
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21911. get: function () {
  21912. return Camera._RIG_MODE_WEBVR;
  21913. },
  21914. enumerable: true,
  21915. configurable: true
  21916. });
  21917. /**
  21918. * Store current camera state (fov, position, etc..)
  21919. */
  21920. Camera.prototype.storeState = function () {
  21921. this._stateStored = true;
  21922. this._storedFov = this.fov;
  21923. return this;
  21924. };
  21925. /**
  21926. * Restores the camera state values if it has been stored. You must call storeState() first
  21927. */
  21928. Camera.prototype._restoreStateValues = function () {
  21929. if (!this._stateStored) {
  21930. return false;
  21931. }
  21932. this.fov = this._storedFov;
  21933. return true;
  21934. };
  21935. /**
  21936. * Restored camera state. You must call storeState() first
  21937. */
  21938. Camera.prototype.restoreState = function () {
  21939. if (this._restoreStateValues()) {
  21940. this.onRestoreStateObservable.notifyObservers(this);
  21941. return true;
  21942. }
  21943. return false;
  21944. };
  21945. Camera.prototype.getClassName = function () {
  21946. return "Camera";
  21947. };
  21948. /**
  21949. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21950. */
  21951. Camera.prototype.toString = function (fullDetails) {
  21952. var ret = "Name: " + this.name;
  21953. ret += ", type: " + this.getClassName();
  21954. if (this.animations) {
  21955. for (var i = 0; i < this.animations.length; i++) {
  21956. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21957. }
  21958. }
  21959. if (fullDetails) {
  21960. }
  21961. return ret;
  21962. };
  21963. Object.defineProperty(Camera.prototype, "globalPosition", {
  21964. get: function () {
  21965. return this._globalPosition;
  21966. },
  21967. enumerable: true,
  21968. configurable: true
  21969. });
  21970. Camera.prototype.getActiveMeshes = function () {
  21971. return this._activeMeshes;
  21972. };
  21973. Camera.prototype.isActiveMesh = function (mesh) {
  21974. return (this._activeMeshes.indexOf(mesh) !== -1);
  21975. };
  21976. /**
  21977. * Is this camera ready to be used/rendered
  21978. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21979. * @return true if the camera is ready
  21980. */
  21981. Camera.prototype.isReady = function (completeCheck) {
  21982. if (completeCheck === void 0) { completeCheck = false; }
  21983. if (completeCheck) {
  21984. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21985. var pp = _a[_i];
  21986. if (pp && !pp.isReady()) {
  21987. return false;
  21988. }
  21989. }
  21990. }
  21991. return _super.prototype.isReady.call(this, completeCheck);
  21992. };
  21993. //Cache
  21994. Camera.prototype._initCache = function () {
  21995. _super.prototype._initCache.call(this);
  21996. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21997. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21998. this._cache.mode = undefined;
  21999. this._cache.minZ = undefined;
  22000. this._cache.maxZ = undefined;
  22001. this._cache.fov = undefined;
  22002. this._cache.fovMode = undefined;
  22003. this._cache.aspectRatio = undefined;
  22004. this._cache.orthoLeft = undefined;
  22005. this._cache.orthoRight = undefined;
  22006. this._cache.orthoBottom = undefined;
  22007. this._cache.orthoTop = undefined;
  22008. this._cache.renderWidth = undefined;
  22009. this._cache.renderHeight = undefined;
  22010. };
  22011. Camera.prototype._updateCache = function (ignoreParentClass) {
  22012. if (!ignoreParentClass) {
  22013. _super.prototype._updateCache.call(this);
  22014. }
  22015. this._cache.position.copyFrom(this.position);
  22016. this._cache.upVector.copyFrom(this.upVector);
  22017. };
  22018. // Synchronized
  22019. Camera.prototype._isSynchronized = function () {
  22020. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22021. };
  22022. Camera.prototype._isSynchronizedViewMatrix = function () {
  22023. if (!_super.prototype._isSynchronized.call(this))
  22024. return false;
  22025. return this._cache.position.equals(this.position)
  22026. && this._cache.upVector.equals(this.upVector)
  22027. && this.isSynchronizedWithParent();
  22028. };
  22029. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22030. var check = this._cache.mode === this.mode
  22031. && this._cache.minZ === this.minZ
  22032. && this._cache.maxZ === this.maxZ;
  22033. if (!check) {
  22034. return false;
  22035. }
  22036. var engine = this.getEngine();
  22037. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22038. check = this._cache.fov === this.fov
  22039. && this._cache.fovMode === this.fovMode
  22040. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22041. }
  22042. else {
  22043. check = this._cache.orthoLeft === this.orthoLeft
  22044. && this._cache.orthoRight === this.orthoRight
  22045. && this._cache.orthoBottom === this.orthoBottom
  22046. && this._cache.orthoTop === this.orthoTop
  22047. && this._cache.renderWidth === engine.getRenderWidth()
  22048. && this._cache.renderHeight === engine.getRenderHeight();
  22049. }
  22050. return check;
  22051. };
  22052. // Controls
  22053. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22054. };
  22055. Camera.prototype.detachControl = function (element) {
  22056. };
  22057. Camera.prototype.update = function () {
  22058. this._checkInputs();
  22059. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22060. this._updateRigCameras();
  22061. }
  22062. };
  22063. Camera.prototype._checkInputs = function () {
  22064. this.onAfterCheckInputsObservable.notifyObservers(this);
  22065. };
  22066. Object.defineProperty(Camera.prototype, "rigCameras", {
  22067. get: function () {
  22068. return this._rigCameras;
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22074. get: function () {
  22075. return this._rigPostProcess;
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. /**
  22081. * Internal, gets the first post proces.
  22082. * @returns the first post process to be run on this camera.
  22083. */
  22084. Camera.prototype._getFirstPostProcess = function () {
  22085. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22086. if (this._postProcesses[ppIndex] !== null) {
  22087. return this._postProcesses[ppIndex];
  22088. }
  22089. }
  22090. return null;
  22091. };
  22092. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22093. // invalidate framebuffer
  22094. var firstPostProcess = this._getFirstPostProcess();
  22095. if (firstPostProcess) {
  22096. firstPostProcess.markTextureDirty();
  22097. }
  22098. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22099. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22100. var cam = this._rigCameras[i];
  22101. var rigPostProcess = cam._rigPostProcess;
  22102. // for VR rig, there does not have to be a post process
  22103. if (rigPostProcess) {
  22104. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22105. if (isPass) {
  22106. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22107. cam.isIntermediate = this._postProcesses.length === 0;
  22108. }
  22109. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22110. rigPostProcess.markTextureDirty();
  22111. }
  22112. else {
  22113. cam._postProcesses = this._postProcesses.slice(0);
  22114. }
  22115. }
  22116. };
  22117. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22118. if (insertAt === void 0) { insertAt = null; }
  22119. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22120. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22121. return 0;
  22122. }
  22123. if (insertAt == null || insertAt < 0) {
  22124. this._postProcesses.push(postProcess);
  22125. }
  22126. else if (this._postProcesses[insertAt] === null) {
  22127. this._postProcesses[insertAt] = postProcess;
  22128. }
  22129. else {
  22130. this._postProcesses.splice(insertAt, 0, postProcess);
  22131. }
  22132. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22133. return this._postProcesses.indexOf(postProcess);
  22134. };
  22135. Camera.prototype.detachPostProcess = function (postProcess) {
  22136. var idx = this._postProcesses.indexOf(postProcess);
  22137. if (idx !== -1) {
  22138. this._postProcesses[idx] = null;
  22139. }
  22140. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22141. };
  22142. Camera.prototype.getWorldMatrix = function () {
  22143. if (!this._worldMatrix) {
  22144. this._worldMatrix = BABYLON.Matrix.Identity();
  22145. }
  22146. var viewMatrix = this.getViewMatrix();
  22147. viewMatrix.invertToRef(this._worldMatrix);
  22148. return this._worldMatrix;
  22149. };
  22150. Camera.prototype._getViewMatrix = function () {
  22151. return BABYLON.Matrix.Identity();
  22152. };
  22153. Camera.prototype.getViewMatrix = function (force) {
  22154. if (!force && this._isSynchronizedViewMatrix()) {
  22155. return this._computedViewMatrix;
  22156. }
  22157. this.updateCache();
  22158. this._computedViewMatrix = this._getViewMatrix();
  22159. this._currentRenderId = this.getScene().getRenderId();
  22160. this._childRenderId = this._currentRenderId;
  22161. this._refreshFrustumPlanes = true;
  22162. if (!this.parent || !this.parent.getWorldMatrix) {
  22163. this._globalPosition.copyFrom(this.position);
  22164. }
  22165. else {
  22166. if (!this._worldMatrix) {
  22167. this._worldMatrix = BABYLON.Matrix.Identity();
  22168. }
  22169. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22170. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  22171. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  22172. this._computedViewMatrix.invert();
  22173. this._markSyncedWithParent();
  22174. }
  22175. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22176. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22177. }
  22178. this.onViewMatrixChangedObservable.notifyObservers(this);
  22179. return this._computedViewMatrix;
  22180. };
  22181. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22182. this._doNotComputeProjectionMatrix = true;
  22183. if (projection !== undefined) {
  22184. this._projectionMatrix = projection;
  22185. }
  22186. };
  22187. ;
  22188. Camera.prototype.unfreezeProjectionMatrix = function () {
  22189. this._doNotComputeProjectionMatrix = false;
  22190. };
  22191. ;
  22192. Camera.prototype.getProjectionMatrix = function (force) {
  22193. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22194. return this._projectionMatrix;
  22195. }
  22196. // Cache
  22197. this._cache.mode = this.mode;
  22198. this._cache.minZ = this.minZ;
  22199. this._cache.maxZ = this.maxZ;
  22200. // Matrix
  22201. this._refreshFrustumPlanes = true;
  22202. var engine = this.getEngine();
  22203. var scene = this.getScene();
  22204. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22205. this._cache.fov = this.fov;
  22206. this._cache.fovMode = this.fovMode;
  22207. this._cache.aspectRatio = engine.getAspectRatio(this);
  22208. if (this.minZ <= 0) {
  22209. this.minZ = 0.1;
  22210. }
  22211. if (scene.useRightHandedSystem) {
  22212. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22213. }
  22214. else {
  22215. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22216. }
  22217. }
  22218. else {
  22219. var halfWidth = engine.getRenderWidth() / 2.0;
  22220. var halfHeight = engine.getRenderHeight() / 2.0;
  22221. if (scene.useRightHandedSystem) {
  22222. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22223. }
  22224. else {
  22225. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22226. }
  22227. this._cache.orthoLeft = this.orthoLeft;
  22228. this._cache.orthoRight = this.orthoRight;
  22229. this._cache.orthoBottom = this.orthoBottom;
  22230. this._cache.orthoTop = this.orthoTop;
  22231. this._cache.renderWidth = engine.getRenderWidth();
  22232. this._cache.renderHeight = engine.getRenderHeight();
  22233. }
  22234. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22235. return this._projectionMatrix;
  22236. };
  22237. Camera.prototype.getTranformationMatrix = function () {
  22238. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22239. return this._transformMatrix;
  22240. };
  22241. Camera.prototype.updateFrustumPlanes = function () {
  22242. if (!this._refreshFrustumPlanes) {
  22243. return;
  22244. }
  22245. this.getTranformationMatrix();
  22246. if (!this._frustumPlanes) {
  22247. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22248. }
  22249. else {
  22250. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22251. }
  22252. this._refreshFrustumPlanes = false;
  22253. };
  22254. Camera.prototype.isInFrustum = function (target) {
  22255. this.updateFrustumPlanes();
  22256. return target.isInFrustum(this._frustumPlanes);
  22257. };
  22258. Camera.prototype.isCompletelyInFrustum = function (target) {
  22259. this.updateFrustumPlanes();
  22260. return target.isCompletelyInFrustum(this._frustumPlanes);
  22261. };
  22262. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22263. if (length === void 0) { length = 100; }
  22264. if (!transform) {
  22265. transform = this.getWorldMatrix();
  22266. }
  22267. if (!origin) {
  22268. origin = this.position;
  22269. }
  22270. var forward = new BABYLON.Vector3(0, 0, 1);
  22271. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22272. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22273. return new BABYLON.Ray(origin, direction, length);
  22274. };
  22275. /**
  22276. * Releases resources associated with this node.
  22277. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22278. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22279. */
  22280. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22281. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22282. // Observables
  22283. this.onViewMatrixChangedObservable.clear();
  22284. this.onProjectionMatrixChangedObservable.clear();
  22285. this.onAfterCheckInputsObservable.clear();
  22286. this.onRestoreStateObservable.clear();
  22287. // Inputs
  22288. if (this.inputs) {
  22289. this.inputs.clear();
  22290. }
  22291. // Animations
  22292. this.getScene().stopAnimation(this);
  22293. // Remove from scene
  22294. this.getScene().removeCamera(this);
  22295. while (this._rigCameras.length > 0) {
  22296. var camera = this._rigCameras.pop();
  22297. if (camera) {
  22298. camera.dispose();
  22299. }
  22300. }
  22301. // Postprocesses
  22302. if (this._rigPostProcess) {
  22303. this._rigPostProcess.dispose(this);
  22304. this._rigPostProcess = null;
  22305. this._postProcesses = [];
  22306. }
  22307. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22308. this._rigPostProcess = null;
  22309. this._postProcesses = [];
  22310. }
  22311. else {
  22312. var i = this._postProcesses.length;
  22313. while (--i >= 0) {
  22314. var postProcess = this._postProcesses[i];
  22315. if (postProcess) {
  22316. postProcess.dispose(this);
  22317. }
  22318. }
  22319. }
  22320. // Render targets
  22321. var i = this.customRenderTargets.length;
  22322. while (--i >= 0) {
  22323. this.customRenderTargets[i].dispose();
  22324. }
  22325. this.customRenderTargets = [];
  22326. // Active Meshes
  22327. this._activeMeshes.dispose();
  22328. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22329. };
  22330. Object.defineProperty(Camera.prototype, "leftCamera", {
  22331. // ---- Camera rigs section ----
  22332. get: function () {
  22333. if (this._rigCameras.length < 1) {
  22334. return null;
  22335. }
  22336. return this._rigCameras[0];
  22337. },
  22338. enumerable: true,
  22339. configurable: true
  22340. });
  22341. Object.defineProperty(Camera.prototype, "rightCamera", {
  22342. get: function () {
  22343. if (this._rigCameras.length < 2) {
  22344. return null;
  22345. }
  22346. return this._rigCameras[1];
  22347. },
  22348. enumerable: true,
  22349. configurable: true
  22350. });
  22351. Camera.prototype.getLeftTarget = function () {
  22352. if (this._rigCameras.length < 1) {
  22353. return null;
  22354. }
  22355. return this._rigCameras[0].getTarget();
  22356. };
  22357. Camera.prototype.getRightTarget = function () {
  22358. if (this._rigCameras.length < 2) {
  22359. return null;
  22360. }
  22361. return this._rigCameras[1].getTarget();
  22362. };
  22363. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22364. if (this.cameraRigMode === mode) {
  22365. return;
  22366. }
  22367. while (this._rigCameras.length > 0) {
  22368. var camera = this._rigCameras.pop();
  22369. if (camera) {
  22370. camera.dispose();
  22371. }
  22372. }
  22373. this.cameraRigMode = mode;
  22374. this._cameraRigParams = {};
  22375. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22376. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22377. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22378. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22379. // create the rig cameras, unless none
  22380. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22381. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22382. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22383. if (leftCamera && rightCamera) {
  22384. this._rigCameras.push(leftCamera);
  22385. this._rigCameras.push(rightCamera);
  22386. }
  22387. }
  22388. switch (this.cameraRigMode) {
  22389. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22390. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22391. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22392. break;
  22393. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22394. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22395. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22396. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22397. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22398. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22399. break;
  22400. case Camera.RIG_MODE_VR:
  22401. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22402. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22403. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22404. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22405. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22406. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22407. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22408. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22409. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22410. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22411. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22412. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22413. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22414. if (metrics.compensateDistortion) {
  22415. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22416. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22417. }
  22418. break;
  22419. case Camera.RIG_MODE_WEBVR:
  22420. if (rigParams.vrDisplay) {
  22421. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22422. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22423. //Left eye
  22424. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22425. this._rigCameras[0].setCameraRigParameter("left", true);
  22426. //leaving this for future reference
  22427. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22428. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22429. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22430. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22431. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22432. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22433. this._rigCameras[0].parent = this;
  22434. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22435. //Right eye
  22436. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22437. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22438. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22439. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22440. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22441. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22442. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22443. this._rigCameras[1].parent = this;
  22444. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22445. if (Camera.UseAlternateWebVRRendering) {
  22446. this._rigCameras[1]._skipRendering = true;
  22447. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22448. }
  22449. }
  22450. break;
  22451. }
  22452. this._cascadePostProcessesToRigCams();
  22453. this.update();
  22454. };
  22455. Camera.prototype._getVRProjectionMatrix = function () {
  22456. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22457. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22458. return this._projectionMatrix;
  22459. };
  22460. Camera.prototype._updateCameraRotationMatrix = function () {
  22461. //Here for WebVR
  22462. };
  22463. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22464. //Here for WebVR
  22465. };
  22466. /**
  22467. * This function MUST be overwritten by the different WebVR cameras available.
  22468. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22469. */
  22470. Camera.prototype._getWebVRProjectionMatrix = function () {
  22471. return BABYLON.Matrix.Identity();
  22472. };
  22473. /**
  22474. * This function MUST be overwritten by the different WebVR cameras available.
  22475. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22476. */
  22477. Camera.prototype._getWebVRViewMatrix = function () {
  22478. return BABYLON.Matrix.Identity();
  22479. };
  22480. Camera.prototype.setCameraRigParameter = function (name, value) {
  22481. if (!this._cameraRigParams) {
  22482. this._cameraRigParams = {};
  22483. }
  22484. this._cameraRigParams[name] = value;
  22485. //provisionnally:
  22486. if (name === "interaxialDistance") {
  22487. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22488. }
  22489. };
  22490. /**
  22491. * needs to be overridden by children so sub has required properties to be copied
  22492. */
  22493. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22494. return null;
  22495. };
  22496. /**
  22497. * May need to be overridden by children
  22498. */
  22499. Camera.prototype._updateRigCameras = function () {
  22500. for (var i = 0; i < this._rigCameras.length; i++) {
  22501. this._rigCameras[i].minZ = this.minZ;
  22502. this._rigCameras[i].maxZ = this.maxZ;
  22503. this._rigCameras[i].fov = this.fov;
  22504. }
  22505. // only update viewport when ANAGLYPH
  22506. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22507. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22508. }
  22509. };
  22510. Camera.prototype._setupInputs = function () {
  22511. };
  22512. Camera.prototype.serialize = function () {
  22513. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22514. // Type
  22515. serializationObject.type = this.getClassName();
  22516. // Parent
  22517. if (this.parent) {
  22518. serializationObject.parentId = this.parent.id;
  22519. }
  22520. if (this.inputs) {
  22521. this.inputs.serialize(serializationObject);
  22522. }
  22523. // Animations
  22524. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22525. serializationObject.ranges = this.serializeAnimationRanges();
  22526. return serializationObject;
  22527. };
  22528. Camera.prototype.clone = function (name) {
  22529. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22530. };
  22531. Camera.prototype.getDirection = function (localAxis) {
  22532. var result = BABYLON.Vector3.Zero();
  22533. this.getDirectionToRef(localAxis, result);
  22534. return result;
  22535. };
  22536. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22537. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22538. };
  22539. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22540. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22541. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22542. switch (type) {
  22543. case "ArcRotateCamera":
  22544. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22545. case "DeviceOrientationCamera":
  22546. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22547. case "FollowCamera":
  22548. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22549. case "ArcFollowCamera":
  22550. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22551. case "GamepadCamera":
  22552. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22553. case "TouchCamera":
  22554. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22555. case "VirtualJoysticksCamera":
  22556. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22557. case "WebVRFreeCamera":
  22558. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22559. case "WebVRGamepadCamera":
  22560. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22561. case "VRDeviceOrientationFreeCamera":
  22562. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22563. case "VRDeviceOrientationGamepadCamera":
  22564. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22565. case "AnaglyphArcRotateCamera":
  22566. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22567. case "AnaglyphFreeCamera":
  22568. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22569. case "AnaglyphGamepadCamera":
  22570. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22571. case "AnaglyphUniversalCamera":
  22572. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22573. case "StereoscopicArcRotateCamera":
  22574. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22575. case "StereoscopicFreeCamera":
  22576. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22577. case "StereoscopicGamepadCamera":
  22578. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22579. case "StereoscopicUniversalCamera":
  22580. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22581. case "FreeCamera": // Forcing Universal here
  22582. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22583. default: // Universal Camera is the default value
  22584. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22585. }
  22586. };
  22587. Camera.prototype.computeWorldMatrix = function () {
  22588. return this.getWorldMatrix();
  22589. };
  22590. Camera.Parse = function (parsedCamera, scene) {
  22591. var type = parsedCamera.type;
  22592. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22593. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22594. // Parent
  22595. if (parsedCamera.parentId) {
  22596. camera._waitingParentId = parsedCamera.parentId;
  22597. }
  22598. //If camera has an input manager, let it parse inputs settings
  22599. if (camera.inputs) {
  22600. camera.inputs.parse(parsedCamera);
  22601. camera._setupInputs();
  22602. }
  22603. if (camera.setPosition) { // need to force position
  22604. camera.position.copyFromFloats(0, 0, 0);
  22605. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22606. }
  22607. // Target
  22608. if (parsedCamera.target) {
  22609. if (camera.setTarget) {
  22610. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22611. }
  22612. }
  22613. // Apply 3d rig, when found
  22614. if (parsedCamera.cameraRigMode) {
  22615. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22616. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22617. }
  22618. // Animations
  22619. if (parsedCamera.animations) {
  22620. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22621. var parsedAnimation = parsedCamera.animations[animationIndex];
  22622. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22623. }
  22624. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22625. }
  22626. if (parsedCamera.autoAnimate) {
  22627. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22628. }
  22629. return camera;
  22630. };
  22631. // Statics
  22632. Camera._PERSPECTIVE_CAMERA = 0;
  22633. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22634. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22635. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22636. Camera._RIG_MODE_NONE = 0;
  22637. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22638. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22639. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22640. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22641. Camera._RIG_MODE_VR = 20;
  22642. Camera._RIG_MODE_WEBVR = 21;
  22643. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22644. Camera.UseAlternateWebVRRendering = false;
  22645. __decorate([
  22646. BABYLON.serializeAsVector3()
  22647. ], Camera.prototype, "position", void 0);
  22648. __decorate([
  22649. BABYLON.serializeAsVector3()
  22650. ], Camera.prototype, "upVector", void 0);
  22651. __decorate([
  22652. BABYLON.serialize()
  22653. ], Camera.prototype, "orthoLeft", void 0);
  22654. __decorate([
  22655. BABYLON.serialize()
  22656. ], Camera.prototype, "orthoRight", void 0);
  22657. __decorate([
  22658. BABYLON.serialize()
  22659. ], Camera.prototype, "orthoBottom", void 0);
  22660. __decorate([
  22661. BABYLON.serialize()
  22662. ], Camera.prototype, "orthoTop", void 0);
  22663. __decorate([
  22664. BABYLON.serialize()
  22665. ], Camera.prototype, "fov", void 0);
  22666. __decorate([
  22667. BABYLON.serialize()
  22668. ], Camera.prototype, "minZ", void 0);
  22669. __decorate([
  22670. BABYLON.serialize()
  22671. ], Camera.prototype, "maxZ", void 0);
  22672. __decorate([
  22673. BABYLON.serialize()
  22674. ], Camera.prototype, "inertia", void 0);
  22675. __decorate([
  22676. BABYLON.serialize()
  22677. ], Camera.prototype, "mode", void 0);
  22678. __decorate([
  22679. BABYLON.serialize()
  22680. ], Camera.prototype, "layerMask", void 0);
  22681. __decorate([
  22682. BABYLON.serialize()
  22683. ], Camera.prototype, "fovMode", void 0);
  22684. __decorate([
  22685. BABYLON.serialize()
  22686. ], Camera.prototype, "cameraRigMode", void 0);
  22687. __decorate([
  22688. BABYLON.serialize()
  22689. ], Camera.prototype, "interaxialDistance", void 0);
  22690. __decorate([
  22691. BABYLON.serialize()
  22692. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22693. return Camera;
  22694. }(BABYLON.Node));
  22695. BABYLON.Camera = Camera;
  22696. })(BABYLON || (BABYLON = {}));
  22697. //# sourceMappingURL=babylon.camera.js.map
  22698. var BABYLON;
  22699. (function (BABYLON) {
  22700. var RenderingManager = /** @class */ (function () {
  22701. function RenderingManager(scene) {
  22702. this._renderingGroups = new Array();
  22703. this._autoClearDepthStencil = {};
  22704. this._customOpaqueSortCompareFn = {};
  22705. this._customAlphaTestSortCompareFn = {};
  22706. this._customTransparentSortCompareFn = {};
  22707. this._renderinGroupInfo = null;
  22708. this._scene = scene;
  22709. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22710. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22711. }
  22712. }
  22713. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22714. if (depth === void 0) { depth = true; }
  22715. if (stencil === void 0) { stencil = true; }
  22716. if (this._depthStencilBufferAlreadyCleaned) {
  22717. return;
  22718. }
  22719. this._scene.getEngine().clear(null, false, depth, stencil);
  22720. this._depthStencilBufferAlreadyCleaned = true;
  22721. };
  22722. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22723. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22724. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22725. var info = null;
  22726. if (observable) {
  22727. if (!this._renderinGroupInfo) {
  22728. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22729. }
  22730. info = this._renderinGroupInfo;
  22731. info.scene = this._scene;
  22732. info.camera = this._scene.activeCamera;
  22733. }
  22734. // Dispatch sprites
  22735. if (renderSprites) {
  22736. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22737. var manager = this._scene.spriteManagers[index];
  22738. this.dispatchSprites(manager);
  22739. }
  22740. }
  22741. // Render
  22742. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22743. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22744. var renderingGroup = this._renderingGroups[index];
  22745. if (!renderingGroup && !observable)
  22746. continue;
  22747. var renderingGroupMask = 0;
  22748. // Fire PRECLEAR stage
  22749. if (observable && info) {
  22750. renderingGroupMask = Math.pow(2, index);
  22751. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22752. info.renderingGroupId = index;
  22753. observable.notifyObservers(info, renderingGroupMask);
  22754. }
  22755. // Clear depth/stencil if needed
  22756. if (RenderingManager.AUTOCLEAR) {
  22757. var autoClear = this._autoClearDepthStencil[index];
  22758. if (autoClear && autoClear.autoClear) {
  22759. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22760. }
  22761. }
  22762. if (observable && info) {
  22763. // Fire PREOPAQUE stage
  22764. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22765. observable.notifyObservers(info, renderingGroupMask);
  22766. // Fire PRETRANSPARENT stage
  22767. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22768. observable.notifyObservers(info, renderingGroupMask);
  22769. }
  22770. if (renderingGroup)
  22771. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22772. // Fire POSTTRANSPARENT stage
  22773. if (observable && info) {
  22774. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22775. observable.notifyObservers(info, renderingGroupMask);
  22776. }
  22777. }
  22778. };
  22779. RenderingManager.prototype.reset = function () {
  22780. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22781. var renderingGroup = this._renderingGroups[index];
  22782. if (renderingGroup) {
  22783. renderingGroup.prepare();
  22784. }
  22785. }
  22786. };
  22787. RenderingManager.prototype.dispose = function () {
  22788. this.freeRenderingGroups();
  22789. this._renderingGroups.length = 0;
  22790. };
  22791. /**
  22792. * Clear the info related to rendering groups preventing retention points during dispose.
  22793. */
  22794. RenderingManager.prototype.freeRenderingGroups = function () {
  22795. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22796. var renderingGroup = this._renderingGroups[index];
  22797. if (renderingGroup) {
  22798. renderingGroup.dispose();
  22799. }
  22800. }
  22801. };
  22802. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22803. if (this._renderingGroups[renderingGroupId] === undefined) {
  22804. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22805. }
  22806. };
  22807. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22808. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22809. this._prepareRenderingGroup(renderingGroupId);
  22810. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22811. };
  22812. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22813. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22814. this._prepareRenderingGroup(renderingGroupId);
  22815. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22816. };
  22817. /**
  22818. * @param subMesh The submesh to dispatch
  22819. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22820. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22821. */
  22822. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22823. if (mesh === undefined) {
  22824. mesh = subMesh.getMesh();
  22825. }
  22826. var renderingGroupId = mesh.renderingGroupId || 0;
  22827. this._prepareRenderingGroup(renderingGroupId);
  22828. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22829. };
  22830. /**
  22831. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22832. * This allowed control for front to back rendering or reversly depending of the special needs.
  22833. *
  22834. * @param renderingGroupId The rendering group id corresponding to its index
  22835. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22836. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22837. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22838. */
  22839. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22840. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22841. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22842. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22843. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22844. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22845. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22846. if (this._renderingGroups[renderingGroupId]) {
  22847. var group = this._renderingGroups[renderingGroupId];
  22848. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22849. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22850. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22851. }
  22852. };
  22853. /**
  22854. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22855. *
  22856. * @param renderingGroupId The rendering group id corresponding to its index
  22857. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22858. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22859. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22860. */
  22861. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22862. if (depth === void 0) { depth = true; }
  22863. if (stencil === void 0) { stencil = true; }
  22864. this._autoClearDepthStencil[renderingGroupId] = {
  22865. autoClear: autoClearDepthStencil,
  22866. depth: depth,
  22867. stencil: stencil
  22868. };
  22869. };
  22870. /**
  22871. * The max id used for rendering groups (not included)
  22872. */
  22873. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22874. /**
  22875. * The min id used for rendering groups (included)
  22876. */
  22877. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22878. /**
  22879. * Used to globally prevent autoclearing scenes.
  22880. */
  22881. RenderingManager.AUTOCLEAR = true;
  22882. return RenderingManager;
  22883. }());
  22884. BABYLON.RenderingManager = RenderingManager;
  22885. })(BABYLON || (BABYLON = {}));
  22886. //# sourceMappingURL=babylon.renderingManager.js.map
  22887. var BABYLON;
  22888. (function (BABYLON) {
  22889. var RenderingGroup = /** @class */ (function () {
  22890. /**
  22891. * Creates a new rendering group.
  22892. * @param index The rendering group index
  22893. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22894. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22895. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22896. */
  22897. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22898. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22899. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22900. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22901. this.index = index;
  22902. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22903. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22904. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22905. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22906. this._particleSystems = new BABYLON.SmartArray(256);
  22907. this._spriteManagers = new BABYLON.SmartArray(256);
  22908. this._edgesRenderers = new BABYLON.SmartArray(16);
  22909. this._scene = scene;
  22910. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22911. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22912. this.transparentSortCompareFn = transparentSortCompareFn;
  22913. }
  22914. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22915. /**
  22916. * Set the opaque sort comparison function.
  22917. * If null the sub meshes will be render in the order they were created
  22918. */
  22919. set: function (value) {
  22920. this._opaqueSortCompareFn = value;
  22921. if (value) {
  22922. this._renderOpaque = this.renderOpaqueSorted;
  22923. }
  22924. else {
  22925. this._renderOpaque = RenderingGroup.renderUnsorted;
  22926. }
  22927. },
  22928. enumerable: true,
  22929. configurable: true
  22930. });
  22931. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22932. /**
  22933. * Set the alpha test sort comparison function.
  22934. * If null the sub meshes will be render in the order they were created
  22935. */
  22936. set: function (value) {
  22937. this._alphaTestSortCompareFn = value;
  22938. if (value) {
  22939. this._renderAlphaTest = this.renderAlphaTestSorted;
  22940. }
  22941. else {
  22942. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22943. }
  22944. },
  22945. enumerable: true,
  22946. configurable: true
  22947. });
  22948. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22949. /**
  22950. * Set the transparent sort comparison function.
  22951. * If null the sub meshes will be render in the order they were created
  22952. */
  22953. set: function (value) {
  22954. if (value) {
  22955. this._transparentSortCompareFn = value;
  22956. }
  22957. else {
  22958. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22959. }
  22960. this._renderTransparent = this.renderTransparentSorted;
  22961. },
  22962. enumerable: true,
  22963. configurable: true
  22964. });
  22965. /**
  22966. * Render all the sub meshes contained in the group.
  22967. * @param customRenderFunction Used to override the default render behaviour of the group.
  22968. * @returns true if rendered some submeshes.
  22969. */
  22970. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22971. if (customRenderFunction) {
  22972. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22973. return;
  22974. }
  22975. var engine = this._scene.getEngine();
  22976. // Depth only
  22977. if (this._depthOnlySubMeshes.length !== 0) {
  22978. engine.setColorWrite(false);
  22979. this._renderAlphaTest(this._depthOnlySubMeshes);
  22980. engine.setColorWrite(true);
  22981. }
  22982. // Opaque
  22983. if (this._opaqueSubMeshes.length !== 0) {
  22984. this._renderOpaque(this._opaqueSubMeshes);
  22985. }
  22986. // Alpha test
  22987. if (this._alphaTestSubMeshes.length !== 0) {
  22988. this._renderAlphaTest(this._alphaTestSubMeshes);
  22989. }
  22990. var stencilState = engine.getStencilBuffer();
  22991. engine.setStencilBuffer(false);
  22992. // Sprites
  22993. if (renderSprites) {
  22994. this._renderSprites();
  22995. }
  22996. // Particles
  22997. if (renderParticles) {
  22998. this._renderParticles(activeMeshes);
  22999. }
  23000. if (this.onBeforeTransparentRendering) {
  23001. this.onBeforeTransparentRendering();
  23002. }
  23003. // Transparent
  23004. if (this._transparentSubMeshes.length !== 0) {
  23005. this._renderTransparent(this._transparentSubMeshes);
  23006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23007. }
  23008. // Set back stencil to false in case it changes before the edge renderer.
  23009. engine.setStencilBuffer(false);
  23010. // Edges
  23011. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23012. this._edgesRenderers.data[edgesRendererIndex].render();
  23013. }
  23014. // Restore Stencil state.
  23015. engine.setStencilBuffer(stencilState);
  23016. };
  23017. /**
  23018. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23019. * @param subMeshes The submeshes to render
  23020. */
  23021. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23022. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23023. };
  23024. /**
  23025. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23026. * @param subMeshes The submeshes to render
  23027. */
  23028. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23029. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23030. };
  23031. /**
  23032. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23033. * @param subMeshes The submeshes to render
  23034. */
  23035. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23036. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23037. };
  23038. /**
  23039. * Renders the submeshes in a specified order.
  23040. * @param subMeshes The submeshes to sort before render
  23041. * @param sortCompareFn The comparison function use to sort
  23042. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23043. * @param transparent Specifies to activate blending if true
  23044. */
  23045. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23046. var subIndex = 0;
  23047. var subMesh;
  23048. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23049. for (; subIndex < subMeshes.length; subIndex++) {
  23050. subMesh = subMeshes.data[subIndex];
  23051. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23052. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23053. }
  23054. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23055. if (sortCompareFn) {
  23056. sortedArray.sort(sortCompareFn);
  23057. }
  23058. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23059. subMesh = sortedArray[subIndex];
  23060. if (transparent) {
  23061. var material = subMesh.getMaterial();
  23062. if (material && material.needDepthPrePass) {
  23063. var engine = material.getScene().getEngine();
  23064. engine.setColorWrite(false);
  23065. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23066. subMesh.render(false);
  23067. engine.setColorWrite(true);
  23068. }
  23069. }
  23070. subMesh.render(transparent);
  23071. }
  23072. };
  23073. /**
  23074. * Renders the submeshes in the order they were dispatched (no sort applied).
  23075. * @param subMeshes The submeshes to render
  23076. */
  23077. RenderingGroup.renderUnsorted = function (subMeshes) {
  23078. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23079. var submesh = subMeshes.data[subIndex];
  23080. submesh.render(false);
  23081. }
  23082. };
  23083. /**
  23084. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23085. * are rendered back to front if in the same alpha index.
  23086. *
  23087. * @param a The first submesh
  23088. * @param b The second submesh
  23089. * @returns The result of the comparison
  23090. */
  23091. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23092. // Alpha index first
  23093. if (a._alphaIndex > b._alphaIndex) {
  23094. return 1;
  23095. }
  23096. if (a._alphaIndex < b._alphaIndex) {
  23097. return -1;
  23098. }
  23099. // Then distance to camera
  23100. return RenderingGroup.backToFrontSortCompare(a, b);
  23101. };
  23102. /**
  23103. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23104. * are rendered back to front.
  23105. *
  23106. * @param a The first submesh
  23107. * @param b The second submesh
  23108. * @returns The result of the comparison
  23109. */
  23110. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23111. // Then distance to camera
  23112. if (a._distanceToCamera < b._distanceToCamera) {
  23113. return 1;
  23114. }
  23115. if (a._distanceToCamera > b._distanceToCamera) {
  23116. return -1;
  23117. }
  23118. return 0;
  23119. };
  23120. /**
  23121. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23122. * are rendered front to back (prevent overdraw).
  23123. *
  23124. * @param a The first submesh
  23125. * @param b The second submesh
  23126. * @returns The result of the comparison
  23127. */
  23128. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23129. // Then distance to camera
  23130. if (a._distanceToCamera < b._distanceToCamera) {
  23131. return -1;
  23132. }
  23133. if (a._distanceToCamera > b._distanceToCamera) {
  23134. return 1;
  23135. }
  23136. return 0;
  23137. };
  23138. /**
  23139. * Resets the different lists of submeshes to prepare a new frame.
  23140. */
  23141. RenderingGroup.prototype.prepare = function () {
  23142. this._opaqueSubMeshes.reset();
  23143. this._transparentSubMeshes.reset();
  23144. this._alphaTestSubMeshes.reset();
  23145. this._depthOnlySubMeshes.reset();
  23146. this._particleSystems.reset();
  23147. this._spriteManagers.reset();
  23148. this._edgesRenderers.reset();
  23149. };
  23150. RenderingGroup.prototype.dispose = function () {
  23151. this._opaqueSubMeshes.dispose();
  23152. this._transparentSubMeshes.dispose();
  23153. this._alphaTestSubMeshes.dispose();
  23154. this._depthOnlySubMeshes.dispose();
  23155. this._particleSystems.dispose();
  23156. this._spriteManagers.dispose();
  23157. this._edgesRenderers.dispose();
  23158. };
  23159. /**
  23160. * Inserts the submesh in its correct queue depending on its material.
  23161. * @param subMesh The submesh to dispatch
  23162. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23163. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23164. */
  23165. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23166. // Get mesh and materials if not provided
  23167. if (mesh === undefined) {
  23168. mesh = subMesh.getMesh();
  23169. }
  23170. if (material === undefined) {
  23171. material = subMesh.getMaterial();
  23172. }
  23173. if (material === null || material === undefined) {
  23174. return;
  23175. }
  23176. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23177. this._transparentSubMeshes.push(subMesh);
  23178. }
  23179. else if (material.needAlphaTesting()) { // Alpha test
  23180. if (material.needDepthPrePass) {
  23181. this._depthOnlySubMeshes.push(subMesh);
  23182. }
  23183. this._alphaTestSubMeshes.push(subMesh);
  23184. }
  23185. else {
  23186. if (material.needDepthPrePass) {
  23187. this._depthOnlySubMeshes.push(subMesh);
  23188. }
  23189. this._opaqueSubMeshes.push(subMesh); // Opaque
  23190. }
  23191. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23192. this._edgesRenderers.push(mesh._edgesRenderer);
  23193. }
  23194. };
  23195. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23196. this._spriteManagers.push(spriteManager);
  23197. };
  23198. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23199. this._particleSystems.push(particleSystem);
  23200. };
  23201. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23202. if (this._particleSystems.length === 0) {
  23203. return;
  23204. }
  23205. // Particles
  23206. var activeCamera = this._scene.activeCamera;
  23207. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23208. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23209. var particleSystem = this._particleSystems.data[particleIndex];
  23210. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23211. continue;
  23212. }
  23213. var emitter = particleSystem.emitter;
  23214. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23215. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23216. }
  23217. }
  23218. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23219. };
  23220. RenderingGroup.prototype._renderSprites = function () {
  23221. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23222. return;
  23223. }
  23224. // Sprites
  23225. var activeCamera = this._scene.activeCamera;
  23226. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23227. for (var id = 0; id < this._spriteManagers.length; id++) {
  23228. var spriteManager = this._spriteManagers.data[id];
  23229. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23230. spriteManager.render();
  23231. }
  23232. }
  23233. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23234. };
  23235. return RenderingGroup;
  23236. }());
  23237. BABYLON.RenderingGroup = RenderingGroup;
  23238. })(BABYLON || (BABYLON = {}));
  23239. //# sourceMappingURL=babylon.renderingGroup.js.map
  23240. var BABYLON;
  23241. (function (BABYLON) {
  23242. /** @ignore */
  23243. var ClickInfo = /** @class */ (function () {
  23244. function ClickInfo() {
  23245. this._singleClick = false;
  23246. this._doubleClick = false;
  23247. this._hasSwiped = false;
  23248. this._ignore = false;
  23249. }
  23250. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23251. get: function () {
  23252. return this._singleClick;
  23253. },
  23254. set: function (b) {
  23255. this._singleClick = b;
  23256. },
  23257. enumerable: true,
  23258. configurable: true
  23259. });
  23260. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23261. get: function () {
  23262. return this._doubleClick;
  23263. },
  23264. set: function (b) {
  23265. this._doubleClick = b;
  23266. },
  23267. enumerable: true,
  23268. configurable: true
  23269. });
  23270. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23271. get: function () {
  23272. return this._hasSwiped;
  23273. },
  23274. set: function (b) {
  23275. this._hasSwiped = b;
  23276. },
  23277. enumerable: true,
  23278. configurable: true
  23279. });
  23280. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23281. get: function () {
  23282. return this._ignore;
  23283. },
  23284. set: function (b) {
  23285. this._ignore = b;
  23286. },
  23287. enumerable: true,
  23288. configurable: true
  23289. });
  23290. return ClickInfo;
  23291. }());
  23292. /**
  23293. * This class is used by the onRenderingGroupObservable
  23294. */
  23295. var RenderingGroupInfo = /** @class */ (function () {
  23296. function RenderingGroupInfo() {
  23297. }
  23298. /**
  23299. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23300. * This stage will be fired no matter what
  23301. */
  23302. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23303. /**
  23304. * Called before opaque object are rendered.
  23305. * This stage will be fired only if there's 3D Opaque content to render
  23306. */
  23307. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23308. /**
  23309. * Called after the opaque objects are rendered and before the transparent ones
  23310. * This stage will be fired only if there's 3D transparent content to render
  23311. */
  23312. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23313. /**
  23314. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23315. * This stage will be fired no matter what
  23316. */
  23317. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23318. return RenderingGroupInfo;
  23319. }());
  23320. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23321. /**
  23322. * Represents a scene to be rendered by the engine.
  23323. * @see http://doc.babylonjs.com/features/scene
  23324. */
  23325. var Scene = /** @class */ (function () {
  23326. /**
  23327. * Creates a new Scene
  23328. * @param engine defines the engine to use to render this scene
  23329. */
  23330. function Scene(engine) {
  23331. // Members
  23332. /**
  23333. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23334. */
  23335. this.autoClear = true;
  23336. /**
  23337. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23338. */
  23339. this.autoClearDepthAndStencil = true;
  23340. /**
  23341. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23342. */
  23343. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23344. /**
  23345. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23346. */
  23347. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23348. this._forceWireframe = false;
  23349. this._forcePointsCloud = false;
  23350. /**
  23351. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23352. */
  23353. this.forceShowBoundingBoxes = false;
  23354. /**
  23355. * Gets or sets a boolean indicating if animations are enabled
  23356. */
  23357. this.animationsEnabled = true;
  23358. this._animationPropertiesOverride = null;
  23359. /**
  23360. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23361. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23362. */
  23363. this.useConstantAnimationDeltaTime = false;
  23364. /**
  23365. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23366. * Please note that it requires to run a ray cast through the scene on every frame
  23367. */
  23368. this.constantlyUpdateMeshUnderPointer = false;
  23369. /**
  23370. * Defines the HTML cursor to use when hovering over interactive elements
  23371. */
  23372. this.hoverCursor = "pointer";
  23373. /**
  23374. * Defines the HTML default cursor to use (empty by default)
  23375. */
  23376. this.defaultCursor = "";
  23377. /**
  23378. * This is used to call preventDefault() on pointer down
  23379. * in order to block unwanted artifacts like system double clicks
  23380. */
  23381. this.preventDefaultOnPointerDown = true;
  23382. // Metadata
  23383. /**
  23384. * Gets or sets user defined metadata
  23385. */
  23386. this.metadata = null;
  23387. /**
  23388. * Use this array to add regular expressions used to disable offline support for specific urls
  23389. */
  23390. this.disableOfflineSupportExceptionRules = new Array();
  23391. /**
  23392. * An event triggered when the scene is disposed.
  23393. */
  23394. this.onDisposeObservable = new BABYLON.Observable();
  23395. this._onDisposeObserver = null;
  23396. /**
  23397. * An event triggered before rendering the scene (right after animations and physics)
  23398. */
  23399. this.onBeforeRenderObservable = new BABYLON.Observable();
  23400. this._onBeforeRenderObserver = null;
  23401. /**
  23402. * An event triggered after rendering the scene
  23403. */
  23404. this.onAfterRenderObservable = new BABYLON.Observable();
  23405. this._onAfterRenderObserver = null;
  23406. /**
  23407. * An event triggered before animating the scene
  23408. */
  23409. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23410. /**
  23411. * An event triggered after animations processing
  23412. */
  23413. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23414. /**
  23415. * An event triggered before draw calls are ready to be sent
  23416. */
  23417. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23418. /**
  23419. * An event triggered after draw calls have been sent
  23420. */
  23421. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23422. /**
  23423. * An event triggered when physic simulation is about to be run
  23424. */
  23425. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23426. /**
  23427. * An event triggered when physic simulation has been done
  23428. */
  23429. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23430. /**
  23431. * An event triggered when the scene is ready
  23432. */
  23433. this.onReadyObservable = new BABYLON.Observable();
  23434. /**
  23435. * An event triggered before rendering a camera
  23436. */
  23437. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23438. this._onBeforeCameraRenderObserver = null;
  23439. /**
  23440. * An event triggered after rendering a camera
  23441. */
  23442. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23443. this._onAfterCameraRenderObserver = null;
  23444. /**
  23445. * An event triggered when active meshes evaluation is about to start
  23446. */
  23447. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23448. /**
  23449. * An event triggered when active meshes evaluation is done
  23450. */
  23451. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23452. /**
  23453. * An event triggered when particles rendering is about to start
  23454. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23455. */
  23456. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23457. /**
  23458. * An event triggered when particles rendering is done
  23459. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23460. */
  23461. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23462. /**
  23463. * An event triggered when sprites rendering is about to start
  23464. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23465. */
  23466. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23467. /**
  23468. * An event triggered when sprites rendering is done
  23469. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23470. */
  23471. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23472. /**
  23473. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23474. */
  23475. this.onDataLoadedObservable = new BABYLON.Observable();
  23476. /**
  23477. * An event triggered when a camera is created
  23478. */
  23479. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23480. /**
  23481. * An event triggered when a camera is removed
  23482. */
  23483. this.onCameraRemovedObservable = new BABYLON.Observable();
  23484. /**
  23485. * An event triggered when a light is created
  23486. */
  23487. this.onNewLightAddedObservable = new BABYLON.Observable();
  23488. /**
  23489. * An event triggered when a light is removed
  23490. */
  23491. this.onLightRemovedObservable = new BABYLON.Observable();
  23492. /**
  23493. * An event triggered when a geometry is created
  23494. */
  23495. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23496. /**
  23497. * An event triggered when a geometry is removed
  23498. */
  23499. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23500. /**
  23501. * An event triggered when a transform node is created
  23502. */
  23503. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23504. /**
  23505. * An event triggered when a transform node is removed
  23506. */
  23507. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23508. /**
  23509. * An event triggered when a mesh is created
  23510. */
  23511. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23512. /**
  23513. * An event triggered when a mesh is removed
  23514. */
  23515. this.onMeshRemovedObservable = new BABYLON.Observable();
  23516. /**
  23517. * An event triggered when render targets are about to be rendered
  23518. * Can happen multiple times per frame.
  23519. */
  23520. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23521. /**
  23522. * An event triggered when render targets were rendered.
  23523. * Can happen multiple times per frame.
  23524. */
  23525. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23526. /**
  23527. * An event triggered before calculating deterministic simulation step
  23528. */
  23529. this.onBeforeStepObservable = new BABYLON.Observable();
  23530. /**
  23531. * An event triggered after calculating deterministic simulation step
  23532. */
  23533. this.onAfterStepObservable = new BABYLON.Observable();
  23534. /**
  23535. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23536. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23537. * 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)
  23538. */
  23539. this.onRenderingGroupObservable = new BABYLON.Observable();
  23540. // Animations
  23541. /**
  23542. * Gets a list of Animations associated with the scene
  23543. */
  23544. this.animations = [];
  23545. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23546. /**
  23547. * 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).
  23548. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23549. */
  23550. this.onPrePointerObservable = new BABYLON.Observable();
  23551. /**
  23552. * Observable event triggered each time an input event is received from the rendering canvas
  23553. */
  23554. this.onPointerObservable = new BABYLON.Observable();
  23555. this._meshPickProceed = false;
  23556. this._currentPickResult = null;
  23557. this._previousPickResult = null;
  23558. this._totalPointersPressed = 0;
  23559. this._doubleClickOccured = false;
  23560. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23561. this.cameraToUseForPointers = null;
  23562. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23563. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23564. this._startingPointerTime = 0;
  23565. this._previousStartingPointerTime = 0;
  23566. // Deterministic lockstep
  23567. this._timeAccumulator = 0;
  23568. this._currentStepId = 0;
  23569. this._currentInternalStep = 0;
  23570. // Keyboard
  23571. /**
  23572. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23573. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23574. */
  23575. this.onPreKeyboardObservable = new BABYLON.Observable();
  23576. /**
  23577. * Observable event triggered each time an keyboard event is received from the hosting window
  23578. */
  23579. this.onKeyboardObservable = new BABYLON.Observable();
  23580. // Coordinates system
  23581. this._useRightHandedSystem = false;
  23582. // Fog
  23583. this._fogEnabled = true;
  23584. this._fogMode = Scene.FOGMODE_NONE;
  23585. /**
  23586. * Gets or sets the fog color to use
  23587. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23588. */
  23589. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23590. /**
  23591. * Gets or sets the fog density to use
  23592. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23593. */
  23594. this.fogDensity = 0.1;
  23595. /**
  23596. * Gets or sets the fog start distance to use
  23597. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23598. */
  23599. this.fogStart = 0;
  23600. /**
  23601. * Gets or sets the fog end distance to use
  23602. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23603. */
  23604. this.fogEnd = 1000.0;
  23605. // Lights
  23606. this._shadowsEnabled = true;
  23607. this._lightsEnabled = true;
  23608. /**
  23609. * All of the lights added to this scene
  23610. * @see http://doc.babylonjs.com/babylon101/lights
  23611. */
  23612. this.lights = new Array();
  23613. // Cameras
  23614. /** All of the cameras added to this scene.
  23615. * @see http://doc.babylonjs.com/babylon101/cameras
  23616. */
  23617. this.cameras = new Array();
  23618. /** All of the active cameras added to this scene. */
  23619. this.activeCameras = new Array();
  23620. // Meshes
  23621. /**
  23622. * All of the tranform nodes added to this scene
  23623. * @see http://doc.babylonjs.com/how_to/transformnode
  23624. */
  23625. this.transformNodes = new Array();
  23626. /**
  23627. * All of the (abstract) meshes added to this scene
  23628. */
  23629. this.meshes = new Array();
  23630. /**
  23631. * All of the animation groups added to this scene
  23632. * @see http://doc.babylonjs.com/how_to/group
  23633. */
  23634. this.animationGroups = new Array();
  23635. // Geometries
  23636. this._geometries = new Array();
  23637. /**
  23638. * All of the materials added to this scene
  23639. * @see http://doc.babylonjs.com/babylon101/materials
  23640. */
  23641. this.materials = new Array();
  23642. /**
  23643. * All of the multi-materials added to this scene
  23644. * @see http://doc.babylonjs.com/how_to/multi_materials
  23645. */
  23646. this.multiMaterials = new Array();
  23647. // Textures
  23648. this._texturesEnabled = true;
  23649. /**
  23650. * All of the textures added to this scene
  23651. */
  23652. this.textures = new Array();
  23653. // Particles
  23654. /**
  23655. * Gets or sets a boolean indicating if particles are enabled on this scene
  23656. */
  23657. this.particlesEnabled = true;
  23658. /**
  23659. * All of the particle systems added to this scene
  23660. * @see http://doc.babylonjs.com/babylon101/particles
  23661. */
  23662. this.particleSystems = new Array();
  23663. // Sprites
  23664. /**
  23665. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23666. */
  23667. this.spritesEnabled = true;
  23668. /**
  23669. * All of the sprite managers added to this scene
  23670. * @see http://doc.babylonjs.com/babylon101/sprites
  23671. */
  23672. this.spriteManagers = new Array();
  23673. /**
  23674. * The list of layers (background and foreground) of the scene
  23675. */
  23676. this.layers = new Array();
  23677. /**
  23678. * The list of effect layers (highlights/glow) added to the scene
  23679. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23680. * @see http://doc.babylonjs.com/how_to/glow_layer
  23681. */
  23682. this.effectLayers = new Array();
  23683. // Skeletons
  23684. this._skeletonsEnabled = true;
  23685. /**
  23686. * The list of skeletons added to the scene
  23687. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23688. */
  23689. this.skeletons = new Array();
  23690. // Morph targets
  23691. /**
  23692. * The list of morph target managers added to the scene
  23693. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23694. */
  23695. this.morphTargetManagers = new Array();
  23696. // Lens flares
  23697. /**
  23698. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23699. */
  23700. this.lensFlaresEnabled = true;
  23701. /**
  23702. * The list of lens flare system added to the scene
  23703. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23704. */
  23705. this.lensFlareSystems = new Array();
  23706. // Collisions
  23707. /**
  23708. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23709. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23710. */
  23711. this.collisionsEnabled = true;
  23712. /**
  23713. * Defines the gravity applied to this scene (used only for collisions)
  23714. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23715. */
  23716. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23717. // Postprocesses
  23718. /**
  23719. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23720. */
  23721. this.postProcessesEnabled = true;
  23722. /**
  23723. * The list of postprocesses added to the scene
  23724. */
  23725. this.postProcesses = new Array();
  23726. // Customs render targets
  23727. /**
  23728. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23729. */
  23730. this.renderTargetsEnabled = true;
  23731. /**
  23732. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23733. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23734. */
  23735. this.dumpNextRenderTargets = false;
  23736. /**
  23737. * The list of user defined render targets added to the scene
  23738. */
  23739. this.customRenderTargets = new Array();
  23740. /**
  23741. * Gets the list of meshes imported to the scene through SceneLoader
  23742. */
  23743. this.importedMeshesFiles = new Array();
  23744. // Probes
  23745. /**
  23746. * Gets or sets a boolean indicating if probes are enabled on this scene
  23747. */
  23748. this.probesEnabled = true;
  23749. /**
  23750. * The list of reflection probes added to the scene
  23751. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23752. */
  23753. this.reflectionProbes = new Array();
  23754. /** @ignore */
  23755. this._actionManagers = new Array();
  23756. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23757. // Procedural textures
  23758. /**
  23759. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23760. */
  23761. this.proceduralTexturesEnabled = true;
  23762. /**
  23763. * The list of procedural textures added to the scene
  23764. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23765. */
  23766. this.proceduralTextures = new Array();
  23767. /**
  23768. * The list of sound tracks added to the scene
  23769. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23770. */
  23771. this.soundTracks = new Array();
  23772. this._audioEnabled = true;
  23773. this._headphone = false;
  23774. // Performance counters
  23775. this._totalVertices = new BABYLON.PerfCounter();
  23776. /** @ignore */
  23777. this._activeIndices = new BABYLON.PerfCounter();
  23778. /** @ignore */
  23779. this._activeParticles = new BABYLON.PerfCounter();
  23780. /** @ignore */
  23781. this._activeBones = new BABYLON.PerfCounter();
  23782. this._animationTime = 0;
  23783. /**
  23784. * Gets or sets a general scale for animation speed
  23785. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23786. */
  23787. this.animationTimeScale = 1;
  23788. this._renderId = 0;
  23789. this._executeWhenReadyTimeoutId = -1;
  23790. this._intermediateRendering = false;
  23791. this._viewUpdateFlag = -1;
  23792. this._projectionUpdateFlag = -1;
  23793. this._alternateViewUpdateFlag = -1;
  23794. this._alternateProjectionUpdateFlag = -1;
  23795. /** @ignore */
  23796. this._toBeDisposed = new BABYLON.SmartArray(256);
  23797. this._activeRequests = new Array();
  23798. this._pendingData = new Array();
  23799. this._isDisposed = false;
  23800. /**
  23801. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23802. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23803. */
  23804. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23805. this._activeMeshes = new BABYLON.SmartArray(256);
  23806. this._processedMaterials = new BABYLON.SmartArray(256);
  23807. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23808. /** @ignore */
  23809. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23810. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23811. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23812. /** @ignore */
  23813. this._activeAnimatables = new Array();
  23814. this._transformMatrix = BABYLON.Matrix.Zero();
  23815. this._useAlternateCameraConfiguration = false;
  23816. this._alternateRendering = false;
  23817. /**
  23818. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23819. * This is useful if there are more lights that the maximum simulteanous authorized
  23820. */
  23821. this.requireLightSorting = false;
  23822. this._depthRenderer = {};
  23823. this._activeMeshesFrozen = false;
  23824. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23825. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23826. this._engine.scenes.push(this);
  23827. this._uid = null;
  23828. this._renderingManager = new BABYLON.RenderingManager(this);
  23829. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23830. if (BABYLON.OutlineRenderer) {
  23831. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23832. }
  23833. if (BABYLON.Tools.IsWindowObjectExist()) {
  23834. this.attachControl();
  23835. }
  23836. //simplification queue
  23837. if (BABYLON.SimplificationQueue) {
  23838. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23839. }
  23840. //collision coordinator initialization. For now legacy per default.
  23841. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23842. // Uniform Buffer
  23843. this._createUbo();
  23844. // Default Image processing definition.
  23845. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23846. }
  23847. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23848. /** The fog is deactivated */
  23849. get: function () {
  23850. return Scene._FOGMODE_NONE;
  23851. },
  23852. enumerable: true,
  23853. configurable: true
  23854. });
  23855. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23856. /** The fog density is following an exponential function */
  23857. get: function () {
  23858. return Scene._FOGMODE_EXP;
  23859. },
  23860. enumerable: true,
  23861. configurable: true
  23862. });
  23863. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23864. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23865. get: function () {
  23866. return Scene._FOGMODE_EXP2;
  23867. },
  23868. enumerable: true,
  23869. configurable: true
  23870. });
  23871. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23872. /** The fog density is following a linear function. */
  23873. get: function () {
  23874. return Scene._FOGMODE_LINEAR;
  23875. },
  23876. enumerable: true,
  23877. configurable: true
  23878. });
  23879. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23880. /**
  23881. * Texture used in all pbr material as the reflection texture.
  23882. * As in the majority of the scene they are the same (exception for multi room and so on),
  23883. * this is easier to reference from here than from all the materials.
  23884. */
  23885. get: function () {
  23886. return this._environmentTexture;
  23887. },
  23888. /**
  23889. * Texture used in all pbr material as the reflection texture.
  23890. * As in the majority of the scene they are the same (exception for multi room and so on),
  23891. * this is easier to set here than in all the materials.
  23892. */
  23893. set: function (value) {
  23894. if (this._environmentTexture === value) {
  23895. return;
  23896. }
  23897. this._environmentTexture = value;
  23898. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23899. },
  23900. enumerable: true,
  23901. configurable: true
  23902. });
  23903. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23904. /**
  23905. * Default image processing configuration used either in the rendering
  23906. * Forward main pass or through the imageProcessingPostProcess if present.
  23907. * As in the majority of the scene they are the same (exception for multi camera),
  23908. * this is easier to reference from here than from all the materials and post process.
  23909. *
  23910. * No setter as we it is a shared configuration, you can set the values instead.
  23911. */
  23912. get: function () {
  23913. return this._imageProcessingConfiguration;
  23914. },
  23915. enumerable: true,
  23916. configurable: true
  23917. });
  23918. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23919. get: function () {
  23920. return this._forceWireframe;
  23921. },
  23922. /**
  23923. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23924. */
  23925. set: function (value) {
  23926. if (this._forceWireframe === value) {
  23927. return;
  23928. }
  23929. this._forceWireframe = value;
  23930. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23931. },
  23932. enumerable: true,
  23933. configurable: true
  23934. });
  23935. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23936. get: function () {
  23937. return this._forcePointsCloud;
  23938. },
  23939. /**
  23940. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23941. */
  23942. set: function (value) {
  23943. if (this._forcePointsCloud === value) {
  23944. return;
  23945. }
  23946. this._forcePointsCloud = value;
  23947. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23948. },
  23949. enumerable: true,
  23950. configurable: true
  23951. });
  23952. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  23953. /**
  23954. * Gets or sets the animation properties override
  23955. */
  23956. get: function () {
  23957. return this._animationPropertiesOverride;
  23958. },
  23959. set: function (value) {
  23960. this._animationPropertiesOverride = value;
  23961. },
  23962. enumerable: true,
  23963. configurable: true
  23964. });
  23965. Object.defineProperty(Scene.prototype, "onDispose", {
  23966. /** Sets a function to be executed when this scene is disposed. */
  23967. set: function (callback) {
  23968. if (this._onDisposeObserver) {
  23969. this.onDisposeObservable.remove(this._onDisposeObserver);
  23970. }
  23971. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23972. },
  23973. enumerable: true,
  23974. configurable: true
  23975. });
  23976. Object.defineProperty(Scene.prototype, "beforeRender", {
  23977. /** Sets a function to be executed before rendering this scene */
  23978. set: function (callback) {
  23979. if (this._onBeforeRenderObserver) {
  23980. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23981. }
  23982. if (callback) {
  23983. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23984. }
  23985. },
  23986. enumerable: true,
  23987. configurable: true
  23988. });
  23989. Object.defineProperty(Scene.prototype, "afterRender", {
  23990. /** Sets a function to be executed after rendering this scene */
  23991. set: function (callback) {
  23992. if (this._onAfterRenderObserver) {
  23993. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23994. }
  23995. if (callback) {
  23996. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23997. }
  23998. },
  23999. enumerable: true,
  24000. configurable: true
  24001. });
  24002. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24003. /** Sets a function to be executed before rendering a camera*/
  24004. set: function (callback) {
  24005. if (this._onBeforeCameraRenderObserver) {
  24006. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24007. }
  24008. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24009. },
  24010. enumerable: true,
  24011. configurable: true
  24012. });
  24013. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24014. /** Sets a function to be executed after rendering a camera*/
  24015. set: function (callback) {
  24016. if (this._onAfterCameraRenderObserver) {
  24017. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24018. }
  24019. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24020. },
  24021. enumerable: true,
  24022. configurable: true
  24023. });
  24024. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24025. /**
  24026. * Gets the gamepad manager associated with the scene
  24027. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24028. */
  24029. get: function () {
  24030. if (!this._gamepadManager) {
  24031. this._gamepadManager = new BABYLON.GamepadManager(this);
  24032. }
  24033. return this._gamepadManager;
  24034. },
  24035. enumerable: true,
  24036. configurable: true
  24037. });
  24038. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24039. /**
  24040. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24041. */
  24042. get: function () {
  24043. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24044. },
  24045. enumerable: true,
  24046. configurable: true
  24047. });
  24048. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24049. get: function () {
  24050. return this._useRightHandedSystem;
  24051. },
  24052. /**
  24053. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24054. */
  24055. set: function (value) {
  24056. if (this._useRightHandedSystem === value) {
  24057. return;
  24058. }
  24059. this._useRightHandedSystem = value;
  24060. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24061. },
  24062. enumerable: true,
  24063. configurable: true
  24064. });
  24065. /**
  24066. * Sets the step Id used by deterministic lock step
  24067. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24068. * @param newStepId defines the step Id
  24069. */
  24070. Scene.prototype.setStepId = function (newStepId) {
  24071. this._currentStepId = newStepId;
  24072. };
  24073. ;
  24074. /**
  24075. * Gets the step Id used by deterministic lock step
  24076. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24077. * @returns the step Id
  24078. */
  24079. Scene.prototype.getStepId = function () {
  24080. return this._currentStepId;
  24081. };
  24082. ;
  24083. /**
  24084. * Gets the internal step used by deterministic lock step
  24085. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24086. * @returns the internal step
  24087. */
  24088. Scene.prototype.getInternalStep = function () {
  24089. return this._currentInternalStep;
  24090. };
  24091. ;
  24092. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24093. get: function () {
  24094. return this._fogEnabled;
  24095. },
  24096. /**
  24097. * Gets or sets a boolean indicating if fog is enabled on this scene
  24098. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24099. */
  24100. set: function (value) {
  24101. if (this._fogEnabled === value) {
  24102. return;
  24103. }
  24104. this._fogEnabled = value;
  24105. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24106. },
  24107. enumerable: true,
  24108. configurable: true
  24109. });
  24110. Object.defineProperty(Scene.prototype, "fogMode", {
  24111. get: function () {
  24112. return this._fogMode;
  24113. },
  24114. /**
  24115. * Gets or sets the fog mode to use
  24116. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24117. */
  24118. set: function (value) {
  24119. if (this._fogMode === value) {
  24120. return;
  24121. }
  24122. this._fogMode = value;
  24123. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24124. },
  24125. enumerable: true,
  24126. configurable: true
  24127. });
  24128. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24129. get: function () {
  24130. return this._shadowsEnabled;
  24131. },
  24132. /**
  24133. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24134. */
  24135. set: function (value) {
  24136. if (this._shadowsEnabled === value) {
  24137. return;
  24138. }
  24139. this._shadowsEnabled = value;
  24140. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24146. get: function () {
  24147. return this._lightsEnabled;
  24148. },
  24149. /**
  24150. * Gets or sets a boolean indicating if lights are enabled on this scene
  24151. */
  24152. set: function (value) {
  24153. if (this._lightsEnabled === value) {
  24154. return;
  24155. }
  24156. this._lightsEnabled = value;
  24157. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24158. },
  24159. enumerable: true,
  24160. configurable: true
  24161. });
  24162. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24163. /** The default material used on meshes when no material is affected */
  24164. get: function () {
  24165. if (!this._defaultMaterial) {
  24166. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24167. }
  24168. return this._defaultMaterial;
  24169. },
  24170. /** The default material used on meshes when no material is affected */
  24171. set: function (value) {
  24172. this._defaultMaterial = value;
  24173. },
  24174. enumerable: true,
  24175. configurable: true
  24176. });
  24177. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24178. get: function () {
  24179. return this._texturesEnabled;
  24180. },
  24181. /**
  24182. * Gets or sets a boolean indicating if textures are enabled on this scene
  24183. */
  24184. set: function (value) {
  24185. if (this._texturesEnabled === value) {
  24186. return;
  24187. }
  24188. this._texturesEnabled = value;
  24189. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24190. },
  24191. enumerable: true,
  24192. configurable: true
  24193. });
  24194. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24195. get: function () {
  24196. return this._skeletonsEnabled;
  24197. },
  24198. /**
  24199. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24200. */
  24201. set: function (value) {
  24202. if (this._skeletonsEnabled === value) {
  24203. return;
  24204. }
  24205. this._skeletonsEnabled = value;
  24206. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24207. },
  24208. enumerable: true,
  24209. configurable: true
  24210. });
  24211. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24212. /**
  24213. * Gets the postprocess render pipeline manager
  24214. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24215. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24216. */
  24217. get: function () {
  24218. if (!this._postProcessRenderPipelineManager) {
  24219. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24220. }
  24221. return this._postProcessRenderPipelineManager;
  24222. },
  24223. enumerable: true,
  24224. configurable: true
  24225. });
  24226. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24227. /**
  24228. * Gets the main soundtrack associated with the scene
  24229. */
  24230. get: function () {
  24231. if (!this._mainSoundTrack) {
  24232. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24233. }
  24234. return this._mainSoundTrack;
  24235. },
  24236. enumerable: true,
  24237. configurable: true
  24238. });
  24239. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24240. /** @ignore */
  24241. get: function () {
  24242. return this._alternateRendering;
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24248. /**
  24249. * Gets the list of frustum planes (built from the active camera)
  24250. */
  24251. get: function () {
  24252. return this._frustumPlanes;
  24253. },
  24254. enumerable: true,
  24255. configurable: true
  24256. });
  24257. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24258. /**
  24259. * Gets the current geometry buffer associated to the scene.
  24260. */
  24261. get: function () {
  24262. return this._geometryBufferRenderer;
  24263. },
  24264. /**
  24265. * Sets the current geometry buffer for the scene.
  24266. */
  24267. set: function (geometryBufferRenderer) {
  24268. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24269. this._geometryBufferRenderer = geometryBufferRenderer;
  24270. }
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. Object.defineProperty(Scene.prototype, "debugLayer", {
  24276. /**
  24277. * Gets the debug layer associated with the scene
  24278. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24279. */
  24280. get: function () {
  24281. if (!this._debugLayer) {
  24282. this._debugLayer = new BABYLON.DebugLayer(this);
  24283. }
  24284. return this._debugLayer;
  24285. },
  24286. enumerable: true,
  24287. configurable: true
  24288. });
  24289. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24290. /**
  24291. * Gets a boolean indicating if collisions are processed on a web worker
  24292. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24293. */
  24294. get: function () {
  24295. return this._workerCollisions;
  24296. },
  24297. set: function (enabled) {
  24298. if (!BABYLON.CollisionCoordinatorLegacy) {
  24299. return;
  24300. }
  24301. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24302. this._workerCollisions = enabled;
  24303. if (this.collisionCoordinator) {
  24304. this.collisionCoordinator.destroy();
  24305. }
  24306. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24307. this.collisionCoordinator.init(this);
  24308. },
  24309. enumerable: true,
  24310. configurable: true
  24311. });
  24312. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24313. /**
  24314. * Gets the octree used to boost mesh selection (picking)
  24315. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24316. */
  24317. get: function () {
  24318. return this._selectionOctree;
  24319. },
  24320. enumerable: true,
  24321. configurable: true
  24322. });
  24323. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24324. /**
  24325. * Gets the mesh that is currently under the pointer
  24326. */
  24327. get: function () {
  24328. return this._pointerOverMesh;
  24329. },
  24330. enumerable: true,
  24331. configurable: true
  24332. });
  24333. Object.defineProperty(Scene.prototype, "pointerX", {
  24334. /**
  24335. * Gets the current on-screen X position of the pointer
  24336. */
  24337. get: function () {
  24338. return this._pointerX;
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. Object.defineProperty(Scene.prototype, "pointerY", {
  24344. /**
  24345. * Gets the current on-screen Y position of the pointer
  24346. */
  24347. get: function () {
  24348. return this._pointerY;
  24349. },
  24350. enumerable: true,
  24351. configurable: true
  24352. });
  24353. /**
  24354. * Gets the cached material (ie. the latest rendered one)
  24355. * @returns the cached material
  24356. */
  24357. Scene.prototype.getCachedMaterial = function () {
  24358. return this._cachedMaterial;
  24359. };
  24360. /**
  24361. * Gets the cached effect (ie. the latest rendered one)
  24362. * @returns the cached effect
  24363. */
  24364. Scene.prototype.getCachedEffect = function () {
  24365. return this._cachedEffect;
  24366. };
  24367. /**
  24368. * Gets the cached visibility state (ie. the latest rendered one)
  24369. * @returns the cached visibility state
  24370. */
  24371. Scene.prototype.getCachedVisibility = function () {
  24372. return this._cachedVisibility;
  24373. };
  24374. /**
  24375. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24376. * @param material defines the current material
  24377. * @param effect defines the current effect
  24378. * @param visibility defines the current visibility state
  24379. * @returns true if one parameter is not cached
  24380. */
  24381. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24382. if (visibility === void 0) { visibility = 1; }
  24383. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24384. };
  24385. /**
  24386. * Gets the bounding box renderer associated with the scene
  24387. * @returns a BoundingBoxRenderer
  24388. */
  24389. Scene.prototype.getBoundingBoxRenderer = function () {
  24390. if (!this._boundingBoxRenderer) {
  24391. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24392. }
  24393. return this._boundingBoxRenderer;
  24394. };
  24395. /**
  24396. * Gets the outline renderer associated with the scene
  24397. * @returns a OutlineRenderer
  24398. */
  24399. Scene.prototype.getOutlineRenderer = function () {
  24400. return this._outlineRenderer;
  24401. };
  24402. /**
  24403. * Gets the engine associated with the scene
  24404. * @returns an Engine
  24405. */
  24406. Scene.prototype.getEngine = function () {
  24407. return this._engine;
  24408. };
  24409. /**
  24410. * Gets the total number of vertices rendered per frame
  24411. * @returns the total number of vertices rendered per frame
  24412. */
  24413. Scene.prototype.getTotalVertices = function () {
  24414. return this._totalVertices.current;
  24415. };
  24416. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24417. /**
  24418. * Gets the performance counter for total vertices
  24419. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24420. */
  24421. get: function () {
  24422. return this._totalVertices;
  24423. },
  24424. enumerable: true,
  24425. configurable: true
  24426. });
  24427. /**
  24428. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24429. * @returns the total number of active indices rendered per frame
  24430. */
  24431. Scene.prototype.getActiveIndices = function () {
  24432. return this._activeIndices.current;
  24433. };
  24434. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24435. /**
  24436. * Gets the performance counter for active indices
  24437. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24438. */
  24439. get: function () {
  24440. return this._activeIndices;
  24441. },
  24442. enumerable: true,
  24443. configurable: true
  24444. });
  24445. /**
  24446. * Gets the total number of active particles rendered per frame
  24447. * @returns the total number of active particles rendered per frame
  24448. */
  24449. Scene.prototype.getActiveParticles = function () {
  24450. return this._activeParticles.current;
  24451. };
  24452. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24453. /**
  24454. * Gets the performance counter for active particles
  24455. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24456. */
  24457. get: function () {
  24458. return this._activeParticles;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. /**
  24464. * Gets the total number of active bones rendered per frame
  24465. * @returns the total number of active bones rendered per frame
  24466. */
  24467. Scene.prototype.getActiveBones = function () {
  24468. return this._activeBones.current;
  24469. };
  24470. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24471. /**
  24472. * Gets the performance counter for active bones
  24473. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24474. */
  24475. get: function () {
  24476. return this._activeBones;
  24477. },
  24478. enumerable: true,
  24479. configurable: true
  24480. });
  24481. /** @ignore */
  24482. Scene.prototype.getInterFramePerfCounter = function () {
  24483. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24484. return 0;
  24485. };
  24486. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24487. /** @ignore */
  24488. get: function () {
  24489. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24490. return null;
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. /** @ignore */
  24496. Scene.prototype.getLastFrameDuration = function () {
  24497. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24498. return 0;
  24499. };
  24500. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24501. /** @ignore */
  24502. get: function () {
  24503. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24504. return null;
  24505. },
  24506. enumerable: true,
  24507. configurable: true
  24508. });
  24509. /** @ignore */
  24510. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24511. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24512. return 0;
  24513. };
  24514. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24515. /** @ignore */
  24516. get: function () {
  24517. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24518. return null;
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. /**
  24524. * Gets the array of active meshes
  24525. * @returns an array of AbstractMesh
  24526. */
  24527. Scene.prototype.getActiveMeshes = function () {
  24528. return this._activeMeshes;
  24529. };
  24530. /** @ignore */
  24531. Scene.prototype.getRenderTargetsDuration = function () {
  24532. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24533. return 0;
  24534. };
  24535. /** @ignore */
  24536. Scene.prototype.getRenderDuration = function () {
  24537. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24538. return 0;
  24539. };
  24540. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24541. /** @ignore */
  24542. get: function () {
  24543. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24544. return null;
  24545. },
  24546. enumerable: true,
  24547. configurable: true
  24548. });
  24549. /** @ignore */
  24550. Scene.prototype.getParticlesDuration = function () {
  24551. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24552. return 0;
  24553. };
  24554. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24555. /** @ignore */
  24556. get: function () {
  24557. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24558. return null;
  24559. },
  24560. enumerable: true,
  24561. configurable: true
  24562. });
  24563. /** @ignore */
  24564. Scene.prototype.getSpritesDuration = function () {
  24565. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24566. return 0;
  24567. };
  24568. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24569. /** @ignore */
  24570. get: function () {
  24571. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24572. return null;
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. /**
  24578. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24579. * @returns a number
  24580. */
  24581. Scene.prototype.getAnimationRatio = function () {
  24582. return this._animationRatio;
  24583. };
  24584. /**
  24585. * Gets an unique Id for the current frame
  24586. * @returns a number
  24587. */
  24588. Scene.prototype.getRenderId = function () {
  24589. return this._renderId;
  24590. };
  24591. /** Call this function if you want to manually increment the render Id*/
  24592. Scene.prototype.incrementRenderId = function () {
  24593. this._renderId++;
  24594. };
  24595. Scene.prototype._updatePointerPosition = function (evt) {
  24596. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24597. if (!canvasRect) {
  24598. return;
  24599. }
  24600. this._pointerX = evt.clientX - canvasRect.left;
  24601. this._pointerY = evt.clientY - canvasRect.top;
  24602. this._unTranslatedPointerX = this._pointerX;
  24603. this._unTranslatedPointerY = this._pointerY;
  24604. };
  24605. Scene.prototype._createUbo = function () {
  24606. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24607. this._sceneUbo.addUniform("viewProjection", 16);
  24608. this._sceneUbo.addUniform("view", 16);
  24609. };
  24610. Scene.prototype._createAlternateUbo = function () {
  24611. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24612. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24613. this._alternateSceneUbo.addUniform("view", 16);
  24614. };
  24615. // Pointers handling
  24616. /**
  24617. * Use this method to simulate a pointer move on a mesh
  24618. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24619. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24620. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24621. * @returns the current scene
  24622. */
  24623. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24624. var evt = new PointerEvent("pointermove", pointerEventInit);
  24625. return this._processPointerMove(pickResult, evt);
  24626. };
  24627. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24628. var canvas = this._engine.getRenderingCanvas();
  24629. if (!canvas) {
  24630. return this;
  24631. }
  24632. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24633. this.setPointerOverSprite(null);
  24634. this.setPointerOverMesh(pickResult.pickedMesh);
  24635. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24636. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24637. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24638. }
  24639. else {
  24640. canvas.style.cursor = this.hoverCursor;
  24641. }
  24642. }
  24643. else {
  24644. canvas.style.cursor = this.defaultCursor;
  24645. }
  24646. }
  24647. else {
  24648. this.setPointerOverMesh(null);
  24649. // Sprites
  24650. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24651. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24652. this.setPointerOverSprite(pickResult.pickedSprite);
  24653. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24654. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24655. }
  24656. else {
  24657. canvas.style.cursor = this.hoverCursor;
  24658. }
  24659. }
  24660. else {
  24661. this.setPointerOverSprite(null);
  24662. // Restore pointer
  24663. canvas.style.cursor = this.defaultCursor;
  24664. }
  24665. }
  24666. if (pickResult) {
  24667. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24668. if (this.onPointerMove) {
  24669. this.onPointerMove(evt, pickResult, type);
  24670. }
  24671. if (this.onPointerObservable.hasObservers()) {
  24672. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24673. this.onPointerObservable.notifyObservers(pi, type);
  24674. }
  24675. }
  24676. return this;
  24677. };
  24678. /**
  24679. * Use this method to simulate a pointer down on a mesh
  24680. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24681. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24682. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24683. * @returns the current scene
  24684. */
  24685. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24686. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24687. return this._processPointerDown(pickResult, evt);
  24688. };
  24689. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24690. var _this = this;
  24691. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24692. this._pickedDownMesh = pickResult.pickedMesh;
  24693. var actionManager = pickResult.pickedMesh.actionManager;
  24694. if (actionManager) {
  24695. if (actionManager.hasPickTriggers) {
  24696. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24697. switch (evt.button) {
  24698. case 0:
  24699. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24700. break;
  24701. case 1:
  24702. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24703. break;
  24704. case 2:
  24705. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24706. break;
  24707. }
  24708. }
  24709. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24710. window.setTimeout(function () {
  24711. 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);
  24712. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24713. if (_this._totalPointersPressed !== 0 &&
  24714. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24715. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24716. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24717. _this._startingPointerTime = 0;
  24718. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24719. }
  24720. }
  24721. }, Scene.LongPressDelay);
  24722. }
  24723. }
  24724. }
  24725. if (pickResult) {
  24726. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24727. if (this.onPointerDown) {
  24728. this.onPointerDown(evt, pickResult, type);
  24729. }
  24730. if (this.onPointerObservable.hasObservers()) {
  24731. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24732. this.onPointerObservable.notifyObservers(pi, type);
  24733. }
  24734. }
  24735. return this;
  24736. };
  24737. /**
  24738. * Use this method to simulate a pointer up on a mesh
  24739. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24740. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24741. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24742. * @returns the current scene
  24743. */
  24744. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24745. var evt = new PointerEvent("pointerup", pointerEventInit);
  24746. var clickInfo = new ClickInfo();
  24747. clickInfo.singleClick = true;
  24748. clickInfo.ignore = true;
  24749. return this._processPointerUp(pickResult, evt, clickInfo);
  24750. };
  24751. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24752. if (pickResult && pickResult && pickResult.pickedMesh) {
  24753. this._pickedUpMesh = pickResult.pickedMesh;
  24754. if (this._pickedDownMesh === this._pickedUpMesh) {
  24755. if (this.onPointerPick) {
  24756. this.onPointerPick(evt, pickResult);
  24757. }
  24758. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24759. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24760. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24761. this.onPointerObservable.notifyObservers(pi, type_1);
  24762. }
  24763. }
  24764. if (pickResult.pickedMesh.actionManager) {
  24765. if (clickInfo.ignore) {
  24766. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24767. }
  24768. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24769. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24770. }
  24771. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24772. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24773. }
  24774. }
  24775. }
  24776. if (this._pickedDownMesh &&
  24777. this._pickedDownMesh.actionManager &&
  24778. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24779. this._pickedDownMesh !== this._pickedUpMesh) {
  24780. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24781. }
  24782. var type = BABYLON.PointerEventTypes.POINTERUP;
  24783. if (this.onPointerObservable.hasObservers()) {
  24784. if (!clickInfo.ignore) {
  24785. if (!clickInfo.hasSwiped) {
  24786. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24787. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24788. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24789. this.onPointerObservable.notifyObservers(pi, type_2);
  24790. }
  24791. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24792. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24793. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24794. this.onPointerObservable.notifyObservers(pi, type_3);
  24795. }
  24796. }
  24797. }
  24798. else {
  24799. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24800. this.onPointerObservable.notifyObservers(pi, type);
  24801. }
  24802. }
  24803. if (this.onPointerUp) {
  24804. this.onPointerUp(evt, pickResult, type);
  24805. }
  24806. return this;
  24807. };
  24808. /**
  24809. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24810. * @param attachUp defines if you want to attach events to pointerup
  24811. * @param attachDown defines if you want to attach events to pointerdown
  24812. * @param attachMove defines if you want to attach events to pointermove
  24813. */
  24814. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24815. var _this = this;
  24816. if (attachUp === void 0) { attachUp = true; }
  24817. if (attachDown === void 0) { attachDown = true; }
  24818. if (attachMove === void 0) { attachMove = true; }
  24819. this._initActionManager = function (act, clickInfo) {
  24820. if (!_this._meshPickProceed) {
  24821. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24822. _this._currentPickResult = pickResult;
  24823. if (pickResult) {
  24824. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24825. }
  24826. _this._meshPickProceed = true;
  24827. }
  24828. return act;
  24829. };
  24830. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24831. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24832. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24833. btn !== _this._previousButtonPressed) {
  24834. _this._doubleClickOccured = false;
  24835. clickInfo.singleClick = true;
  24836. clickInfo.ignore = false;
  24837. cb(clickInfo, _this._currentPickResult);
  24838. }
  24839. };
  24840. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24841. var clickInfo = new ClickInfo();
  24842. _this._currentPickResult = null;
  24843. var act = null;
  24844. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24845. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24846. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24847. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24848. act = _this._initActionManager(act, clickInfo);
  24849. if (act)
  24850. checkPicking = act.hasPickTriggers;
  24851. }
  24852. if (checkPicking) {
  24853. var btn = evt.button;
  24854. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24855. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24856. if (!clickInfo.hasSwiped) {
  24857. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24858. if (!checkSingleClickImmediately) {
  24859. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24860. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24861. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24862. act = _this._initActionManager(act, clickInfo);
  24863. if (act)
  24864. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24865. }
  24866. }
  24867. if (checkSingleClickImmediately) {
  24868. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24869. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24870. btn !== _this._previousButtonPressed) {
  24871. clickInfo.singleClick = true;
  24872. cb(clickInfo, _this._currentPickResult);
  24873. }
  24874. }
  24875. // at least one double click is required to be check and exclusive double click is enabled
  24876. else {
  24877. // wait that no double click has been raised during the double click delay
  24878. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24879. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24880. }
  24881. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24882. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24883. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24884. act = _this._initActionManager(act, clickInfo);
  24885. if (act)
  24886. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24887. }
  24888. if (checkDoubleClick) {
  24889. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24890. if (btn === _this._previousButtonPressed &&
  24891. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24892. !_this._doubleClickOccured) {
  24893. // pointer has not moved for 2 clicks, it's a double click
  24894. if (!clickInfo.hasSwiped &&
  24895. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24896. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24897. _this._previousStartingPointerTime = 0;
  24898. _this._doubleClickOccured = true;
  24899. clickInfo.doubleClick = true;
  24900. clickInfo.ignore = false;
  24901. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24902. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24903. }
  24904. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24905. cb(clickInfo, _this._currentPickResult);
  24906. }
  24907. // if the two successive clicks are too far, it's just two simple clicks
  24908. else {
  24909. _this._doubleClickOccured = false;
  24910. _this._previousStartingPointerTime = _this._startingPointerTime;
  24911. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24912. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24913. _this._previousButtonPressed = btn;
  24914. if (Scene.ExclusiveDoubleClickMode) {
  24915. if (_this._previousDelayedSimpleClickTimeout) {
  24916. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24917. }
  24918. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24919. cb(clickInfo, _this._previousPickResult);
  24920. }
  24921. else {
  24922. cb(clickInfo, _this._currentPickResult);
  24923. }
  24924. }
  24925. }
  24926. // just the first click of the double has been raised
  24927. else {
  24928. _this._doubleClickOccured = false;
  24929. _this._previousStartingPointerTime = _this._startingPointerTime;
  24930. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24931. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24932. _this._previousButtonPressed = btn;
  24933. }
  24934. }
  24935. }
  24936. }
  24937. clickInfo.ignore = true;
  24938. cb(clickInfo, _this._currentPickResult);
  24939. };
  24940. this._spritePredicate = function (sprite) {
  24941. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24942. };
  24943. this._onPointerMove = function (evt) {
  24944. _this._updatePointerPosition(evt);
  24945. // PreObservable support
  24946. if (_this.onPrePointerObservable.hasObservers()) {
  24947. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24948. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24949. _this.onPrePointerObservable.notifyObservers(pi, type);
  24950. if (pi.skipOnPointerObservable) {
  24951. return;
  24952. }
  24953. }
  24954. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24955. return;
  24956. }
  24957. if (!_this.pointerMovePredicate) {
  24958. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24959. }
  24960. // Meshes
  24961. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24962. _this._processPointerMove(pickResult, evt);
  24963. };
  24964. this._onPointerDown = function (evt) {
  24965. _this._totalPointersPressed++;
  24966. _this._pickedDownMesh = null;
  24967. _this._meshPickProceed = false;
  24968. _this._updatePointerPosition(evt);
  24969. if (_this.preventDefaultOnPointerDown && canvas) {
  24970. evt.preventDefault();
  24971. canvas.focus();
  24972. }
  24973. // PreObservable support
  24974. if (_this.onPrePointerObservable.hasObservers()) {
  24975. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24976. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24977. _this.onPrePointerObservable.notifyObservers(pi, type);
  24978. if (pi.skipOnPointerObservable) {
  24979. return;
  24980. }
  24981. }
  24982. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24983. return;
  24984. }
  24985. _this._startingPointerPosition.x = _this._pointerX;
  24986. _this._startingPointerPosition.y = _this._pointerY;
  24987. _this._startingPointerTime = Date.now();
  24988. if (!_this.pointerDownPredicate) {
  24989. _this.pointerDownPredicate = function (mesh) {
  24990. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24991. };
  24992. }
  24993. // Meshes
  24994. _this._pickedDownMesh = null;
  24995. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24996. _this._processPointerDown(pickResult, evt);
  24997. // Sprites
  24998. _this._pickedDownSprite = null;
  24999. if (_this.spriteManagers.length > 0) {
  25000. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25001. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25002. if (pickResult.pickedSprite.actionManager) {
  25003. _this._pickedDownSprite = pickResult.pickedSprite;
  25004. switch (evt.button) {
  25005. case 0:
  25006. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25007. break;
  25008. case 1:
  25009. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25010. break;
  25011. case 2:
  25012. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25013. break;
  25014. }
  25015. if (pickResult.pickedSprite.actionManager) {
  25016. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25017. }
  25018. }
  25019. }
  25020. }
  25021. };
  25022. this._onPointerUp = function (evt) {
  25023. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25024. return; // So we need to test it the pointer down was pressed before.
  25025. }
  25026. _this._totalPointersPressed--;
  25027. _this._pickedUpMesh = null;
  25028. _this._meshPickProceed = false;
  25029. _this._updatePointerPosition(evt);
  25030. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25031. // PreObservable support
  25032. if (_this.onPrePointerObservable.hasObservers()) {
  25033. if (!clickInfo.ignore) {
  25034. if (!clickInfo.hasSwiped) {
  25035. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25036. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25037. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25038. _this.onPrePointerObservable.notifyObservers(pi, type);
  25039. if (pi.skipOnPointerObservable) {
  25040. return;
  25041. }
  25042. }
  25043. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25044. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25045. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25046. _this.onPrePointerObservable.notifyObservers(pi, type);
  25047. if (pi.skipOnPointerObservable) {
  25048. return;
  25049. }
  25050. }
  25051. }
  25052. }
  25053. else {
  25054. var type = BABYLON.PointerEventTypes.POINTERUP;
  25055. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25056. _this.onPrePointerObservable.notifyObservers(pi, type);
  25057. if (pi.skipOnPointerObservable) {
  25058. return;
  25059. }
  25060. }
  25061. }
  25062. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25063. return;
  25064. }
  25065. if (!_this.pointerUpPredicate) {
  25066. _this.pointerUpPredicate = function (mesh) {
  25067. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25068. };
  25069. }
  25070. // Meshes
  25071. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25072. _this._initActionManager(null, clickInfo);
  25073. }
  25074. if (!pickResult) {
  25075. pickResult = _this._currentPickResult;
  25076. }
  25077. _this._processPointerUp(pickResult, evt, clickInfo);
  25078. // Sprites
  25079. if (_this.spriteManagers.length > 0) {
  25080. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25081. if (spritePickResult) {
  25082. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25083. if (spritePickResult.pickedSprite.actionManager) {
  25084. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25085. if (spritePickResult.pickedSprite.actionManager) {
  25086. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25087. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25088. }
  25089. }
  25090. }
  25091. }
  25092. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25093. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25094. }
  25095. }
  25096. }
  25097. _this._previousPickResult = _this._currentPickResult;
  25098. });
  25099. };
  25100. this._onKeyDown = function (evt) {
  25101. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25102. if (_this.onPreKeyboardObservable.hasObservers()) {
  25103. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25104. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25105. if (pi.skipOnPointerObservable) {
  25106. return;
  25107. }
  25108. }
  25109. if (_this.onKeyboardObservable.hasObservers()) {
  25110. var pi = new BABYLON.KeyboardInfo(type, evt);
  25111. _this.onKeyboardObservable.notifyObservers(pi, type);
  25112. }
  25113. if (_this.actionManager) {
  25114. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25115. }
  25116. };
  25117. this._onKeyUp = function (evt) {
  25118. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25119. if (_this.onPreKeyboardObservable.hasObservers()) {
  25120. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25121. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25122. if (pi.skipOnPointerObservable) {
  25123. return;
  25124. }
  25125. }
  25126. if (_this.onKeyboardObservable.hasObservers()) {
  25127. var pi = new BABYLON.KeyboardInfo(type, evt);
  25128. _this.onKeyboardObservable.notifyObservers(pi, type);
  25129. }
  25130. if (_this.actionManager) {
  25131. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25132. }
  25133. };
  25134. var engine = this.getEngine();
  25135. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25136. if (!canvas) {
  25137. return;
  25138. }
  25139. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25140. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25141. });
  25142. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25143. if (!canvas) {
  25144. return;
  25145. }
  25146. canvas.removeEventListener("keydown", _this._onKeyDown);
  25147. canvas.removeEventListener("keyup", _this._onKeyUp);
  25148. });
  25149. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25150. var canvas = this._engine.getRenderingCanvas();
  25151. if (!canvas) {
  25152. return;
  25153. }
  25154. if (attachMove) {
  25155. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25156. // Wheel
  25157. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25158. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25159. }
  25160. if (attachDown) {
  25161. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25162. }
  25163. if (attachUp) {
  25164. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25165. }
  25166. canvas.tabIndex = 1;
  25167. };
  25168. /** Detaches all event handlers*/
  25169. Scene.prototype.detachControl = function () {
  25170. var engine = this.getEngine();
  25171. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25172. var canvas = engine.getRenderingCanvas();
  25173. if (!canvas) {
  25174. return;
  25175. }
  25176. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25177. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25178. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25179. if (this._onCanvasBlurObserver) {
  25180. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25181. }
  25182. if (this._onCanvasFocusObserver) {
  25183. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25184. }
  25185. // Wheel
  25186. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25187. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25188. // Keyboard
  25189. canvas.removeEventListener("keydown", this._onKeyDown);
  25190. canvas.removeEventListener("keyup", this._onKeyUp);
  25191. // Observables
  25192. this.onKeyboardObservable.clear();
  25193. this.onPreKeyboardObservable.clear();
  25194. this.onPointerObservable.clear();
  25195. this.onPrePointerObservable.clear();
  25196. };
  25197. /**
  25198. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25199. * Delay loaded resources are not taking in account
  25200. * @return true if all required resources are ready
  25201. */
  25202. Scene.prototype.isReady = function () {
  25203. if (this._isDisposed) {
  25204. return false;
  25205. }
  25206. if (this._pendingData.length > 0) {
  25207. return false;
  25208. }
  25209. var index;
  25210. var engine = this.getEngine();
  25211. // Geometries
  25212. for (index = 0; index < this._geometries.length; index++) {
  25213. var geometry = this._geometries[index];
  25214. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25215. return false;
  25216. }
  25217. }
  25218. // Meshes
  25219. for (index = 0; index < this.meshes.length; index++) {
  25220. var mesh = this.meshes[index];
  25221. if (!mesh.isEnabled()) {
  25222. continue;
  25223. }
  25224. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25225. continue;
  25226. }
  25227. if (!mesh.isReady(true)) {
  25228. return false;
  25229. }
  25230. // Effect layers
  25231. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25232. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25233. var layer = _a[_i];
  25234. if (!layer.hasMesh(mesh)) {
  25235. continue;
  25236. }
  25237. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25238. var subMesh = _c[_b];
  25239. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25240. return false;
  25241. }
  25242. }
  25243. }
  25244. }
  25245. // Post-processes
  25246. if (this.activeCameras && this.activeCameras.length > 0) {
  25247. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25248. var camera = _e[_d];
  25249. if (!camera.isReady(true)) {
  25250. return false;
  25251. }
  25252. }
  25253. }
  25254. else if (this.activeCamera) {
  25255. if (!this.activeCamera.isReady(true)) {
  25256. return false;
  25257. }
  25258. }
  25259. // Particles
  25260. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25261. var particleSystem = _g[_f];
  25262. if (!particleSystem.isReady()) {
  25263. return false;
  25264. }
  25265. }
  25266. return true;
  25267. };
  25268. /** Resets all cached information relative to material (including effect and visibility) */
  25269. Scene.prototype.resetCachedMaterial = function () {
  25270. this._cachedMaterial = null;
  25271. this._cachedEffect = null;
  25272. this._cachedVisibility = null;
  25273. };
  25274. /**
  25275. * Registers a function to be called before every frame render
  25276. * @param func defines the function to register
  25277. */
  25278. Scene.prototype.registerBeforeRender = function (func) {
  25279. this.onBeforeRenderObservable.add(func);
  25280. };
  25281. /**
  25282. * Unregisters a function called before every frame render
  25283. * @param func defines the function to unregister
  25284. */
  25285. Scene.prototype.unregisterBeforeRender = function (func) {
  25286. this.onBeforeRenderObservable.removeCallback(func);
  25287. };
  25288. /**
  25289. * Registers a function to be called after every frame render
  25290. * @param func defines the function to register
  25291. */
  25292. Scene.prototype.registerAfterRender = function (func) {
  25293. this.onAfterRenderObservable.add(func);
  25294. };
  25295. /**
  25296. * Unregisters a function called after every frame render
  25297. * @param func defines the function to unregister
  25298. */
  25299. Scene.prototype.unregisterAfterRender = function (func) {
  25300. this.onAfterRenderObservable.removeCallback(func);
  25301. };
  25302. Scene.prototype._executeOnceBeforeRender = function (func) {
  25303. var _this = this;
  25304. var execFunc = function () {
  25305. func();
  25306. setTimeout(function () {
  25307. _this.unregisterBeforeRender(execFunc);
  25308. });
  25309. };
  25310. this.registerBeforeRender(execFunc);
  25311. };
  25312. /**
  25313. * The provided function will run before render once and will be disposed afterwards.
  25314. * A timeout delay can be provided so that the function will be executed in N ms.
  25315. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25316. * @param func The function to be executed.
  25317. * @param timeout optional delay in ms
  25318. */
  25319. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25320. var _this = this;
  25321. if (timeout !== undefined) {
  25322. setTimeout(function () {
  25323. _this._executeOnceBeforeRender(func);
  25324. }, timeout);
  25325. }
  25326. else {
  25327. this._executeOnceBeforeRender(func);
  25328. }
  25329. };
  25330. /** @ignore */
  25331. Scene.prototype._addPendingData = function (data) {
  25332. this._pendingData.push(data);
  25333. };
  25334. /** @ignore */
  25335. Scene.prototype._removePendingData = function (data) {
  25336. var wasLoading = this.isLoading;
  25337. var index = this._pendingData.indexOf(data);
  25338. if (index !== -1) {
  25339. this._pendingData.splice(index, 1);
  25340. }
  25341. if (wasLoading && !this.isLoading) {
  25342. this.onDataLoadedObservable.notifyObservers(this);
  25343. }
  25344. };
  25345. /**
  25346. * Returns the number of items waiting to be loaded
  25347. * @returns the number of items waiting to be loaded
  25348. */
  25349. Scene.prototype.getWaitingItemsCount = function () {
  25350. return this._pendingData.length;
  25351. };
  25352. Object.defineProperty(Scene.prototype, "isLoading", {
  25353. /**
  25354. * Returns a boolean indicating if the scene is still loading data
  25355. */
  25356. get: function () {
  25357. return this._pendingData.length > 0;
  25358. },
  25359. enumerable: true,
  25360. configurable: true
  25361. });
  25362. /**
  25363. * Registers a function to be executed when the scene is ready
  25364. * @param {Function} func - the function to be executed
  25365. */
  25366. Scene.prototype.executeWhenReady = function (func) {
  25367. var _this = this;
  25368. this.onReadyObservable.add(func);
  25369. if (this._executeWhenReadyTimeoutId !== -1) {
  25370. return;
  25371. }
  25372. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25373. _this._checkIsReady();
  25374. }, 150);
  25375. };
  25376. /**
  25377. * Returns a promise that resolves when the scene is ready
  25378. * @returns A promise that resolves when the scene is ready
  25379. */
  25380. Scene.prototype.whenReadyAsync = function () {
  25381. var _this = this;
  25382. return new Promise(function (resolve) {
  25383. _this.executeWhenReady(function () {
  25384. resolve();
  25385. });
  25386. });
  25387. };
  25388. /** @ignore */
  25389. Scene.prototype._checkIsReady = function () {
  25390. var _this = this;
  25391. if (this.isReady()) {
  25392. this.onReadyObservable.notifyObservers(this);
  25393. this.onReadyObservable.clear();
  25394. this._executeWhenReadyTimeoutId = -1;
  25395. return;
  25396. }
  25397. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25398. _this._checkIsReady();
  25399. }, 150);
  25400. };
  25401. // Animations
  25402. /**
  25403. * Will start the animation sequence of a given target
  25404. * @param target defines the target
  25405. * @param from defines from which frame should animation start
  25406. * @param to defines until which frame should animation run.
  25407. * @param weight defines the weight to apply to the animation (1.0 by default)
  25408. * @param loop defines if the animation loops
  25409. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25410. * @param onAnimationEnd defines the function to be executed when the animation ends
  25411. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25412. * @returns the animatable object created for this animation
  25413. */
  25414. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25415. if (weight === void 0) { weight = 1.0; }
  25416. if (speedRatio === void 0) { speedRatio = 1.0; }
  25417. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25418. returnedAnimatable.weight = weight;
  25419. return returnedAnimatable;
  25420. };
  25421. /**
  25422. * Will start the animation sequence of a given target
  25423. * @param target defines the target
  25424. * @param from defines from which frame should animation start
  25425. * @param to defines until which frame should animation run.
  25426. * @param loop defines if the animation loops
  25427. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25428. * @param onAnimationEnd defines the function to be executed when the animation ends
  25429. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25430. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25431. * @returns the animatable object created for this animation
  25432. */
  25433. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25434. if (speedRatio === void 0) { speedRatio = 1.0; }
  25435. if (stopCurrent === void 0) { stopCurrent = true; }
  25436. if (from > to && speedRatio > 0) {
  25437. speedRatio *= -1;
  25438. }
  25439. if (stopCurrent) {
  25440. this.stopAnimation(target);
  25441. }
  25442. if (!animatable) {
  25443. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25444. }
  25445. // Local animations
  25446. if (target.animations) {
  25447. animatable.appendAnimations(target, target.animations);
  25448. }
  25449. // Children animations
  25450. if (target.getAnimatables) {
  25451. var animatables = target.getAnimatables();
  25452. for (var index = 0; index < animatables.length; index++) {
  25453. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25454. }
  25455. }
  25456. animatable.reset();
  25457. return animatable;
  25458. };
  25459. /**
  25460. * Begin a new animation on a given node
  25461. * @param target defines the target where the animation will take place
  25462. * @param animations defines the list of animations to start
  25463. * @param from defines the initial value
  25464. * @param to defines the final value
  25465. * @param loop defines if you want animation to loop (off by default)
  25466. * @param speedRatio defines the speed ratio to apply to all animations
  25467. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25468. * @returns the list of created animatables
  25469. */
  25470. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25471. if (speedRatio === undefined) {
  25472. speedRatio = 1.0;
  25473. }
  25474. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25475. return animatable;
  25476. };
  25477. /**
  25478. * Begin a new animation on a given node and its hierarchy
  25479. * @param target defines the root node where the animation will take place
  25480. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25481. * @param animations defines the list of animations to start
  25482. * @param from defines the initial value
  25483. * @param to defines the final value
  25484. * @param loop defines if you want animation to loop (off by default)
  25485. * @param speedRatio defines the speed ratio to apply to all animations
  25486. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25487. * @returns the list of animatables created for all nodes
  25488. */
  25489. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25490. var children = target.getDescendants(directDescendantsOnly);
  25491. var result = [];
  25492. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25493. var child = children_1[_i];
  25494. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25495. }
  25496. return result;
  25497. };
  25498. /**
  25499. * Gets the animatable associated with a specific target
  25500. * @param target defines the target of the animatable
  25501. * @returns the required animatable if found
  25502. */
  25503. Scene.prototype.getAnimatableByTarget = function (target) {
  25504. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25505. if (this._activeAnimatables[index].target === target) {
  25506. return this._activeAnimatables[index];
  25507. }
  25508. }
  25509. return null;
  25510. };
  25511. /**
  25512. * Gets all animatables associated with a given target
  25513. * @param target defines the target to look animatables for
  25514. * @returns an array of Animatables
  25515. */
  25516. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25517. var result = [];
  25518. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25519. if (this._activeAnimatables[index].target === target) {
  25520. result.push(this._activeAnimatables[index]);
  25521. }
  25522. }
  25523. return result;
  25524. };
  25525. Object.defineProperty(Scene.prototype, "animatables", {
  25526. /**
  25527. * Gets all animatable attached to the scene
  25528. */
  25529. get: function () {
  25530. return this._activeAnimatables;
  25531. },
  25532. enumerable: true,
  25533. configurable: true
  25534. });
  25535. /**
  25536. * Will stop the animation of the given target
  25537. * @param target - the target
  25538. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25539. */
  25540. Scene.prototype.stopAnimation = function (target, animationName) {
  25541. var animatables = this.getAllAnimatablesByTarget(target);
  25542. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25543. var animatable = animatables_1[_i];
  25544. animatable.stop(animationName);
  25545. }
  25546. };
  25547. /**
  25548. * Stops and removes all animations that have been applied to the scene
  25549. */
  25550. Scene.prototype.stopAllAnimations = function () {
  25551. if (this._activeAnimatables) {
  25552. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25553. this._activeAnimatables[i].stop();
  25554. }
  25555. this._activeAnimatables = [];
  25556. }
  25557. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25558. var group = _a[_i];
  25559. group.stop();
  25560. }
  25561. };
  25562. Scene.prototype._animate = function () {
  25563. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25564. return;
  25565. }
  25566. // Getting time
  25567. var now = BABYLON.Tools.Now;
  25568. if (!this._animationTimeLast) {
  25569. if (this._pendingData.length > 0) {
  25570. return;
  25571. }
  25572. this._animationTimeLast = now;
  25573. }
  25574. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25575. this._animationTime += deltaTime;
  25576. this._animationTimeLast = now;
  25577. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25578. this._activeAnimatables[index]._animate(this._animationTime);
  25579. }
  25580. // Late animation bindings
  25581. this._processLateAnimationBindings();
  25582. };
  25583. /** @ignore */
  25584. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25585. var target = runtimeAnimation.target;
  25586. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25587. if (!target._lateAnimationHolders) {
  25588. target._lateAnimationHolders = {};
  25589. }
  25590. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25591. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25592. totalWeight: 0,
  25593. animations: []
  25594. };
  25595. }
  25596. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25597. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25598. };
  25599. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25600. var normalizer = 1.0;
  25601. var finalPosition = BABYLON.Tmp.Vector3[0];
  25602. var finalScaling = BABYLON.Tmp.Vector3[1];
  25603. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25604. var startIndex = 0;
  25605. var originalAnimation = holder.animations[0];
  25606. var scale = 1;
  25607. if (holder.totalWeight < 1.0) {
  25608. // We need to mix the original value in
  25609. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25610. scale = 1.0 - holder.totalWeight;
  25611. }
  25612. else {
  25613. startIndex = 1;
  25614. // We need to normalize the weights
  25615. normalizer = holder.totalWeight;
  25616. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25617. scale = originalAnimation.weight / normalizer;
  25618. if (scale == 1) {
  25619. return originalAnimation.currentValue;
  25620. }
  25621. }
  25622. finalScaling.scaleInPlace(scale);
  25623. finalPosition.scaleInPlace(scale);
  25624. finalQuaternion.scaleInPlace(scale);
  25625. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25626. var runtimeAnimation = holder.animations[animIndex];
  25627. var scale = runtimeAnimation.weight / normalizer;
  25628. var currentPosition = BABYLON.Tmp.Vector3[2];
  25629. var currentScaling = BABYLON.Tmp.Vector3[3];
  25630. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25631. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25632. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25633. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25634. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25635. }
  25636. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25637. return originalAnimation._workValue;
  25638. };
  25639. Scene.prototype._processLateAnimationBindings = function () {
  25640. if (!this._registeredForLateAnimationBindings.length) {
  25641. return;
  25642. }
  25643. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25644. var target = this._registeredForLateAnimationBindings.data[index];
  25645. for (var path in target._lateAnimationHolders) {
  25646. var holder = target._lateAnimationHolders[path];
  25647. var originalAnimation = holder.animations[0];
  25648. var originalValue = originalAnimation.originalValue;
  25649. var finalTarget = originalAnimation.target;
  25650. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25651. var finalValue = void 0;
  25652. if (matrixDecomposeMode) {
  25653. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25654. }
  25655. else {
  25656. var startIndex = 0;
  25657. var normalizer = 1.0;
  25658. if (holder.totalWeight < 1.0) {
  25659. // We need to mix the original value in
  25660. if (originalValue.scale) {
  25661. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25662. }
  25663. else {
  25664. finalValue = originalValue * (1.0 - holder.totalWeight);
  25665. }
  25666. }
  25667. else {
  25668. // We need to normalize the weights
  25669. normalizer = holder.totalWeight;
  25670. var scale_1 = originalAnimation.weight / normalizer;
  25671. if (scale_1 !== 1) {
  25672. if (originalAnimation.currentValue.scale) {
  25673. finalValue = originalAnimation.currentValue.scale(scale_1);
  25674. }
  25675. else {
  25676. finalValue = originalAnimation.currentValue * scale_1;
  25677. }
  25678. }
  25679. else {
  25680. finalValue = originalAnimation.currentValue;
  25681. }
  25682. startIndex = 1;
  25683. }
  25684. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25685. var runtimeAnimation = holder.animations[animIndex];
  25686. var scale = runtimeAnimation.weight / normalizer;
  25687. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25688. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25689. }
  25690. else {
  25691. finalValue += runtimeAnimation.currentValue * scale;
  25692. }
  25693. }
  25694. }
  25695. finalTarget[path] = finalValue;
  25696. }
  25697. target._lateAnimationHolders = {};
  25698. }
  25699. this._registeredForLateAnimationBindings.reset();
  25700. };
  25701. // Matrix
  25702. /** @ignore */
  25703. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25704. this._useAlternateCameraConfiguration = active;
  25705. };
  25706. /**
  25707. * Gets the current view matrix
  25708. * @returns a Matrix
  25709. */
  25710. Scene.prototype.getViewMatrix = function () {
  25711. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25712. };
  25713. /**
  25714. * Gets the current projection matrix
  25715. * @returns a Matrix
  25716. */
  25717. Scene.prototype.getProjectionMatrix = function () {
  25718. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25719. };
  25720. /**
  25721. * Gets the current transform matrix
  25722. * @returns a Matrix made of View * Projection
  25723. */
  25724. Scene.prototype.getTransformMatrix = function () {
  25725. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25726. };
  25727. /**
  25728. * Sets the current transform matrix
  25729. * @param view defines the View matrix to use
  25730. * @param projection defines the Projection matrix to use
  25731. */
  25732. Scene.prototype.setTransformMatrix = function (view, projection) {
  25733. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25734. return;
  25735. }
  25736. this._viewUpdateFlag = view.updateFlag;
  25737. this._projectionUpdateFlag = projection.updateFlag;
  25738. this._viewMatrix = view;
  25739. this._projectionMatrix = projection;
  25740. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25741. // Update frustum
  25742. if (!this._frustumPlanes) {
  25743. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25744. }
  25745. else {
  25746. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25747. }
  25748. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25749. var otherCamera = this.activeCamera._alternateCamera;
  25750. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25751. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25752. }
  25753. if (this._sceneUbo.useUbo) {
  25754. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25755. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25756. this._sceneUbo.update();
  25757. }
  25758. };
  25759. /** @ignore */
  25760. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25761. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25762. return;
  25763. }
  25764. this._alternateViewUpdateFlag = view.updateFlag;
  25765. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25766. this._alternateViewMatrix = view;
  25767. this._alternateProjectionMatrix = projection;
  25768. if (!this._alternateTransformMatrix) {
  25769. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25770. }
  25771. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25772. if (!this._alternateSceneUbo) {
  25773. this._createAlternateUbo();
  25774. }
  25775. if (this._alternateSceneUbo.useUbo) {
  25776. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25777. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25778. this._alternateSceneUbo.update();
  25779. }
  25780. };
  25781. /**
  25782. * Gets the uniform buffer used to store scene data
  25783. * @returns a UniformBuffer
  25784. */
  25785. Scene.prototype.getSceneUniformBuffer = function () {
  25786. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25787. };
  25788. /**
  25789. * Gets an unique (relatively to the current scene) Id
  25790. * @returns an unique number for the scene
  25791. */
  25792. Scene.prototype.getUniqueId = function () {
  25793. var result = Scene._uniqueIdCounter;
  25794. Scene._uniqueIdCounter++;
  25795. return result;
  25796. };
  25797. /**
  25798. * Add a mesh to the list of scene's meshes
  25799. * @param newMesh defines the mesh to add
  25800. */
  25801. Scene.prototype.addMesh = function (newMesh) {
  25802. this.meshes.push(newMesh);
  25803. //notify the collision coordinator
  25804. if (this.collisionCoordinator) {
  25805. this.collisionCoordinator.onMeshAdded(newMesh);
  25806. }
  25807. newMesh._resyncLightSources();
  25808. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25809. };
  25810. /**
  25811. * Remove a mesh for the list of scene's meshes
  25812. * @param toRemove defines the mesh to remove
  25813. * @returns the index where the mesh was in the mesh list
  25814. */
  25815. Scene.prototype.removeMesh = function (toRemove) {
  25816. var index = this.meshes.indexOf(toRemove);
  25817. if (index !== -1) {
  25818. // Remove from the scene if mesh found
  25819. this.meshes.splice(index, 1);
  25820. }
  25821. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25822. return index;
  25823. };
  25824. /**
  25825. * Add a transform node to the list of scene's transform nodes
  25826. * @param newTransformNode defines the transform node to add
  25827. */
  25828. Scene.prototype.addTransformNode = function (newTransformNode) {
  25829. this.transformNodes.push(newTransformNode);
  25830. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25831. };
  25832. /**
  25833. * Remove a transform node for the list of scene's transform nodes
  25834. * @param toRemove defines the transform node to remove
  25835. * @returns the index where the transform node was in the transform node list
  25836. */
  25837. Scene.prototype.removeTransformNode = function (toRemove) {
  25838. var index = this.transformNodes.indexOf(toRemove);
  25839. if (index !== -1) {
  25840. // Remove from the scene if found
  25841. this.transformNodes.splice(index, 1);
  25842. }
  25843. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25844. return index;
  25845. };
  25846. /**
  25847. * Remove a skeleton for the list of scene's skeletons
  25848. * @param toRemove defines the skeleton to remove
  25849. * @returns the index where the skeleton was in the skeleton list
  25850. */
  25851. Scene.prototype.removeSkeleton = function (toRemove) {
  25852. var index = this.skeletons.indexOf(toRemove);
  25853. if (index !== -1) {
  25854. // Remove from the scene if found
  25855. this.skeletons.splice(index, 1);
  25856. }
  25857. return index;
  25858. };
  25859. /**
  25860. * Remove a morph target for the list of scene's morph targets
  25861. * @param toRemove defines the morph target to remove
  25862. * @returns the index where the morph target was in the morph target list
  25863. */
  25864. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25865. var index = this.morphTargetManagers.indexOf(toRemove);
  25866. if (index !== -1) {
  25867. // Remove from the scene if found
  25868. this.morphTargetManagers.splice(index, 1);
  25869. }
  25870. return index;
  25871. };
  25872. /**
  25873. * Remove a light for the list of scene's lights
  25874. * @param toRemove defines the light to remove
  25875. * @returns the index where the light was in the light list
  25876. */
  25877. Scene.prototype.removeLight = function (toRemove) {
  25878. var index = this.lights.indexOf(toRemove);
  25879. if (index !== -1) {
  25880. // Remove from meshes
  25881. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25882. var mesh = _a[_i];
  25883. mesh._removeLightSource(toRemove);
  25884. }
  25885. // Remove from the scene if mesh found
  25886. this.lights.splice(index, 1);
  25887. this.sortLightsByPriority();
  25888. }
  25889. this.onLightRemovedObservable.notifyObservers(toRemove);
  25890. return index;
  25891. };
  25892. /**
  25893. * Remove a camera for the list of scene's cameras
  25894. * @param toRemove defines the camera to remove
  25895. * @returns the index where the camera was in the camera list
  25896. */
  25897. Scene.prototype.removeCamera = function (toRemove) {
  25898. var index = this.cameras.indexOf(toRemove);
  25899. if (index !== -1) {
  25900. // Remove from the scene if mesh found
  25901. this.cameras.splice(index, 1);
  25902. }
  25903. // Remove from activeCameras
  25904. var index2 = this.activeCameras.indexOf(toRemove);
  25905. if (index2 !== -1) {
  25906. // Remove from the scene if mesh found
  25907. this.activeCameras.splice(index2, 1);
  25908. }
  25909. // Reset the activeCamera
  25910. if (this.activeCamera === toRemove) {
  25911. if (this.cameras.length > 0) {
  25912. this.activeCamera = this.cameras[0];
  25913. }
  25914. else {
  25915. this.activeCamera = null;
  25916. }
  25917. }
  25918. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25919. return index;
  25920. };
  25921. /**
  25922. * Remove a particle system for the list of scene's particle systems
  25923. * @param toRemove defines the particle system to remove
  25924. * @returns the index where the particle system was in the particle system list
  25925. */
  25926. Scene.prototype.removeParticleSystem = function (toRemove) {
  25927. var index = this.particleSystems.indexOf(toRemove);
  25928. if (index !== -1) {
  25929. this.particleSystems.splice(index, 1);
  25930. }
  25931. return index;
  25932. };
  25933. /**
  25934. * Remove a animation for the list of scene's animations
  25935. * @param toRemove defines the animation to remove
  25936. * @returns the index where the animation was in the animation list
  25937. */
  25938. Scene.prototype.removeAnimation = function (toRemove) {
  25939. var index = this.animations.indexOf(toRemove);
  25940. if (index !== -1) {
  25941. this.animations.splice(index, 1);
  25942. }
  25943. return index;
  25944. };
  25945. /**
  25946. * Removes the given animation group from this scene.
  25947. * @param toRemove The animation group to remove
  25948. * @returns The index of the removed animation group
  25949. */
  25950. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25951. var index = this.animationGroups.indexOf(toRemove);
  25952. if (index !== -1) {
  25953. this.animationGroups.splice(index, 1);
  25954. }
  25955. return index;
  25956. };
  25957. /**
  25958. * Removes the given multi-material from this scene.
  25959. * @param toRemove The multi-material to remove
  25960. * @returns The index of the removed multi-material
  25961. */
  25962. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25963. var index = this.multiMaterials.indexOf(toRemove);
  25964. if (index !== -1) {
  25965. this.multiMaterials.splice(index, 1);
  25966. }
  25967. return index;
  25968. };
  25969. /**
  25970. * Removes the given material from this scene.
  25971. * @param toRemove The material to remove
  25972. * @returns The index of the removed material
  25973. */
  25974. Scene.prototype.removeMaterial = function (toRemove) {
  25975. var index = this.materials.indexOf(toRemove);
  25976. if (index !== -1) {
  25977. this.materials.splice(index, 1);
  25978. }
  25979. return index;
  25980. };
  25981. /**
  25982. * Removes the given lens flare system from this scene.
  25983. * @param toRemove The lens flare system to remove
  25984. * @returns The index of the removed lens flare system
  25985. */
  25986. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25987. var index = this.lensFlareSystems.indexOf(toRemove);
  25988. if (index !== -1) {
  25989. this.lensFlareSystems.splice(index, 1);
  25990. }
  25991. return index;
  25992. };
  25993. /**
  25994. * Removes the given action manager from this scene.
  25995. * @param toRemove The action manager to remove
  25996. * @returns The index of the removed action manager
  25997. */
  25998. Scene.prototype.removeActionManager = function (toRemove) {
  25999. var index = this._actionManagers.indexOf(toRemove);
  26000. if (index !== -1) {
  26001. this._actionManagers.splice(index, 1);
  26002. }
  26003. return index;
  26004. };
  26005. /**
  26006. * Removes the given effect layer from this scene.
  26007. * @param toRemove defines the effect layer to remove
  26008. * @returns the index of the removed effect layer
  26009. */
  26010. Scene.prototype.removeEffectLayer = function (toRemove) {
  26011. var index = this.effectLayers.indexOf(toRemove);
  26012. if (index !== -1) {
  26013. this.effectLayers.splice(index, 1);
  26014. }
  26015. return index;
  26016. };
  26017. /**
  26018. * Removes the given texture from this scene.
  26019. * @param toRemove The texture to remove
  26020. * @returns The index of the removed texture
  26021. */
  26022. Scene.prototype.removeTexture = function (toRemove) {
  26023. var index = this.textures.indexOf(toRemove);
  26024. if (index !== -1) {
  26025. this.textures.splice(index, 1);
  26026. }
  26027. return index;
  26028. };
  26029. /**
  26030. * Adds the given light to this scene
  26031. * @param newLight The light to add
  26032. */
  26033. Scene.prototype.addLight = function (newLight) {
  26034. this.lights.push(newLight);
  26035. this.sortLightsByPriority();
  26036. // Add light to all meshes (To support if the light is removed and then readded)
  26037. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26038. var mesh = _a[_i];
  26039. if (mesh._lightSources.indexOf(newLight) === -1) {
  26040. mesh._lightSources.push(newLight);
  26041. mesh._resyncLightSources();
  26042. }
  26043. }
  26044. this.onNewLightAddedObservable.notifyObservers(newLight);
  26045. };
  26046. /**
  26047. * Sorts the list list based on light priorities
  26048. */
  26049. Scene.prototype.sortLightsByPriority = function () {
  26050. if (this.requireLightSorting) {
  26051. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26052. }
  26053. };
  26054. /**
  26055. * Adds the given camera to this scene
  26056. * @param newCamera The camera to add
  26057. */
  26058. Scene.prototype.addCamera = function (newCamera) {
  26059. this.cameras.push(newCamera);
  26060. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26061. };
  26062. /**
  26063. * Adds the given skeleton to this scene
  26064. * @param newSkeleton The skeleton to add
  26065. */
  26066. Scene.prototype.addSkeleton = function (newSkeleton) {
  26067. this.skeletons.push(newSkeleton);
  26068. };
  26069. /**
  26070. * Adds the given particle system to this scene
  26071. * @param newParticleSystem The particle system to add
  26072. */
  26073. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26074. this.particleSystems.push(newParticleSystem);
  26075. };
  26076. /**
  26077. * Adds the given animation to this scene
  26078. * @param newAnimation The animation to add
  26079. */
  26080. Scene.prototype.addAnimation = function (newAnimation) {
  26081. this.animations.push(newAnimation);
  26082. };
  26083. /**
  26084. * Adds the given animation group to this scene.
  26085. * @param newAnimationGroup The animation group to add
  26086. */
  26087. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26088. this.animationGroups.push(newAnimationGroup);
  26089. };
  26090. /**
  26091. * Adds the given multi-material to this scene
  26092. * @param newMultiMaterial The multi-material to add
  26093. */
  26094. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26095. this.multiMaterials.push(newMultiMaterial);
  26096. };
  26097. /**
  26098. * Adds the given material to this scene
  26099. * @param newMaterial The material to add
  26100. */
  26101. Scene.prototype.addMaterial = function (newMaterial) {
  26102. this.materials.push(newMaterial);
  26103. };
  26104. /**
  26105. * Adds the given morph target to this scene
  26106. * @param newMorphTargetManager The morph target to add
  26107. */
  26108. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26109. this.morphTargetManagers.push(newMorphTargetManager);
  26110. };
  26111. /**
  26112. * Adds the given geometry to this scene
  26113. * @param newGeometry The geometry to add
  26114. */
  26115. Scene.prototype.addGeometry = function (newGeometry) {
  26116. this._geometries.push(newGeometry);
  26117. };
  26118. /**
  26119. * Adds the given lens flare system to this scene
  26120. * @param newLensFlareSystem The lens flare system to add
  26121. */
  26122. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26123. this.lensFlareSystems.push(newLensFlareSystem);
  26124. };
  26125. /**
  26126. * Adds the given effect layer to this scene
  26127. * @param newEffectLayer defines the effect layer to add
  26128. */
  26129. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26130. this.effectLayers.push(newEffectLayer);
  26131. };
  26132. /**
  26133. * Adds the given action manager to this scene
  26134. * @param newActionManager The action manager to add
  26135. */
  26136. Scene.prototype.addActionManager = function (newActionManager) {
  26137. this._actionManagers.push(newActionManager);
  26138. };
  26139. /**
  26140. * Adds the given texture to this scene.
  26141. * @param newTexture The texture to add
  26142. */
  26143. Scene.prototype.addTexture = function (newTexture) {
  26144. this.textures.push(newTexture);
  26145. };
  26146. /**
  26147. * Switch active camera
  26148. * @param newCamera defines the new active camera
  26149. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26150. */
  26151. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26152. if (attachControl === void 0) { attachControl = true; }
  26153. var canvas = this._engine.getRenderingCanvas();
  26154. if (!canvas) {
  26155. return;
  26156. }
  26157. if (this.activeCamera) {
  26158. this.activeCamera.detachControl(canvas);
  26159. }
  26160. this.activeCamera = newCamera;
  26161. if (attachControl) {
  26162. newCamera.attachControl(canvas);
  26163. }
  26164. };
  26165. /**
  26166. * sets the active camera of the scene using its ID
  26167. * @param id defines the camera's ID
  26168. * @return the new active camera or null if none found.
  26169. */
  26170. Scene.prototype.setActiveCameraByID = function (id) {
  26171. var camera = this.getCameraByID(id);
  26172. if (camera) {
  26173. this.activeCamera = camera;
  26174. return camera;
  26175. }
  26176. return null;
  26177. };
  26178. /**
  26179. * sets the active camera of the scene using its name
  26180. * @param name defines the camera's name
  26181. * @returns the new active camera or null if none found.
  26182. */
  26183. Scene.prototype.setActiveCameraByName = function (name) {
  26184. var camera = this.getCameraByName(name);
  26185. if (camera) {
  26186. this.activeCamera = camera;
  26187. return camera;
  26188. }
  26189. return null;
  26190. };
  26191. /**
  26192. * get an animation group using its name
  26193. * @param name defines the material's name
  26194. * @return the animation group or null if none found.
  26195. */
  26196. Scene.prototype.getAnimationGroupByName = function (name) {
  26197. for (var index = 0; index < this.animationGroups.length; index++) {
  26198. if (this.animationGroups[index].name === name) {
  26199. return this.animationGroups[index];
  26200. }
  26201. }
  26202. return null;
  26203. };
  26204. /**
  26205. * get a material using its id
  26206. * @param id defines the material's ID
  26207. * @return the material or null if none found.
  26208. */
  26209. Scene.prototype.getMaterialByID = function (id) {
  26210. for (var index = 0; index < this.materials.length; index++) {
  26211. if (this.materials[index].id === id) {
  26212. return this.materials[index];
  26213. }
  26214. }
  26215. return null;
  26216. };
  26217. /**
  26218. * Gets a material using its name
  26219. * @param name defines the material's name
  26220. * @return the material or null if none found.
  26221. */
  26222. Scene.prototype.getMaterialByName = function (name) {
  26223. for (var index = 0; index < this.materials.length; index++) {
  26224. if (this.materials[index].name === name) {
  26225. return this.materials[index];
  26226. }
  26227. }
  26228. return null;
  26229. };
  26230. /**
  26231. * Gets a lens flare system using its name
  26232. * @param name defines the name to look for
  26233. * @returns the lens flare system or null if not found
  26234. */
  26235. Scene.prototype.getLensFlareSystemByName = function (name) {
  26236. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26237. if (this.lensFlareSystems[index].name === name) {
  26238. return this.lensFlareSystems[index];
  26239. }
  26240. }
  26241. return null;
  26242. };
  26243. /**
  26244. * Gets a lens flare system using its id
  26245. * @param id defines the id to look for
  26246. * @returns the lens flare system or null if not found
  26247. */
  26248. Scene.prototype.getLensFlareSystemByID = function (id) {
  26249. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26250. if (this.lensFlareSystems[index].id === id) {
  26251. return this.lensFlareSystems[index];
  26252. }
  26253. }
  26254. return null;
  26255. };
  26256. /**
  26257. * Gets a camera using its id
  26258. * @param id defines the id to look for
  26259. * @returns the camera or null if not found
  26260. */
  26261. Scene.prototype.getCameraByID = function (id) {
  26262. for (var index = 0; index < this.cameras.length; index++) {
  26263. if (this.cameras[index].id === id) {
  26264. return this.cameras[index];
  26265. }
  26266. }
  26267. return null;
  26268. };
  26269. /**
  26270. * Gets a camera using its unique id
  26271. * @param uniqueId defines the unique id to look for
  26272. * @returns the camera or null if not found
  26273. */
  26274. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26275. for (var index = 0; index < this.cameras.length; index++) {
  26276. if (this.cameras[index].uniqueId === uniqueId) {
  26277. return this.cameras[index];
  26278. }
  26279. }
  26280. return null;
  26281. };
  26282. /**
  26283. * Gets a camera using its name
  26284. * @param name defines the camera's name
  26285. * @return the camera or null if none found.
  26286. */
  26287. Scene.prototype.getCameraByName = function (name) {
  26288. for (var index = 0; index < this.cameras.length; index++) {
  26289. if (this.cameras[index].name === name) {
  26290. return this.cameras[index];
  26291. }
  26292. }
  26293. return null;
  26294. };
  26295. /**
  26296. * Gets a bone using its id
  26297. * @param id defines the bone's id
  26298. * @return the bone or null if not found
  26299. */
  26300. Scene.prototype.getBoneByID = function (id) {
  26301. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26302. var skeleton = this.skeletons[skeletonIndex];
  26303. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26304. if (skeleton.bones[boneIndex].id === id) {
  26305. return skeleton.bones[boneIndex];
  26306. }
  26307. }
  26308. }
  26309. return null;
  26310. };
  26311. /**
  26312. * Gets a bone using its id
  26313. * @param name defines the bone's name
  26314. * @return the bone or null if not found
  26315. */
  26316. Scene.prototype.getBoneByName = function (name) {
  26317. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26318. var skeleton = this.skeletons[skeletonIndex];
  26319. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26320. if (skeleton.bones[boneIndex].name === name) {
  26321. return skeleton.bones[boneIndex];
  26322. }
  26323. }
  26324. }
  26325. return null;
  26326. };
  26327. /**
  26328. * Gets a light node using its name
  26329. * @param name defines the the light's name
  26330. * @return the light or null if none found.
  26331. */
  26332. Scene.prototype.getLightByName = function (name) {
  26333. for (var index = 0; index < this.lights.length; index++) {
  26334. if (this.lights[index].name === name) {
  26335. return this.lights[index];
  26336. }
  26337. }
  26338. return null;
  26339. };
  26340. /**
  26341. * Gets a light node using its id
  26342. * @param id defines the light's id
  26343. * @return the light or null if none found.
  26344. */
  26345. Scene.prototype.getLightByID = function (id) {
  26346. for (var index = 0; index < this.lights.length; index++) {
  26347. if (this.lights[index].id === id) {
  26348. return this.lights[index];
  26349. }
  26350. }
  26351. return null;
  26352. };
  26353. /**
  26354. * Gets a light node using its scene-generated unique ID
  26355. * @param uniqueId defines the light's unique id
  26356. * @return the light or null if none found.
  26357. */
  26358. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26359. for (var index = 0; index < this.lights.length; index++) {
  26360. if (this.lights[index].uniqueId === uniqueId) {
  26361. return this.lights[index];
  26362. }
  26363. }
  26364. return null;
  26365. };
  26366. /**
  26367. * Gets a particle system by id
  26368. * @param id defines the particle system id
  26369. * @return the corresponding system or null if none found
  26370. */
  26371. Scene.prototype.getParticleSystemByID = function (id) {
  26372. for (var index = 0; index < this.particleSystems.length; index++) {
  26373. if (this.particleSystems[index].id === id) {
  26374. return this.particleSystems[index];
  26375. }
  26376. }
  26377. return null;
  26378. };
  26379. /**
  26380. * Gets a geometry using its ID
  26381. * @param id defines the geometry's id
  26382. * @return the geometry or null if none found.
  26383. */
  26384. Scene.prototype.getGeometryByID = function (id) {
  26385. for (var index = 0; index < this._geometries.length; index++) {
  26386. if (this._geometries[index].id === id) {
  26387. return this._geometries[index];
  26388. }
  26389. }
  26390. return null;
  26391. };
  26392. /**
  26393. * Add a new geometry to this scene
  26394. * @param geometry defines the geometry to be added to the scene.
  26395. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26396. * @return a boolean defining if the geometry was added or not
  26397. */
  26398. Scene.prototype.pushGeometry = function (geometry, force) {
  26399. if (!force && this.getGeometryByID(geometry.id)) {
  26400. return false;
  26401. }
  26402. this._geometries.push(geometry);
  26403. //notify the collision coordinator
  26404. if (this.collisionCoordinator) {
  26405. this.collisionCoordinator.onGeometryAdded(geometry);
  26406. }
  26407. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26408. return true;
  26409. };
  26410. /**
  26411. * Removes an existing geometry
  26412. * @param geometry defines the geometry to be removed from the scene
  26413. * @return a boolean defining if the geometry was removed or not
  26414. */
  26415. Scene.prototype.removeGeometry = function (geometry) {
  26416. var index = this._geometries.indexOf(geometry);
  26417. if (index > -1) {
  26418. this._geometries.splice(index, 1);
  26419. //notify the collision coordinator
  26420. if (this.collisionCoordinator) {
  26421. this.collisionCoordinator.onGeometryDeleted(geometry);
  26422. }
  26423. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26424. return true;
  26425. }
  26426. return false;
  26427. };
  26428. /**
  26429. * Gets the list of geometries attached to the scene
  26430. * @returns an array of Geometry
  26431. */
  26432. Scene.prototype.getGeometries = function () {
  26433. return this._geometries;
  26434. };
  26435. /**
  26436. * Gets the first added mesh found of a given ID
  26437. * @param id defines the id to search for
  26438. * @return the mesh found or null if not found at all
  26439. */
  26440. Scene.prototype.getMeshByID = function (id) {
  26441. for (var index = 0; index < this.meshes.length; index++) {
  26442. if (this.meshes[index].id === id) {
  26443. return this.meshes[index];
  26444. }
  26445. }
  26446. return null;
  26447. };
  26448. /**
  26449. * Gets a list of meshes using their id
  26450. * @param id defines the id to search for
  26451. * @returns a list of meshes
  26452. */
  26453. Scene.prototype.getMeshesByID = function (id) {
  26454. return this.meshes.filter(function (m) {
  26455. return m.id === id;
  26456. });
  26457. };
  26458. /**
  26459. * Gets the first added transform node found of a given ID
  26460. * @param id defines the id to search for
  26461. * @return the found transform node or null if not found at all.
  26462. */
  26463. Scene.prototype.getTransformNodeByID = function (id) {
  26464. for (var index = 0; index < this.transformNodes.length; index++) {
  26465. if (this.transformNodes[index].id === id) {
  26466. return this.transformNodes[index];
  26467. }
  26468. }
  26469. return null;
  26470. };
  26471. /**
  26472. * Gets a list of transform nodes using their id
  26473. * @param id defines the id to search for
  26474. * @returns a list of transform nodes
  26475. */
  26476. Scene.prototype.getTransformNodesByID = function (id) {
  26477. return this.transformNodes.filter(function (m) {
  26478. return m.id === id;
  26479. });
  26480. };
  26481. /**
  26482. * Gets a mesh with its auto-generated unique id
  26483. * @param uniqueId defines the unique id to search for
  26484. * @return the found mesh or null if not found at all.
  26485. */
  26486. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26487. for (var index = 0; index < this.meshes.length; index++) {
  26488. if (this.meshes[index].uniqueId === uniqueId) {
  26489. return this.meshes[index];
  26490. }
  26491. }
  26492. return null;
  26493. };
  26494. /**
  26495. * Gets a the last added mesh using a given id
  26496. * @param id defines the id to search for
  26497. * @return the found mesh or null if not found at all.
  26498. */
  26499. Scene.prototype.getLastMeshByID = function (id) {
  26500. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26501. if (this.meshes[index].id === id) {
  26502. return this.meshes[index];
  26503. }
  26504. }
  26505. return null;
  26506. };
  26507. /**
  26508. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26509. * @param id defines the id to search for
  26510. * @return the found node or null if not found at all
  26511. */
  26512. Scene.prototype.getLastEntryByID = function (id) {
  26513. var index;
  26514. for (index = this.meshes.length - 1; index >= 0; index--) {
  26515. if (this.meshes[index].id === id) {
  26516. return this.meshes[index];
  26517. }
  26518. }
  26519. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26520. if (this.transformNodes[index].id === id) {
  26521. return this.transformNodes[index];
  26522. }
  26523. }
  26524. for (index = this.cameras.length - 1; index >= 0; index--) {
  26525. if (this.cameras[index].id === id) {
  26526. return this.cameras[index];
  26527. }
  26528. }
  26529. for (index = this.lights.length - 1; index >= 0; index--) {
  26530. if (this.lights[index].id === id) {
  26531. return this.lights[index];
  26532. }
  26533. }
  26534. return null;
  26535. };
  26536. /**
  26537. * Gets a node (Mesh, Camera, Light) using a given id
  26538. * @param id defines the id to search for
  26539. * @return the found node or null if not found at all
  26540. */
  26541. Scene.prototype.getNodeByID = function (id) {
  26542. var mesh = this.getMeshByID(id);
  26543. if (mesh) {
  26544. return mesh;
  26545. }
  26546. var light = this.getLightByID(id);
  26547. if (light) {
  26548. return light;
  26549. }
  26550. var camera = this.getCameraByID(id);
  26551. if (camera) {
  26552. return camera;
  26553. }
  26554. var bone = this.getBoneByID(id);
  26555. return bone;
  26556. };
  26557. /**
  26558. * Gets a node (Mesh, Camera, Light) using a given name
  26559. * @param name defines the name to search for
  26560. * @return the found node or null if not found at all.
  26561. */
  26562. Scene.prototype.getNodeByName = function (name) {
  26563. var mesh = this.getMeshByName(name);
  26564. if (mesh) {
  26565. return mesh;
  26566. }
  26567. var light = this.getLightByName(name);
  26568. if (light) {
  26569. return light;
  26570. }
  26571. var camera = this.getCameraByName(name);
  26572. if (camera) {
  26573. return camera;
  26574. }
  26575. var bone = this.getBoneByName(name);
  26576. return bone;
  26577. };
  26578. /**
  26579. * Gets a mesh using a given name
  26580. * @param name defines the name to search for
  26581. * @return the found mesh or null if not found at all.
  26582. */
  26583. Scene.prototype.getMeshByName = function (name) {
  26584. for (var index = 0; index < this.meshes.length; index++) {
  26585. if (this.meshes[index].name === name) {
  26586. return this.meshes[index];
  26587. }
  26588. }
  26589. return null;
  26590. };
  26591. /**
  26592. * Gets a transform node using a given name
  26593. * @param name defines the name to search for
  26594. * @return the found transform node or null if not found at all.
  26595. */
  26596. Scene.prototype.getTransformNodeByName = function (name) {
  26597. for (var index = 0; index < this.transformNodes.length; index++) {
  26598. if (this.transformNodes[index].name === name) {
  26599. return this.transformNodes[index];
  26600. }
  26601. }
  26602. return null;
  26603. };
  26604. /**
  26605. * Gets a sound using a given name
  26606. * @param name defines the name to search for
  26607. * @return the found sound or null if not found at all.
  26608. */
  26609. Scene.prototype.getSoundByName = function (name) {
  26610. var index;
  26611. if (BABYLON.AudioEngine) {
  26612. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26613. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26614. return this.mainSoundTrack.soundCollection[index];
  26615. }
  26616. }
  26617. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26618. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26619. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26620. return this.soundTracks[sdIndex].soundCollection[index];
  26621. }
  26622. }
  26623. }
  26624. }
  26625. return null;
  26626. };
  26627. /**
  26628. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26629. * @param id defines the id to search for
  26630. * @return the found skeleton or null if not found at all.
  26631. */
  26632. Scene.prototype.getLastSkeletonByID = function (id) {
  26633. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26634. if (this.skeletons[index].id === id) {
  26635. return this.skeletons[index];
  26636. }
  26637. }
  26638. return null;
  26639. };
  26640. /**
  26641. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26642. * @param id defines the id to search for
  26643. * @return the found skeleton or null if not found at all.
  26644. */
  26645. Scene.prototype.getSkeletonById = function (id) {
  26646. for (var index = 0; index < this.skeletons.length; index++) {
  26647. if (this.skeletons[index].id === id) {
  26648. return this.skeletons[index];
  26649. }
  26650. }
  26651. return null;
  26652. };
  26653. /**
  26654. * Gets a skeleton using a given name
  26655. * @param name defines the name to search for
  26656. * @return the found skeleton or null if not found at all.
  26657. */
  26658. Scene.prototype.getSkeletonByName = function (name) {
  26659. for (var index = 0; index < this.skeletons.length; index++) {
  26660. if (this.skeletons[index].name === name) {
  26661. return this.skeletons[index];
  26662. }
  26663. }
  26664. return null;
  26665. };
  26666. /**
  26667. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26668. * @param id defines the id to search for
  26669. * @return the found morph target manager or null if not found at all.
  26670. */
  26671. Scene.prototype.getMorphTargetManagerById = function (id) {
  26672. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26673. if (this.morphTargetManagers[index].uniqueId === id) {
  26674. return this.morphTargetManagers[index];
  26675. }
  26676. }
  26677. return null;
  26678. };
  26679. /**
  26680. * Gets a boolean indicating if the given mesh is active
  26681. * @param mesh defines the mesh to look for
  26682. * @returns true if the mesh is in the active list
  26683. */
  26684. Scene.prototype.isActiveMesh = function (mesh) {
  26685. return (this._activeMeshes.indexOf(mesh) !== -1);
  26686. };
  26687. /**
  26688. * Return a the first highlight layer of the scene with a given name.
  26689. * @param name The name of the highlight layer to look for.
  26690. * @return The highlight layer if found otherwise null.
  26691. */
  26692. Scene.prototype.getHighlightLayerByName = function (name) {
  26693. for (var index = 0; index < this.effectLayers.length; index++) {
  26694. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26695. return this.effectLayers[index];
  26696. }
  26697. }
  26698. return null;
  26699. };
  26700. /**
  26701. * Return a the first highlight layer of the scene with a given name.
  26702. * @param name The name of the highlight layer to look for.
  26703. * @return The highlight layer if found otherwise null.
  26704. */
  26705. Scene.prototype.getGlowLayerByName = function (name) {
  26706. for (var index = 0; index < this.effectLayers.length; index++) {
  26707. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26708. return this.effectLayers[index];
  26709. }
  26710. }
  26711. return null;
  26712. };
  26713. Object.defineProperty(Scene.prototype, "uid", {
  26714. /**
  26715. * Return a unique id as a string which can serve as an identifier for the scene
  26716. */
  26717. get: function () {
  26718. if (!this._uid) {
  26719. this._uid = BABYLON.Tools.RandomId();
  26720. }
  26721. return this._uid;
  26722. },
  26723. enumerable: true,
  26724. configurable: true
  26725. });
  26726. /**
  26727. * Add an externaly attached data from its key.
  26728. * This method call will fail and return false, if such key already exists.
  26729. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26730. * @param key the unique key that identifies the data
  26731. * @param data the data object to associate to the key for this Engine instance
  26732. * @return true if no such key were already present and the data was added successfully, false otherwise
  26733. */
  26734. Scene.prototype.addExternalData = function (key, data) {
  26735. if (!this._externalData) {
  26736. this._externalData = new BABYLON.StringDictionary();
  26737. }
  26738. return this._externalData.add(key, data);
  26739. };
  26740. /**
  26741. * Get an externaly attached data from its key
  26742. * @param key the unique key that identifies the data
  26743. * @return the associated data, if present (can be null), or undefined if not present
  26744. */
  26745. Scene.prototype.getExternalData = function (key) {
  26746. if (!this._externalData) {
  26747. return null;
  26748. }
  26749. return this._externalData.get(key);
  26750. };
  26751. /**
  26752. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26753. * @param key the unique key that identifies the data
  26754. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26755. * @return the associated data, can be null if the factory returned null.
  26756. */
  26757. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26758. if (!this._externalData) {
  26759. this._externalData = new BABYLON.StringDictionary();
  26760. }
  26761. return this._externalData.getOrAddWithFactory(key, factory);
  26762. };
  26763. /**
  26764. * Remove an externaly attached data from the Engine instance
  26765. * @param key the unique key that identifies the data
  26766. * @return true if the data was successfully removed, false if it doesn't exist
  26767. */
  26768. Scene.prototype.removeExternalData = function (key) {
  26769. return this._externalData.remove(key);
  26770. };
  26771. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26772. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26773. if (mesh.showSubMeshesBoundingBox) {
  26774. var boundingInfo = subMesh.getBoundingInfo();
  26775. if (boundingInfo !== null && boundingInfo !== undefined) {
  26776. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26777. }
  26778. }
  26779. var material = subMesh.getMaterial();
  26780. if (material !== null && material !== undefined) {
  26781. // Render targets
  26782. if (material.getRenderTargetTextures !== undefined) {
  26783. if (this._processedMaterials.indexOf(material) === -1) {
  26784. this._processedMaterials.push(material);
  26785. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26786. }
  26787. }
  26788. // Dispatch
  26789. this._activeIndices.addCount(subMesh.indexCount, false);
  26790. this._renderingManager.dispatch(subMesh, mesh, material);
  26791. }
  26792. }
  26793. };
  26794. /**
  26795. * Clear the processed materials smart array preventing retention point in material dispose.
  26796. */
  26797. Scene.prototype.freeProcessedMaterials = function () {
  26798. this._processedMaterials.dispose();
  26799. };
  26800. /**
  26801. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26802. */
  26803. Scene.prototype.freeActiveMeshes = function () {
  26804. this._activeMeshes.dispose();
  26805. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26806. this.activeCamera._activeMeshes.dispose();
  26807. }
  26808. if (this.activeCameras) {
  26809. for (var i = 0; i < this.activeCameras.length; i++) {
  26810. var activeCamera = this.activeCameras[i];
  26811. if (activeCamera && activeCamera._activeMeshes) {
  26812. activeCamera._activeMeshes.dispose();
  26813. }
  26814. }
  26815. }
  26816. };
  26817. /**
  26818. * Clear the info related to rendering groups preventing retention points during dispose.
  26819. */
  26820. Scene.prototype.freeRenderingGroups = function () {
  26821. if (this._renderingManager) {
  26822. this._renderingManager.freeRenderingGroups();
  26823. }
  26824. if (this.textures) {
  26825. for (var i = 0; i < this.textures.length; i++) {
  26826. var texture = this.textures[i];
  26827. if (texture && texture.renderList) {
  26828. texture.freeRenderingGroups();
  26829. }
  26830. }
  26831. }
  26832. };
  26833. /** @ignore */
  26834. Scene.prototype._isInIntermediateRendering = function () {
  26835. return this._intermediateRendering;
  26836. };
  26837. /**
  26838. * Defines the current active mesh candidate provider
  26839. * @param provider defines the provider to use
  26840. */
  26841. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26842. this._activeMeshCandidateProvider = provider;
  26843. };
  26844. /**
  26845. * Gets the current active mesh candidate provider
  26846. * @returns the current active mesh candidate provider
  26847. */
  26848. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26849. return this._activeMeshCandidateProvider;
  26850. };
  26851. /**
  26852. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26853. * @returns the current scene
  26854. */
  26855. Scene.prototype.freezeActiveMeshes = function () {
  26856. if (!this.activeCamera) {
  26857. return this;
  26858. }
  26859. if (!this._frustumPlanes) {
  26860. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26861. }
  26862. this._evaluateActiveMeshes();
  26863. this._activeMeshesFrozen = true;
  26864. return this;
  26865. };
  26866. /**
  26867. * Use this function to restart evaluating active meshes on every frame
  26868. * @returns the current scene
  26869. */
  26870. Scene.prototype.unfreezeActiveMeshes = function () {
  26871. this._activeMeshesFrozen = false;
  26872. return this;
  26873. };
  26874. Scene.prototype._evaluateActiveMeshes = function () {
  26875. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26876. return;
  26877. }
  26878. if (!this.activeCamera) {
  26879. return;
  26880. }
  26881. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26882. this.activeCamera._activeMeshes.reset();
  26883. this._activeMeshes.reset();
  26884. this._renderingManager.reset();
  26885. this._processedMaterials.reset();
  26886. this._activeParticleSystems.reset();
  26887. this._activeSkeletons.reset();
  26888. this._softwareSkinnedMeshes.reset();
  26889. if (this._boundingBoxRenderer) {
  26890. this._boundingBoxRenderer.reset();
  26891. }
  26892. // Meshes
  26893. var meshes;
  26894. var len;
  26895. var checkIsEnabled = true;
  26896. // Determine mesh candidates
  26897. if (this._activeMeshCandidateProvider !== undefined) {
  26898. // Use _activeMeshCandidateProvider
  26899. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26900. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26901. if (meshes !== undefined) {
  26902. len = meshes.length;
  26903. }
  26904. else {
  26905. len = 0;
  26906. }
  26907. }
  26908. else if (this._selectionOctree !== undefined) {
  26909. // Octree
  26910. var selection = this._selectionOctree.select(this._frustumPlanes);
  26911. meshes = selection.data;
  26912. len = selection.length;
  26913. }
  26914. else {
  26915. // Full scene traversal
  26916. len = this.meshes.length;
  26917. meshes = this.meshes;
  26918. }
  26919. // Check each mesh
  26920. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26921. mesh = meshes[meshIndex];
  26922. if (mesh.isBlocked) {
  26923. continue;
  26924. }
  26925. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26926. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26927. continue;
  26928. }
  26929. mesh.computeWorldMatrix();
  26930. // Intersections
  26931. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26932. this._meshesForIntersections.pushNoDuplicate(mesh);
  26933. }
  26934. // Switch to current LOD
  26935. meshLOD = mesh.getLOD(this.activeCamera);
  26936. if (meshLOD === undefined || meshLOD === null) {
  26937. continue;
  26938. }
  26939. mesh._preActivate();
  26940. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26941. this._activeMeshes.push(mesh);
  26942. this.activeCamera._activeMeshes.push(mesh);
  26943. mesh._activate(this._renderId);
  26944. if (meshLOD !== mesh) {
  26945. meshLOD._activate(this._renderId);
  26946. }
  26947. this._activeMesh(mesh, meshLOD);
  26948. }
  26949. }
  26950. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26951. // Particle systems
  26952. if (this.particlesEnabled) {
  26953. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26954. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26955. var particleSystem = this.particleSystems[particleIndex];
  26956. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26957. continue;
  26958. }
  26959. var emitter = particleSystem.emitter;
  26960. if (!emitter.position || emitter.isEnabled()) {
  26961. this._activeParticleSystems.push(particleSystem);
  26962. particleSystem.animate();
  26963. this._renderingManager.dispatchParticles(particleSystem);
  26964. }
  26965. }
  26966. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26967. }
  26968. };
  26969. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26970. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26971. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26972. mesh.skeleton.prepare();
  26973. }
  26974. if (!mesh.computeBonesUsingShaders) {
  26975. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26976. }
  26977. }
  26978. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26979. var boundingInfo = sourceMesh.getBoundingInfo();
  26980. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26981. }
  26982. if (mesh !== undefined && mesh !== null
  26983. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26984. // Submeshes Octrees
  26985. var len;
  26986. var subMeshes;
  26987. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26988. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26989. len = intersections.length;
  26990. subMeshes = intersections.data;
  26991. }
  26992. else {
  26993. subMeshes = mesh.subMeshes;
  26994. len = subMeshes.length;
  26995. }
  26996. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26997. subMesh = subMeshes[subIndex];
  26998. this._evaluateSubMesh(subMesh, mesh);
  26999. }
  27000. }
  27001. };
  27002. /**
  27003. * Update the transform matrix to update from the current active camera
  27004. * @param force defines a boolean used to force the update even if cache is up to date
  27005. */
  27006. Scene.prototype.updateTransformMatrix = function (force) {
  27007. if (!this.activeCamera) {
  27008. return;
  27009. }
  27010. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27011. };
  27012. /**
  27013. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27014. * @param alternateCamera defines the camera to use
  27015. */
  27016. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27017. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27018. };
  27019. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27020. if (camera && camera._skipRendering) {
  27021. return;
  27022. }
  27023. var engine = this._engine;
  27024. this.activeCamera = camera;
  27025. if (!this.activeCamera)
  27026. throw new Error("Active camera not set");
  27027. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27028. // Viewport
  27029. engine.setViewport(this.activeCamera.viewport);
  27030. // Camera
  27031. this.resetCachedMaterial();
  27032. this._renderId++;
  27033. this.updateTransformMatrix();
  27034. if (camera._alternateCamera) {
  27035. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27036. this._alternateRendering = true;
  27037. }
  27038. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27039. // Meshes
  27040. this._evaluateActiveMeshes();
  27041. // Software skinning
  27042. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27043. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27044. mesh.applySkeleton(mesh.skeleton);
  27045. }
  27046. // Render targets
  27047. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27048. var needsRestoreFrameBuffer = false;
  27049. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27050. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27051. }
  27052. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27053. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27054. }
  27055. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27056. this._intermediateRendering = true;
  27057. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27058. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27059. var renderTarget = this._renderTargets.data[renderIndex];
  27060. if (renderTarget._shouldRender()) {
  27061. this._renderId++;
  27062. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27063. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27064. }
  27065. }
  27066. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27067. this._intermediateRendering = false;
  27068. this._renderId++;
  27069. needsRestoreFrameBuffer = true; // Restore back buffer
  27070. }
  27071. // Render EffecttLayer Texture
  27072. var stencilState = this._engine.getStencilBuffer();
  27073. var renderEffects = false;
  27074. var needStencil = false;
  27075. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27076. this._intermediateRendering = true;
  27077. for (var i = 0; i < this.effectLayers.length; i++) {
  27078. var effectLayer = this.effectLayers[i];
  27079. if (effectLayer.shouldRender() &&
  27080. (!effectLayer.camera ||
  27081. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27082. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27083. renderEffects = true;
  27084. needStencil = needStencil || effectLayer.needStencil();
  27085. var renderTarget = effectLayer._mainTexture;
  27086. if (renderTarget._shouldRender()) {
  27087. this._renderId++;
  27088. renderTarget.render(false, false);
  27089. needsRestoreFrameBuffer = true;
  27090. }
  27091. }
  27092. }
  27093. this._intermediateRendering = false;
  27094. this._renderId++;
  27095. }
  27096. if (needsRestoreFrameBuffer) {
  27097. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27098. }
  27099. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27100. // Prepare Frame
  27101. this.postProcessManager._prepareFrame();
  27102. // Backgrounds
  27103. var layerIndex;
  27104. var layer;
  27105. if (this.layers.length) {
  27106. engine.setDepthBuffer(false);
  27107. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27108. layer = this.layers[layerIndex];
  27109. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27110. layer.render();
  27111. }
  27112. }
  27113. engine.setDepthBuffer(true);
  27114. }
  27115. // Activate effect Layer stencil
  27116. if (needStencil) {
  27117. this._engine.setStencilBuffer(true);
  27118. }
  27119. // Render
  27120. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27121. this._renderingManager.render(null, null, true, true);
  27122. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27123. // Restore effect Layer stencil
  27124. if (needStencil) {
  27125. this._engine.setStencilBuffer(stencilState);
  27126. }
  27127. // Bounding boxes
  27128. if (this._boundingBoxRenderer) {
  27129. this._boundingBoxRenderer.render();
  27130. }
  27131. // Lens flares
  27132. if (this.lensFlaresEnabled) {
  27133. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27134. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27135. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27136. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27137. lensFlareSystem.render();
  27138. }
  27139. }
  27140. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27141. }
  27142. // Effect Layer
  27143. if (renderEffects) {
  27144. engine.setDepthBuffer(false);
  27145. for (var i = 0; i < this.effectLayers.length; i++) {
  27146. if (this.effectLayers[i].shouldRender()) {
  27147. this.effectLayers[i].render();
  27148. }
  27149. }
  27150. engine.setDepthBuffer(true);
  27151. }
  27152. // Foregrounds
  27153. if (this.layers.length) {
  27154. engine.setDepthBuffer(false);
  27155. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27156. layer = this.layers[layerIndex];
  27157. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27158. layer.render();
  27159. }
  27160. }
  27161. engine.setDepthBuffer(true);
  27162. }
  27163. // Finalize frame
  27164. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27165. // Reset some special arrays
  27166. this._renderTargets.reset();
  27167. this._alternateRendering = false;
  27168. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27169. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27170. };
  27171. Scene.prototype._processSubCameras = function (camera) {
  27172. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27173. this._renderForCamera(camera);
  27174. return;
  27175. }
  27176. // rig cameras
  27177. for (var index = 0; index < camera._rigCameras.length; index++) {
  27178. this._renderForCamera(camera._rigCameras[index], camera);
  27179. }
  27180. this.activeCamera = camera;
  27181. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27182. };
  27183. Scene.prototype._checkIntersections = function () {
  27184. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27185. var sourceMesh = this._meshesForIntersections.data[index];
  27186. if (!sourceMesh.actionManager) {
  27187. continue;
  27188. }
  27189. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27190. var action = sourceMesh.actionManager.actions[actionIndex];
  27191. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27192. var parameters = action.getTriggerParameter();
  27193. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27194. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27195. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27196. if (areIntersecting && currentIntersectionInProgress === -1) {
  27197. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27198. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27199. sourceMesh._intersectionsInProgress.push(otherMesh);
  27200. }
  27201. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27202. sourceMesh._intersectionsInProgress.push(otherMesh);
  27203. }
  27204. }
  27205. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27206. //They intersected, and now they don't.
  27207. //is this trigger an exit trigger? execute an event.
  27208. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27209. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27210. }
  27211. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27212. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27213. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27214. return otherMesh === parameterMesh;
  27215. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27216. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27217. }
  27218. }
  27219. }
  27220. }
  27221. }
  27222. };
  27223. /**
  27224. * Render the scene
  27225. */
  27226. Scene.prototype.render = function () {
  27227. if (this.isDisposed) {
  27228. return;
  27229. }
  27230. this._activeParticles.fetchNewFrame();
  27231. this._totalVertices.fetchNewFrame();
  27232. this._activeIndices.fetchNewFrame();
  27233. this._activeBones.fetchNewFrame();
  27234. this._meshesForIntersections.reset();
  27235. this.resetCachedMaterial();
  27236. this.onBeforeAnimationsObservable.notifyObservers(this);
  27237. // Actions
  27238. if (this.actionManager) {
  27239. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27240. }
  27241. //Simplification Queue
  27242. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27243. this.simplificationQueue.executeNext();
  27244. }
  27245. if (this._engine.isDeterministicLockStep()) {
  27246. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27247. var defaultFPS = (60.0 / 1000.0);
  27248. var defaultFrameTime = 1000 / 60; // frame time in MS
  27249. if (this._physicsEngine) {
  27250. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27251. }
  27252. var stepsTaken = 0;
  27253. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27254. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27255. internalSteps = Math.min(internalSteps, maxSubSteps);
  27256. do {
  27257. this.onBeforeStepObservable.notifyObservers(this);
  27258. // Animations
  27259. this._animationRatio = defaultFrameTime * defaultFPS;
  27260. this._animate();
  27261. this.onAfterAnimationsObservable.notifyObservers(this);
  27262. // Physics
  27263. if (this._physicsEngine) {
  27264. this.onBeforePhysicsObservable.notifyObservers(this);
  27265. this._physicsEngine._step(defaultFrameTime / 1000);
  27266. this.onAfterPhysicsObservable.notifyObservers(this);
  27267. }
  27268. this.onAfterStepObservable.notifyObservers(this);
  27269. this._currentStepId++;
  27270. stepsTaken++;
  27271. deltaTime -= defaultFrameTime;
  27272. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27273. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27274. }
  27275. else {
  27276. // Animations
  27277. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27278. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27279. this._animate();
  27280. this.onAfterAnimationsObservable.notifyObservers(this);
  27281. // Physics
  27282. if (this._physicsEngine) {
  27283. this.onBeforePhysicsObservable.notifyObservers(this);
  27284. this._physicsEngine._step(deltaTime / 1000.0);
  27285. this.onAfterPhysicsObservable.notifyObservers(this);
  27286. }
  27287. }
  27288. // update gamepad manager
  27289. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27290. this._gamepadManager._checkGamepadsStatus();
  27291. }
  27292. // Update Cameras
  27293. if (this.activeCameras.length > 0) {
  27294. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27295. var camera = this.activeCameras[cameraIndex];
  27296. camera.update();
  27297. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27298. // rig cameras
  27299. for (var index = 0; index < camera._rigCameras.length; index++) {
  27300. camera._rigCameras[index].update();
  27301. }
  27302. }
  27303. }
  27304. }
  27305. else if (this.activeCamera) {
  27306. this.activeCamera.update();
  27307. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27308. // rig cameras
  27309. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27310. this.activeCamera._rigCameras[index].update();
  27311. }
  27312. }
  27313. }
  27314. // Before render
  27315. this.onBeforeRenderObservable.notifyObservers(this);
  27316. // Customs render targets
  27317. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27318. var engine = this.getEngine();
  27319. var currentActiveCamera = this.activeCamera;
  27320. if (this.renderTargetsEnabled) {
  27321. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27322. this._intermediateRendering = true;
  27323. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27324. var renderTarget = this.customRenderTargets[customIndex];
  27325. if (renderTarget._shouldRender()) {
  27326. this._renderId++;
  27327. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27328. if (!this.activeCamera)
  27329. throw new Error("Active camera not set");
  27330. // Viewport
  27331. engine.setViewport(this.activeCamera.viewport);
  27332. // Camera
  27333. this.updateTransformMatrix();
  27334. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27335. }
  27336. }
  27337. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27338. this._intermediateRendering = false;
  27339. this._renderId++;
  27340. }
  27341. // Restore back buffer
  27342. if (this.customRenderTargets.length > 0) {
  27343. engine.restoreDefaultFramebuffer();
  27344. }
  27345. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27346. this.activeCamera = currentActiveCamera;
  27347. // Procedural textures
  27348. if (this.proceduralTexturesEnabled) {
  27349. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27350. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27351. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27352. if (proceduralTexture._shouldRender()) {
  27353. proceduralTexture.render();
  27354. }
  27355. }
  27356. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27357. }
  27358. // Clear
  27359. if (this.autoClearDepthAndStencil || this.autoClear) {
  27360. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27361. }
  27362. // Shadows
  27363. if (this.shadowsEnabled) {
  27364. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27365. var light = this.lights[lightIndex];
  27366. var shadowGenerator = light.getShadowGenerator();
  27367. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27368. var shadowMap = (shadowGenerator.getShadowMap());
  27369. if (this.textures.indexOf(shadowMap) !== -1) {
  27370. this._renderTargets.push(shadowMap);
  27371. }
  27372. }
  27373. }
  27374. }
  27375. // Depth renderer
  27376. for (var key in this._depthRenderer) {
  27377. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27378. }
  27379. // Geometry renderer
  27380. if (this._geometryBufferRenderer) {
  27381. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27382. }
  27383. // RenderPipeline
  27384. if (this._postProcessRenderPipelineManager) {
  27385. this._postProcessRenderPipelineManager.update();
  27386. }
  27387. // Multi-cameras?
  27388. if (this.activeCameras.length > 0) {
  27389. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27390. if (cameraIndex > 0) {
  27391. this._engine.clear(null, false, true, true);
  27392. }
  27393. this._processSubCameras(this.activeCameras[cameraIndex]);
  27394. }
  27395. }
  27396. else {
  27397. if (!this.activeCamera) {
  27398. throw new Error("No camera defined");
  27399. }
  27400. this._processSubCameras(this.activeCamera);
  27401. }
  27402. // Intersection checks
  27403. this._checkIntersections();
  27404. // Update the audio listener attached to the camera
  27405. if (BABYLON.AudioEngine) {
  27406. this._updateAudioParameters();
  27407. }
  27408. // After render
  27409. if (this.afterRender) {
  27410. this.afterRender();
  27411. }
  27412. this.onAfterRenderObservable.notifyObservers(this);
  27413. // Cleaning
  27414. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27415. var data = this._toBeDisposed.data[index];
  27416. if (data) {
  27417. data.dispose();
  27418. }
  27419. this._toBeDisposed[index] = null;
  27420. }
  27421. this._toBeDisposed.reset();
  27422. if (this.dumpNextRenderTargets) {
  27423. this.dumpNextRenderTargets = false;
  27424. }
  27425. this._activeBones.addCount(0, true);
  27426. this._activeIndices.addCount(0, true);
  27427. this._activeParticles.addCount(0, true);
  27428. };
  27429. Scene.prototype._updateAudioParameters = function () {
  27430. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27431. return;
  27432. }
  27433. var listeningCamera;
  27434. var audioEngine = BABYLON.Engine.audioEngine;
  27435. if (this.activeCameras.length > 0) {
  27436. listeningCamera = this.activeCameras[0];
  27437. }
  27438. else {
  27439. listeningCamera = this.activeCamera;
  27440. }
  27441. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27442. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27443. // for VR cameras
  27444. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27445. listeningCamera = listeningCamera.rigCameras[0];
  27446. }
  27447. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27448. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27449. cameraDirection.normalize();
  27450. // To avoid some errors on GearVR
  27451. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27452. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27453. }
  27454. var i;
  27455. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27456. var sound = this.mainSoundTrack.soundCollection[i];
  27457. if (sound.useCustomAttenuation) {
  27458. sound.updateDistanceFromListener();
  27459. }
  27460. }
  27461. for (i = 0; i < this.soundTracks.length; i++) {
  27462. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27463. sound = this.soundTracks[i].soundCollection[j];
  27464. if (sound.useCustomAttenuation) {
  27465. sound.updateDistanceFromListener();
  27466. }
  27467. }
  27468. }
  27469. }
  27470. };
  27471. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27472. // Audio
  27473. /**
  27474. * Gets or sets if audio support is enabled
  27475. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27476. */
  27477. get: function () {
  27478. return this._audioEnabled;
  27479. },
  27480. set: function (value) {
  27481. this._audioEnabled = value;
  27482. if (BABYLON.AudioEngine) {
  27483. if (this._audioEnabled) {
  27484. this._enableAudio();
  27485. }
  27486. else {
  27487. this._disableAudio();
  27488. }
  27489. }
  27490. },
  27491. enumerable: true,
  27492. configurable: true
  27493. });
  27494. Scene.prototype._disableAudio = function () {
  27495. var i;
  27496. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27497. this.mainSoundTrack.soundCollection[i].pause();
  27498. }
  27499. for (i = 0; i < this.soundTracks.length; i++) {
  27500. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27501. this.soundTracks[i].soundCollection[j].pause();
  27502. }
  27503. }
  27504. };
  27505. Scene.prototype._enableAudio = function () {
  27506. var i;
  27507. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27508. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27509. this.mainSoundTrack.soundCollection[i].play();
  27510. }
  27511. }
  27512. for (i = 0; i < this.soundTracks.length; i++) {
  27513. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27514. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27515. this.soundTracks[i].soundCollection[j].play();
  27516. }
  27517. }
  27518. }
  27519. };
  27520. Object.defineProperty(Scene.prototype, "headphone", {
  27521. /**
  27522. * Gets or sets if audio will be output to headphones
  27523. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27524. */
  27525. get: function () {
  27526. return this._headphone;
  27527. },
  27528. set: function (value) {
  27529. this._headphone = value;
  27530. if (BABYLON.AudioEngine) {
  27531. if (this._headphone) {
  27532. this._switchAudioModeForHeadphones();
  27533. }
  27534. else {
  27535. this._switchAudioModeForNormalSpeakers();
  27536. }
  27537. }
  27538. },
  27539. enumerable: true,
  27540. configurable: true
  27541. });
  27542. Scene.prototype._switchAudioModeForHeadphones = function () {
  27543. this.mainSoundTrack.switchPanningModelToHRTF();
  27544. for (var i = 0; i < this.soundTracks.length; i++) {
  27545. this.soundTracks[i].switchPanningModelToHRTF();
  27546. }
  27547. };
  27548. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27549. this.mainSoundTrack.switchPanningModelToEqualPower();
  27550. for (var i = 0; i < this.soundTracks.length; i++) {
  27551. this.soundTracks[i].switchPanningModelToEqualPower();
  27552. }
  27553. };
  27554. /**
  27555. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27556. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27557. * @returns the created depth renderer
  27558. */
  27559. Scene.prototype.enableDepthRenderer = function (camera) {
  27560. camera = camera || this.activeCamera;
  27561. if (!camera) {
  27562. throw "No camera available to enable depth renderer";
  27563. }
  27564. if (!this._depthRenderer[camera.id]) {
  27565. var textureType = 0;
  27566. if (this._engine.getCaps().textureHalfFloatRender) {
  27567. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27568. }
  27569. else if (this._engine.getCaps().textureFloatRender) {
  27570. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27571. }
  27572. else {
  27573. throw "Depth renderer does not support int texture type";
  27574. }
  27575. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27576. }
  27577. return this._depthRenderer[camera.id];
  27578. };
  27579. /**
  27580. * Disables a depth renderer for a given camera
  27581. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27582. */
  27583. Scene.prototype.disableDepthRenderer = function (camera) {
  27584. camera = camera || this.activeCamera;
  27585. if (!camera || !this._depthRenderer[camera.id]) {
  27586. return;
  27587. }
  27588. this._depthRenderer[camera.id].dispose();
  27589. delete this._depthRenderer[camera.id];
  27590. };
  27591. /**
  27592. * Enables a GeometryBufferRender and associates it with the scene
  27593. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27594. * @returns the GeometryBufferRenderer
  27595. */
  27596. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27597. if (ratio === void 0) { ratio = 1; }
  27598. if (this._geometryBufferRenderer) {
  27599. return this._geometryBufferRenderer;
  27600. }
  27601. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27602. if (!this._geometryBufferRenderer.isSupported) {
  27603. this._geometryBufferRenderer = null;
  27604. }
  27605. return this._geometryBufferRenderer;
  27606. };
  27607. /**
  27608. * Disables the GeometryBufferRender associated with the scene
  27609. */
  27610. Scene.prototype.disableGeometryBufferRenderer = function () {
  27611. if (!this._geometryBufferRenderer) {
  27612. return;
  27613. }
  27614. this._geometryBufferRenderer.dispose();
  27615. this._geometryBufferRenderer = null;
  27616. };
  27617. /**
  27618. * Freeze all materials
  27619. * A frozen material will not be updatable but should be faster to render
  27620. */
  27621. Scene.prototype.freezeMaterials = function () {
  27622. for (var i = 0; i < this.materials.length; i++) {
  27623. this.materials[i].freeze();
  27624. }
  27625. };
  27626. /**
  27627. * Unfreeze all materials
  27628. * A frozen material will not be updatable but should be faster to render
  27629. */
  27630. Scene.prototype.unfreezeMaterials = function () {
  27631. for (var i = 0; i < this.materials.length; i++) {
  27632. this.materials[i].unfreeze();
  27633. }
  27634. };
  27635. /**
  27636. * Releases all held ressources
  27637. */
  27638. Scene.prototype.dispose = function () {
  27639. this.beforeRender = null;
  27640. this.afterRender = null;
  27641. this.skeletons = [];
  27642. this.morphTargetManagers = [];
  27643. this.importedMeshesFiles = new Array();
  27644. this.stopAllAnimations();
  27645. this.resetCachedMaterial();
  27646. for (var key in this._depthRenderer) {
  27647. this._depthRenderer[key].dispose();
  27648. }
  27649. if (this._gamepadManager) {
  27650. this._gamepadManager.dispose();
  27651. this._gamepadManager = null;
  27652. }
  27653. // Smart arrays
  27654. if (this.activeCamera) {
  27655. this.activeCamera._activeMeshes.dispose();
  27656. this.activeCamera = null;
  27657. }
  27658. this._activeMeshes.dispose();
  27659. this._renderingManager.dispose();
  27660. this._processedMaterials.dispose();
  27661. this._activeParticleSystems.dispose();
  27662. this._activeSkeletons.dispose();
  27663. this._softwareSkinnedMeshes.dispose();
  27664. this._renderTargets.dispose();
  27665. this._registeredForLateAnimationBindings.dispose();
  27666. if (this._boundingBoxRenderer) {
  27667. this._boundingBoxRenderer.dispose();
  27668. }
  27669. this._meshesForIntersections.dispose();
  27670. this._toBeDisposed.dispose();
  27671. // Abort active requests
  27672. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27673. var request = _a[_i];
  27674. request.abort();
  27675. }
  27676. // Debug layer
  27677. if (this._debugLayer) {
  27678. this._debugLayer.hide();
  27679. }
  27680. // Events
  27681. this.onDisposeObservable.notifyObservers(this);
  27682. this.onDisposeObservable.clear();
  27683. this.onBeforeRenderObservable.clear();
  27684. this.onAfterRenderObservable.clear();
  27685. this.onBeforeRenderTargetsRenderObservable.clear();
  27686. this.onAfterRenderTargetsRenderObservable.clear();
  27687. this.onAfterStepObservable.clear();
  27688. this.onBeforeStepObservable.clear();
  27689. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27690. this.onAfterActiveMeshesEvaluationObservable.clear();
  27691. this.onBeforeParticlesRenderingObservable.clear();
  27692. this.onAfterParticlesRenderingObservable.clear();
  27693. this.onBeforeSpritesRenderingObservable.clear();
  27694. this.onAfterSpritesRenderingObservable.clear();
  27695. this.onBeforeDrawPhaseObservable.clear();
  27696. this.onAfterDrawPhaseObservable.clear();
  27697. this.onBeforePhysicsObservable.clear();
  27698. this.onAfterPhysicsObservable.clear();
  27699. this.onBeforeAnimationsObservable.clear();
  27700. this.onAfterAnimationsObservable.clear();
  27701. this.onDataLoadedObservable.clear();
  27702. this.detachControl();
  27703. // Release sounds & sounds tracks
  27704. if (BABYLON.AudioEngine) {
  27705. this.disposeSounds();
  27706. }
  27707. // VR Helper
  27708. if (this.VRHelper) {
  27709. this.VRHelper.dispose();
  27710. }
  27711. // Detach cameras
  27712. var canvas = this._engine.getRenderingCanvas();
  27713. if (canvas) {
  27714. var index;
  27715. for (index = 0; index < this.cameras.length; index++) {
  27716. this.cameras[index].detachControl(canvas);
  27717. }
  27718. }
  27719. // Release animation groups
  27720. while (this.animationGroups.length) {
  27721. this.animationGroups[0].dispose();
  27722. }
  27723. // Release lights
  27724. while (this.lights.length) {
  27725. this.lights[0].dispose();
  27726. }
  27727. // Release meshes
  27728. while (this.meshes.length) {
  27729. this.meshes[0].dispose(true);
  27730. }
  27731. while (this.transformNodes.length) {
  27732. this.removeTransformNode(this.transformNodes[0]);
  27733. }
  27734. // Release cameras
  27735. while (this.cameras.length) {
  27736. this.cameras[0].dispose();
  27737. }
  27738. // Release materials
  27739. if (this.defaultMaterial) {
  27740. this.defaultMaterial.dispose();
  27741. }
  27742. while (this.multiMaterials.length) {
  27743. this.multiMaterials[0].dispose();
  27744. }
  27745. while (this.materials.length) {
  27746. this.materials[0].dispose();
  27747. }
  27748. // Release particles
  27749. while (this.particleSystems.length) {
  27750. this.particleSystems[0].dispose();
  27751. }
  27752. // Release sprites
  27753. while (this.spriteManagers.length) {
  27754. this.spriteManagers[0].dispose();
  27755. }
  27756. // Release postProcesses
  27757. while (this.postProcesses.length) {
  27758. this.postProcesses[0].dispose();
  27759. }
  27760. // Release layers
  27761. while (this.layers.length) {
  27762. this.layers[0].dispose();
  27763. }
  27764. while (this.effectLayers.length) {
  27765. this.effectLayers[0].dispose();
  27766. }
  27767. // Release textures
  27768. while (this.textures.length) {
  27769. this.textures[0].dispose();
  27770. }
  27771. // Release UBO
  27772. this._sceneUbo.dispose();
  27773. if (this._alternateSceneUbo) {
  27774. this._alternateSceneUbo.dispose();
  27775. }
  27776. // Post-processes
  27777. this.postProcessManager.dispose();
  27778. if (this._postProcessRenderPipelineManager) {
  27779. this._postProcessRenderPipelineManager.dispose();
  27780. }
  27781. // Physics
  27782. if (this._physicsEngine) {
  27783. this.disablePhysicsEngine();
  27784. }
  27785. // Remove from engine
  27786. index = this._engine.scenes.indexOf(this);
  27787. if (index > -1) {
  27788. this._engine.scenes.splice(index, 1);
  27789. }
  27790. this._engine.wipeCaches(true);
  27791. this._isDisposed = true;
  27792. };
  27793. Object.defineProperty(Scene.prototype, "isDisposed", {
  27794. /**
  27795. * Gets if the scene is already disposed
  27796. */
  27797. get: function () {
  27798. return this._isDisposed;
  27799. },
  27800. enumerable: true,
  27801. configurable: true
  27802. });
  27803. /**
  27804. * Releases sounds & soundtracks
  27805. */
  27806. Scene.prototype.disposeSounds = function () {
  27807. if (!this._mainSoundTrack) {
  27808. return;
  27809. }
  27810. this.mainSoundTrack.dispose();
  27811. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27812. this.soundTracks[scIndex].dispose();
  27813. }
  27814. };
  27815. // Octrees
  27816. /**
  27817. * Get the world extend vectors with an optional filter
  27818. *
  27819. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27820. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27821. */
  27822. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27823. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27824. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27825. filterPredicate = filterPredicate || (function () { return true; });
  27826. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27827. mesh.computeWorldMatrix(true);
  27828. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27829. return;
  27830. }
  27831. var boundingInfo = mesh.getBoundingInfo();
  27832. var minBox = boundingInfo.boundingBox.minimumWorld;
  27833. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27834. BABYLON.Tools.CheckExtends(minBox, min, max);
  27835. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27836. });
  27837. return {
  27838. min: min,
  27839. max: max
  27840. };
  27841. };
  27842. /**
  27843. * Creates or updates the octree used to boost selection (picking)
  27844. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27845. * @param maxCapacity defines the maximum capacity per leaf
  27846. * @param maxDepth defines the maximum depth of the octree
  27847. * @returns an octree of AbstractMesh
  27848. */
  27849. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27850. if (maxCapacity === void 0) { maxCapacity = 64; }
  27851. if (maxDepth === void 0) { maxDepth = 2; }
  27852. if (!this._selectionOctree) {
  27853. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27854. }
  27855. var worldExtends = this.getWorldExtends();
  27856. // Update octree
  27857. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27858. return this._selectionOctree;
  27859. };
  27860. // Picking
  27861. /**
  27862. * Creates a ray that can be used to pick in the scene
  27863. * @param x defines the x coordinate of the origin (on-screen)
  27864. * @param y defines the y coordinate of the origin (on-screen)
  27865. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27866. * @param camera defines the camera to use for the picking
  27867. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27868. * @returns a Ray
  27869. */
  27870. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27871. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27872. var result = BABYLON.Ray.Zero();
  27873. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27874. return result;
  27875. };
  27876. /**
  27877. * Creates a ray that can be used to pick in the scene
  27878. * @param x defines the x coordinate of the origin (on-screen)
  27879. * @param y defines the y coordinate of the origin (on-screen)
  27880. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27881. * @param result defines the ray where to store the picking ray
  27882. * @param camera defines the camera to use for the picking
  27883. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27884. * @returns the current scene
  27885. */
  27886. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27887. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27888. var engine = this._engine;
  27889. if (!camera) {
  27890. if (!this.activeCamera)
  27891. throw new Error("Active camera not set");
  27892. camera = this.activeCamera;
  27893. }
  27894. var cameraViewport = camera.viewport;
  27895. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27896. // Moving coordinates to local viewport world
  27897. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27898. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27899. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27900. return this;
  27901. };
  27902. /**
  27903. * Creates a ray that can be used to pick in the scene
  27904. * @param x defines the x coordinate of the origin (on-screen)
  27905. * @param y defines the y coordinate of the origin (on-screen)
  27906. * @param camera defines the camera to use for the picking
  27907. * @returns a Ray
  27908. */
  27909. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27910. var result = BABYLON.Ray.Zero();
  27911. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27912. return result;
  27913. };
  27914. /**
  27915. * Creates a ray that can be used to pick in the scene
  27916. * @param x defines the x coordinate of the origin (on-screen)
  27917. * @param y defines the y coordinate of the origin (on-screen)
  27918. * @param result defines the ray where to store the picking ray
  27919. * @param camera defines the camera to use for the picking
  27920. * @returns the current scene
  27921. */
  27922. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27923. if (!BABYLON.PickingInfo) {
  27924. return this;
  27925. }
  27926. var engine = this._engine;
  27927. if (!camera) {
  27928. if (!this.activeCamera)
  27929. throw new Error("Active camera not set");
  27930. camera = this.activeCamera;
  27931. }
  27932. var cameraViewport = camera.viewport;
  27933. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27934. var identity = BABYLON.Matrix.Identity();
  27935. // Moving coordinates to local viewport world
  27936. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27937. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27938. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27939. return this;
  27940. };
  27941. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27942. if (!BABYLON.PickingInfo) {
  27943. return null;
  27944. }
  27945. var pickingInfo = null;
  27946. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27947. var mesh = this.meshes[meshIndex];
  27948. if (predicate) {
  27949. if (!predicate(mesh)) {
  27950. continue;
  27951. }
  27952. }
  27953. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27954. continue;
  27955. }
  27956. var world = mesh.getWorldMatrix();
  27957. var ray = rayFunction(world);
  27958. var result = mesh.intersects(ray, fastCheck);
  27959. if (!result || !result.hit)
  27960. continue;
  27961. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27962. continue;
  27963. pickingInfo = result;
  27964. if (fastCheck) {
  27965. break;
  27966. }
  27967. }
  27968. return pickingInfo || new BABYLON.PickingInfo();
  27969. };
  27970. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27971. if (!BABYLON.PickingInfo) {
  27972. return null;
  27973. }
  27974. var pickingInfos = new Array();
  27975. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27976. var mesh = this.meshes[meshIndex];
  27977. if (predicate) {
  27978. if (!predicate(mesh)) {
  27979. continue;
  27980. }
  27981. }
  27982. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27983. continue;
  27984. }
  27985. var world = mesh.getWorldMatrix();
  27986. var ray = rayFunction(world);
  27987. var result = mesh.intersects(ray, false);
  27988. if (!result || !result.hit)
  27989. continue;
  27990. pickingInfos.push(result);
  27991. }
  27992. return pickingInfos;
  27993. };
  27994. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27995. if (!BABYLON.PickingInfo) {
  27996. return null;
  27997. }
  27998. var pickingInfo = null;
  27999. if (!camera) {
  28000. if (!this.activeCamera) {
  28001. return null;
  28002. }
  28003. camera = this.activeCamera;
  28004. }
  28005. if (this.spriteManagers.length > 0) {
  28006. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28007. var spriteManager = this.spriteManagers[spriteIndex];
  28008. if (!spriteManager.isPickable) {
  28009. continue;
  28010. }
  28011. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28012. if (!result || !result.hit)
  28013. continue;
  28014. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28015. continue;
  28016. pickingInfo = result;
  28017. if (fastCheck) {
  28018. break;
  28019. }
  28020. }
  28021. }
  28022. return pickingInfo || new BABYLON.PickingInfo();
  28023. };
  28024. /** Launch a ray to try to pick a mesh in the scene
  28025. * @param x position on screen
  28026. * @param y position on screen
  28027. * @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
  28028. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28029. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28030. * @returns a PickingInfo
  28031. */
  28032. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28033. var _this = this;
  28034. if (!BABYLON.PickingInfo) {
  28035. return null;
  28036. }
  28037. return this._internalPick(function (world) {
  28038. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28039. return _this._tempPickingRay;
  28040. }, predicate, fastCheck);
  28041. };
  28042. /** Launch a ray to try to pick a sprite in the scene
  28043. * @param x position on screen
  28044. * @param y position on screen
  28045. * @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
  28046. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28047. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28048. * @returns a PickingInfo
  28049. */
  28050. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28051. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28052. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28053. };
  28054. /** Use the given ray to pick a mesh in the scene
  28055. * @param ray The ray to use to pick meshes
  28056. * @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
  28057. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28058. * @returns a PickingInfo
  28059. */
  28060. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28061. var _this = this;
  28062. return this._internalPick(function (world) {
  28063. if (!_this._pickWithRayInverseMatrix) {
  28064. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28065. }
  28066. world.invertToRef(_this._pickWithRayInverseMatrix);
  28067. if (!_this._cachedRayForTransform) {
  28068. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28069. }
  28070. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28071. return _this._cachedRayForTransform;
  28072. }, predicate, fastCheck);
  28073. };
  28074. /**
  28075. * Launch a ray to try to pick a mesh in the scene
  28076. * @param x X position on screen
  28077. * @param y Y position on screen
  28078. * @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
  28079. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28080. * @returns an array of PickingInfo
  28081. */
  28082. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28083. var _this = this;
  28084. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28085. };
  28086. /**
  28087. * Launch a ray to try to pick a mesh in the scene
  28088. * @param ray Ray to use
  28089. * @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
  28090. * @returns an array of PickingInfo
  28091. */
  28092. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28093. var _this = this;
  28094. return this._internalMultiPick(function (world) {
  28095. if (!_this._pickWithRayInverseMatrix) {
  28096. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28097. }
  28098. world.invertToRef(_this._pickWithRayInverseMatrix);
  28099. if (!_this._cachedRayForTransform) {
  28100. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28101. }
  28102. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28103. return _this._cachedRayForTransform;
  28104. }, predicate);
  28105. };
  28106. /**
  28107. * Force the value of meshUnderPointer
  28108. * @param mesh defines the mesh to use
  28109. */
  28110. Scene.prototype.setPointerOverMesh = function (mesh) {
  28111. if (this._pointerOverMesh === mesh) {
  28112. return;
  28113. }
  28114. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28115. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28116. }
  28117. this._pointerOverMesh = mesh;
  28118. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28119. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28120. }
  28121. };
  28122. /**
  28123. * Gets the mesh under the pointer
  28124. * @returns a Mesh or null if no mesh is under the pointer
  28125. */
  28126. Scene.prototype.getPointerOverMesh = function () {
  28127. return this._pointerOverMesh;
  28128. };
  28129. /**
  28130. * Force the sprite under the pointer
  28131. * @param sprite defines the sprite to use
  28132. */
  28133. Scene.prototype.setPointerOverSprite = function (sprite) {
  28134. if (this._pointerOverSprite === sprite) {
  28135. return;
  28136. }
  28137. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28138. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28139. }
  28140. this._pointerOverSprite = sprite;
  28141. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28142. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28143. }
  28144. };
  28145. /**
  28146. * Gets the sprite under the pointer
  28147. * @returns a Sprite or null if no sprite is under the pointer
  28148. */
  28149. Scene.prototype.getPointerOverSprite = function () {
  28150. return this._pointerOverSprite;
  28151. };
  28152. // Physics
  28153. /**
  28154. * Gets the current physics engine
  28155. * @returns a PhysicsEngine or null if none attached
  28156. */
  28157. Scene.prototype.getPhysicsEngine = function () {
  28158. return this._physicsEngine;
  28159. };
  28160. /**
  28161. * Enables physics to the current scene
  28162. * @param gravity defines the scene's gravity for the physics engine
  28163. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28164. * @return a boolean indicating if the physics engine was initialized
  28165. */
  28166. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28167. if (gravity === void 0) { gravity = null; }
  28168. if (this._physicsEngine) {
  28169. return true;
  28170. }
  28171. try {
  28172. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28173. return true;
  28174. }
  28175. catch (e) {
  28176. BABYLON.Tools.Error(e.message);
  28177. return false;
  28178. }
  28179. };
  28180. /**
  28181. * Disables and disposes the physics engine associated with the scene
  28182. */
  28183. Scene.prototype.disablePhysicsEngine = function () {
  28184. if (!this._physicsEngine) {
  28185. return;
  28186. }
  28187. this._physicsEngine.dispose();
  28188. this._physicsEngine = null;
  28189. };
  28190. /**
  28191. * Gets a boolean indicating if there is an active physics engine
  28192. * @returns a boolean indicating if there is an active physics engine
  28193. */
  28194. Scene.prototype.isPhysicsEnabled = function () {
  28195. return this._physicsEngine !== undefined;
  28196. };
  28197. /**
  28198. * Deletes a physics compound impostor
  28199. * @param compound defines the compound to delete
  28200. */
  28201. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28202. var mesh = compound.parts[0].mesh;
  28203. if (mesh.physicsImpostor) {
  28204. mesh.physicsImpostor.dispose( /*true*/);
  28205. mesh.physicsImpostor = null;
  28206. }
  28207. };
  28208. // Misc.
  28209. /** @ignore */
  28210. Scene.prototype._rebuildGeometries = function () {
  28211. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28212. var geometry = _a[_i];
  28213. geometry._rebuild();
  28214. }
  28215. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28216. var mesh = _c[_b];
  28217. mesh._rebuild();
  28218. }
  28219. if (this.postProcessManager) {
  28220. this.postProcessManager._rebuild();
  28221. }
  28222. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28223. var layer = _e[_d];
  28224. layer._rebuild();
  28225. }
  28226. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28227. var effectLayer = _g[_f];
  28228. effectLayer._rebuild();
  28229. }
  28230. if (this._boundingBoxRenderer) {
  28231. this._boundingBoxRenderer._rebuild();
  28232. }
  28233. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28234. var system = _j[_h];
  28235. system.rebuild();
  28236. }
  28237. if (this._postProcessRenderPipelineManager) {
  28238. this._postProcessRenderPipelineManager._rebuild();
  28239. }
  28240. };
  28241. /** @ignore */
  28242. Scene.prototype._rebuildTextures = function () {
  28243. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28244. var texture = _a[_i];
  28245. texture._rebuild();
  28246. }
  28247. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28248. };
  28249. /**
  28250. * Creates a default light for the scene.
  28251. * @param replace Whether to replace the existing lights in the scene.
  28252. */
  28253. Scene.prototype.createDefaultLight = function (replace) {
  28254. if (replace === void 0) { replace = false; }
  28255. // Dispose existing light in replace mode.
  28256. if (replace) {
  28257. if (this.lights) {
  28258. for (var i = 0; i < this.lights.length; i++) {
  28259. this.lights[i].dispose();
  28260. }
  28261. }
  28262. }
  28263. // Light
  28264. if (this.lights.length === 0) {
  28265. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28266. }
  28267. };
  28268. /**
  28269. * Creates a default camera for the scene.
  28270. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28271. * @param replace Whether to replace the existing active camera in the scene.
  28272. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28273. */
  28274. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28275. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28276. if (replace === void 0) { replace = false; }
  28277. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28278. // Dispose existing camera in replace mode.
  28279. if (replace) {
  28280. if (this.activeCamera) {
  28281. this.activeCamera.dispose();
  28282. this.activeCamera = null;
  28283. }
  28284. }
  28285. // Camera
  28286. if (!this.activeCamera) {
  28287. var worldExtends = this.getWorldExtends();
  28288. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28289. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28290. var camera;
  28291. var radius = worldSize.length() * 1.5;
  28292. // empty scene scenario!
  28293. if (!isFinite(radius)) {
  28294. radius = 1;
  28295. worldCenter.copyFromFloats(0, 0, 0);
  28296. }
  28297. if (createArcRotateCamera) {
  28298. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28299. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28300. arcRotateCamera.wheelPrecision = 100 / radius;
  28301. camera = arcRotateCamera;
  28302. }
  28303. else {
  28304. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28305. freeCamera.setTarget(worldCenter);
  28306. camera = freeCamera;
  28307. }
  28308. camera.minZ = radius * 0.01;
  28309. camera.maxZ = radius * 1000;
  28310. camera.speed = radius * 0.2;
  28311. this.activeCamera = camera;
  28312. var canvas = this.getEngine().getRenderingCanvas();
  28313. if (attachCameraControls && canvas) {
  28314. camera.attachControl(canvas);
  28315. }
  28316. }
  28317. };
  28318. /**
  28319. * Creates a default camera and a default light
  28320. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28321. * @param replace defines if the camera and/or light will replace the existing ones
  28322. * @param attachCameraControls defines if attachControl will be called on the new camera
  28323. */
  28324. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28325. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28326. if (replace === void 0) { replace = false; }
  28327. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28328. this.createDefaultLight(replace);
  28329. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28330. };
  28331. /**
  28332. * Creates a new sky box
  28333. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28334. * @param environmentTexture defines the texture to use as environment texture
  28335. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28336. * @param scale defines the overall scale of the skybox
  28337. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28338. * @returns a new mesh holding the sky box
  28339. */
  28340. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  28341. if (pbr === void 0) { pbr = false; }
  28342. if (scale === void 0) { scale = 1000; }
  28343. if (blur === void 0) { blur = 0; }
  28344. if (environmentTexture) {
  28345. this.environmentTexture = environmentTexture;
  28346. }
  28347. if (!this.environmentTexture) {
  28348. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28349. return null;
  28350. }
  28351. // Skybox
  28352. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28353. if (pbr) {
  28354. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28355. hdrSkyboxMaterial.backFaceCulling = false;
  28356. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28357. if (hdrSkyboxMaterial.reflectionTexture) {
  28358. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28359. }
  28360. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28361. hdrSkyboxMaterial.disableLighting = true;
  28362. hdrSkyboxMaterial.twoSidedLighting = true;
  28363. hdrSkybox.infiniteDistance = true;
  28364. hdrSkybox.material = hdrSkyboxMaterial;
  28365. }
  28366. else {
  28367. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28368. skyboxMaterial.backFaceCulling = false;
  28369. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28370. if (skyboxMaterial.reflectionTexture) {
  28371. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28372. }
  28373. skyboxMaterial.disableLighting = true;
  28374. hdrSkybox.infiniteDistance = true;
  28375. hdrSkybox.material = skyboxMaterial;
  28376. }
  28377. return hdrSkybox;
  28378. };
  28379. /**
  28380. * Creates a new environment
  28381. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28382. * @param options defines the options you can use to configure the environment
  28383. * @returns the new EnvironmentHelper
  28384. */
  28385. Scene.prototype.createDefaultEnvironment = function (options) {
  28386. if (BABYLON.EnvironmentHelper) {
  28387. return new BABYLON.EnvironmentHelper(options, this);
  28388. }
  28389. return null;
  28390. };
  28391. /**
  28392. * Creates a new VREXperienceHelper
  28393. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28394. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28395. * @returns a new VREXperienceHelper
  28396. */
  28397. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28398. if (webVROptions === void 0) { webVROptions = {}; }
  28399. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28400. };
  28401. // Tags
  28402. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28403. if (tagsQuery === undefined) {
  28404. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28405. return list;
  28406. }
  28407. var listByTags = [];
  28408. forEach = forEach || (function (item) { return; });
  28409. for (var i in list) {
  28410. var item = list[i];
  28411. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28412. listByTags.push(item);
  28413. forEach(item);
  28414. }
  28415. }
  28416. return listByTags;
  28417. };
  28418. /**
  28419. * Get a list of meshes by tags
  28420. * @param tagsQuery defines the tags query to use
  28421. * @param forEach defines a predicate used to filter results
  28422. * @returns an array of Mesh
  28423. */
  28424. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28425. return this._getByTags(this.meshes, tagsQuery, forEach);
  28426. };
  28427. /**
  28428. * Get a list of cameras by tags
  28429. * @param tagsQuery defines the tags query to use
  28430. * @param forEach defines a predicate used to filter results
  28431. * @returns an array of Camera
  28432. */
  28433. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28434. return this._getByTags(this.cameras, tagsQuery, forEach);
  28435. };
  28436. /**
  28437. * Get a list of lights by tags
  28438. * @param tagsQuery defines the tags query to use
  28439. * @param forEach defines a predicate used to filter results
  28440. * @returns an array of Light
  28441. */
  28442. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28443. return this._getByTags(this.lights, tagsQuery, forEach);
  28444. };
  28445. /**
  28446. * Get a list of materials by tags
  28447. * @param tagsQuery defines the tags query to use
  28448. * @param forEach defines a predicate used to filter results
  28449. * @returns an array of Material
  28450. */
  28451. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28452. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28453. };
  28454. /**
  28455. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28456. * This allowed control for front to back rendering or reversly depending of the special needs.
  28457. *
  28458. * @param renderingGroupId The rendering group id corresponding to its index
  28459. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28460. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28461. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28462. */
  28463. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28464. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28465. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28466. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28467. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28468. };
  28469. /**
  28470. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28471. *
  28472. * @param renderingGroupId The rendering group id corresponding to its index
  28473. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28474. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28475. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28476. */
  28477. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28478. if (depth === void 0) { depth = true; }
  28479. if (stencil === void 0) { stencil = true; }
  28480. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28481. };
  28482. /**
  28483. * Will flag all materials as dirty to trigger new shader compilation
  28484. * @param flag defines the flag used to specify which material part must be marked as dirty
  28485. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28486. */
  28487. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28488. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28489. var material = _a[_i];
  28490. if (predicate && !predicate(material)) {
  28491. continue;
  28492. }
  28493. material.markAsDirty(flag);
  28494. }
  28495. };
  28496. /** @ignore */
  28497. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28498. var _this = this;
  28499. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28500. this._activeRequests.push(request);
  28501. request.onCompleteObservable.add(function (request) {
  28502. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28503. });
  28504. return request;
  28505. };
  28506. /** @ignore */
  28507. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28508. var _this = this;
  28509. return new Promise(function (resolve, reject) {
  28510. _this._loadFile(url, function (data) {
  28511. resolve(data);
  28512. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28513. reject(exception);
  28514. });
  28515. });
  28516. };
  28517. // Statics
  28518. Scene._FOGMODE_NONE = 0;
  28519. Scene._FOGMODE_EXP = 1;
  28520. Scene._FOGMODE_EXP2 = 2;
  28521. Scene._FOGMODE_LINEAR = 3;
  28522. Scene._uniqueIdCounter = 0;
  28523. /**
  28524. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28525. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28526. */
  28527. Scene.MinDeltaTime = 1.0;
  28528. /**
  28529. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28530. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28531. */
  28532. Scene.MaxDeltaTime = 1000.0;
  28533. /** The distance in pixel that you have to move to prevent some events */
  28534. Scene.DragMovementThreshold = 10; // in pixels
  28535. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28536. Scene.LongPressDelay = 500; // in milliseconds
  28537. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28538. Scene.DoubleClickDelay = 300; // in milliseconds
  28539. /** If you need to check double click without raising a single click at first click, enable this flag */
  28540. Scene.ExclusiveDoubleClickMode = false;
  28541. return Scene;
  28542. }());
  28543. BABYLON.Scene = Scene;
  28544. })(BABYLON || (BABYLON = {}));
  28545. //# sourceMappingURL=babylon.scene.js.map
  28546. var BABYLON;
  28547. (function (BABYLON) {
  28548. /**
  28549. * Set of assets to keep when moving a scene into an asset container.
  28550. */
  28551. var KeepAssets = /** @class */ (function () {
  28552. function KeepAssets() {
  28553. /**
  28554. * Cameras to keep.
  28555. */
  28556. this.cameras = new Array();
  28557. /**
  28558. * Lights to keep.
  28559. */
  28560. this.lights = new Array();
  28561. /**
  28562. * Meshes to keep.
  28563. */
  28564. this.meshes = new Array();
  28565. /**
  28566. * Skeletons to keep.
  28567. */
  28568. this.skeletons = new Array();
  28569. /**
  28570. * ParticleSystems to keep.
  28571. */
  28572. this.particleSystems = new Array();
  28573. /**
  28574. * Animations to keep.
  28575. */
  28576. this.animations = new Array();
  28577. /**
  28578. * AnimationGroups to keep.
  28579. */
  28580. this.animationGroups = new Array();
  28581. /**
  28582. * MultiMaterials to keep.
  28583. */
  28584. this.multiMaterials = new Array();
  28585. /**
  28586. * Materials to keep.
  28587. */
  28588. this.materials = new Array();
  28589. /**
  28590. * MorphTargetManagers to keep.
  28591. */
  28592. this.morphTargetManagers = new Array();
  28593. /**
  28594. * Geometries to keep.
  28595. */
  28596. this.geometries = new Array();
  28597. /**
  28598. * TransformNodes to keep.
  28599. */
  28600. this.transformNodes = new Array();
  28601. /**
  28602. * LensFlareSystems to keep.
  28603. */
  28604. this.lensFlareSystems = new Array();
  28605. /**
  28606. * ShadowGenerators to keep.
  28607. */
  28608. this.shadowGenerators = new Array();
  28609. /**
  28610. * ActionManagers to keep.
  28611. */
  28612. this.actionManagers = new Array();
  28613. /**
  28614. * Sounds to keep.
  28615. */
  28616. this.sounds = new Array();
  28617. /**
  28618. * Textures to keep.
  28619. */
  28620. this.textures = new Array();
  28621. /**
  28622. * Effect layers to keep.
  28623. */
  28624. this.effectLayers = new Array();
  28625. }
  28626. return KeepAssets;
  28627. }());
  28628. BABYLON.KeepAssets = KeepAssets;
  28629. /**
  28630. * Container with a set of assets that can be added or removed from a scene.
  28631. */
  28632. var AssetContainer = /** @class */ (function () {
  28633. /**
  28634. * Instantiates an AssetContainer.
  28635. * @param scene The scene the AssetContainer belongs to.
  28636. */
  28637. function AssetContainer(scene) {
  28638. // Objects
  28639. /**
  28640. * Cameras populated in the container.
  28641. */
  28642. this.cameras = new Array();
  28643. /**
  28644. * Lights populated in the container.
  28645. */
  28646. this.lights = new Array();
  28647. /**
  28648. * Meshes populated in the container.
  28649. */
  28650. this.meshes = new Array();
  28651. /**
  28652. * Skeletons populated in the container.
  28653. */
  28654. this.skeletons = new Array();
  28655. /**
  28656. * ParticleSystems populated in the container.
  28657. */
  28658. this.particleSystems = new Array();
  28659. /**
  28660. * Animations populated in the container.
  28661. */
  28662. this.animations = new Array();
  28663. /**
  28664. * AnimationGroups populated in the container.
  28665. */
  28666. this.animationGroups = new Array();
  28667. /**
  28668. * MultiMaterials populated in the container.
  28669. */
  28670. this.multiMaterials = new Array();
  28671. /**
  28672. * Materials populated in the container.
  28673. */
  28674. this.materials = new Array();
  28675. /**
  28676. * MorphTargetManagers populated in the container.
  28677. */
  28678. this.morphTargetManagers = new Array();
  28679. /**
  28680. * Geometries populated in the container.
  28681. */
  28682. this.geometries = new Array();
  28683. /**
  28684. * TransformNodes populated in the container.
  28685. */
  28686. this.transformNodes = new Array();
  28687. /**
  28688. * LensFlareSystems populated in the container.
  28689. */
  28690. this.lensFlareSystems = new Array();
  28691. /**
  28692. * ShadowGenerators populated in the container.
  28693. */
  28694. this.shadowGenerators = new Array();
  28695. /**
  28696. * ActionManagers populated in the container.
  28697. */
  28698. this.actionManagers = new Array();
  28699. /**
  28700. * Sounds populated in the container.
  28701. */
  28702. this.sounds = new Array();
  28703. /**
  28704. * Textures populated in the container.
  28705. */
  28706. this.textures = new Array();
  28707. /**
  28708. * Effect layers populated in the container.
  28709. */
  28710. this.effectLayers = new Array();
  28711. this.scene = scene;
  28712. }
  28713. /**
  28714. * Adds all the assets from the container to the scene.
  28715. */
  28716. AssetContainer.prototype.addAllToScene = function () {
  28717. var _this = this;
  28718. this.cameras.forEach(function (o) {
  28719. _this.scene.addCamera(o);
  28720. });
  28721. this.lights.forEach(function (o) {
  28722. _this.scene.addLight(o);
  28723. });
  28724. this.meshes.forEach(function (o) {
  28725. _this.scene.addMesh(o);
  28726. });
  28727. this.skeletons.forEach(function (o) {
  28728. _this.scene.addSkeleton(o);
  28729. });
  28730. this.particleSystems.forEach(function (o) {
  28731. _this.scene.addParticleSystem(o);
  28732. });
  28733. this.animations.forEach(function (o) {
  28734. _this.scene.addAnimation(o);
  28735. });
  28736. this.animationGroups.forEach(function (o) {
  28737. _this.scene.addAnimationGroup(o);
  28738. });
  28739. this.multiMaterials.forEach(function (o) {
  28740. _this.scene.addMultiMaterial(o);
  28741. });
  28742. this.materials.forEach(function (o) {
  28743. _this.scene.addMaterial(o);
  28744. });
  28745. this.morphTargetManagers.forEach(function (o) {
  28746. _this.scene.addMorphTargetManager(o);
  28747. });
  28748. this.geometries.forEach(function (o) {
  28749. _this.scene.addGeometry(o);
  28750. });
  28751. this.transformNodes.forEach(function (o) {
  28752. _this.scene.addTransformNode(o);
  28753. });
  28754. this.lensFlareSystems.forEach(function (o) {
  28755. _this.scene.addLensFlareSystem(o);
  28756. });
  28757. this.actionManagers.forEach(function (o) {
  28758. _this.scene.addActionManager(o);
  28759. });
  28760. this.sounds.forEach(function (o) {
  28761. o.play();
  28762. o.autoplay = true;
  28763. _this.scene.mainSoundTrack.AddSound(o);
  28764. });
  28765. this.textures.forEach(function (o) {
  28766. _this.scene.addTexture(o);
  28767. });
  28768. this.effectLayers.forEach(function (o) {
  28769. _this.scene.addEffectLayer(o);
  28770. });
  28771. };
  28772. /**
  28773. * Removes all the assets in the container from the scene
  28774. */
  28775. AssetContainer.prototype.removeAllFromScene = function () {
  28776. var _this = this;
  28777. this.cameras.forEach(function (o) {
  28778. _this.scene.removeCamera(o);
  28779. });
  28780. this.lights.forEach(function (o) {
  28781. _this.scene.removeLight(o);
  28782. });
  28783. this.meshes.forEach(function (o) {
  28784. _this.scene.removeMesh(o);
  28785. });
  28786. this.skeletons.forEach(function (o) {
  28787. _this.scene.removeSkeleton(o);
  28788. });
  28789. this.particleSystems.forEach(function (o) {
  28790. _this.scene.removeParticleSystem(o);
  28791. });
  28792. this.animations.forEach(function (o) {
  28793. _this.scene.removeAnimation(o);
  28794. });
  28795. this.animationGroups.forEach(function (o) {
  28796. _this.scene.removeAnimationGroup(o);
  28797. });
  28798. this.multiMaterials.forEach(function (o) {
  28799. _this.scene.removeMultiMaterial(o);
  28800. });
  28801. this.materials.forEach(function (o) {
  28802. _this.scene.removeMaterial(o);
  28803. });
  28804. this.morphTargetManagers.forEach(function (o) {
  28805. _this.scene.removeMorphTargetManager(o);
  28806. });
  28807. this.geometries.forEach(function (o) {
  28808. _this.scene.removeGeometry(o);
  28809. });
  28810. this.transformNodes.forEach(function (o) {
  28811. _this.scene.removeTransformNode(o);
  28812. });
  28813. this.lensFlareSystems.forEach(function (o) {
  28814. _this.scene.removeLensFlareSystem(o);
  28815. });
  28816. this.actionManagers.forEach(function (o) {
  28817. _this.scene.removeActionManager(o);
  28818. });
  28819. this.sounds.forEach(function (o) {
  28820. o.stop();
  28821. o.autoplay = false;
  28822. _this.scene.mainSoundTrack.RemoveSound(o);
  28823. });
  28824. this.textures.forEach(function (o) {
  28825. _this.scene.removeTexture(o);
  28826. });
  28827. this.effectLayers.forEach(function (o) {
  28828. _this.scene.removeEffectLayer(o);
  28829. });
  28830. };
  28831. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28832. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28833. var asset = sourceAssets_1[_i];
  28834. var move = true;
  28835. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28836. var keepAsset = keepAssets_1[_a];
  28837. if (asset === keepAsset) {
  28838. move = false;
  28839. break;
  28840. }
  28841. }
  28842. if (move) {
  28843. targetAssets.push(asset);
  28844. }
  28845. }
  28846. };
  28847. /**
  28848. * Removes all the assets contained in the scene and adds them to the container.
  28849. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28850. */
  28851. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28852. if (keepAssets === undefined) {
  28853. keepAssets = new KeepAssets();
  28854. }
  28855. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28856. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28857. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28858. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28859. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28860. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28861. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28862. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28863. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28864. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28865. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28866. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28867. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28868. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28869. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28870. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28871. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28872. this.removeAllFromScene();
  28873. };
  28874. return AssetContainer;
  28875. }());
  28876. BABYLON.AssetContainer = AssetContainer;
  28877. })(BABYLON || (BABYLON = {}));
  28878. //# sourceMappingURL=babylon.assetContainer.js.map
  28879. var BABYLON;
  28880. (function (BABYLON) {
  28881. var Buffer = /** @class */ (function () {
  28882. /**
  28883. * Constructor
  28884. * @param engine the engine
  28885. * @param data the data to use for this buffer
  28886. * @param updatable whether the data is updatable
  28887. * @param stride the stride (optional)
  28888. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28889. * @param instanced whether the buffer is instanced (optional)
  28890. * @param useBytes set to true if the stride in in bytes (optional)
  28891. */
  28892. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28893. if (stride === void 0) { stride = 0; }
  28894. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28895. if (instanced === void 0) { instanced = false; }
  28896. if (useBytes === void 0) { useBytes = false; }
  28897. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28898. this._engine = engine.getScene().getEngine();
  28899. }
  28900. else {
  28901. this._engine = engine;
  28902. }
  28903. this._updatable = updatable;
  28904. this._instanced = instanced;
  28905. this._data = data;
  28906. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28907. if (!postponeInternalCreation) { // by default
  28908. this.create();
  28909. }
  28910. }
  28911. /**
  28912. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28913. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28914. * @param offset defines offset in the buffer (0 by default)
  28915. * @param size defines the size in floats of attributes (position is 3 for instance)
  28916. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28917. * @param instanced defines if the vertex buffer contains indexed data
  28918. * @param useBytes defines if the offset and stride are in bytes
  28919. * @returns the new vertex buffer
  28920. */
  28921. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28922. if (useBytes === void 0) { useBytes = false; }
  28923. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28924. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28925. // a lot of these parameters are ignored as they are overriden by the buffer
  28926. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28927. };
  28928. // Properties
  28929. Buffer.prototype.isUpdatable = function () {
  28930. return this._updatable;
  28931. };
  28932. Buffer.prototype.getData = function () {
  28933. return this._data;
  28934. };
  28935. Buffer.prototype.getBuffer = function () {
  28936. return this._buffer;
  28937. };
  28938. /**
  28939. * Gets the stride in float32 units (i.e. byte stride / 4).
  28940. * May not be an integer if the byte stride is not divisible by 4.
  28941. * DEPRECATED. Use byteStride instead.
  28942. * @returns the stride in float32 units
  28943. */
  28944. Buffer.prototype.getStrideSize = function () {
  28945. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28946. };
  28947. // Methods
  28948. Buffer.prototype.create = function (data) {
  28949. if (data === void 0) { data = null; }
  28950. if (!data && this._buffer) {
  28951. return; // nothing to do
  28952. }
  28953. data = data || this._data;
  28954. if (!data) {
  28955. return;
  28956. }
  28957. if (!this._buffer) { // create buffer
  28958. if (this._updatable) {
  28959. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28960. this._data = data;
  28961. }
  28962. else {
  28963. this._buffer = this._engine.createVertexBuffer(data);
  28964. }
  28965. }
  28966. else if (this._updatable) { // update buffer
  28967. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28968. this._data = data;
  28969. }
  28970. };
  28971. Buffer.prototype._rebuild = function () {
  28972. this._buffer = null;
  28973. this.create(this._data);
  28974. };
  28975. Buffer.prototype.update = function (data) {
  28976. this.create(data);
  28977. };
  28978. /**
  28979. * Updates the data directly.
  28980. * @param data the new data
  28981. * @param offset the new offset
  28982. * @param vertexCount the vertex count (optional)
  28983. * @param useBytes set to true if the offset is in bytes
  28984. */
  28985. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28986. if (useBytes === void 0) { useBytes = false; }
  28987. if (!this._buffer) {
  28988. return;
  28989. }
  28990. if (this._updatable) { // update buffer
  28991. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28992. this._data = null;
  28993. }
  28994. };
  28995. Buffer.prototype.dispose = function () {
  28996. if (!this._buffer) {
  28997. return;
  28998. }
  28999. if (this._engine._releaseBuffer(this._buffer)) {
  29000. this._buffer = null;
  29001. }
  29002. };
  29003. return Buffer;
  29004. }());
  29005. BABYLON.Buffer = Buffer;
  29006. })(BABYLON || (BABYLON = {}));
  29007. //# sourceMappingURL=babylon.buffer.js.map
  29008. var BABYLON;
  29009. (function (BABYLON) {
  29010. var VertexBuffer = /** @class */ (function () {
  29011. /**
  29012. * Constructor
  29013. * @param engine the engine
  29014. * @param data the data to use for this vertex buffer
  29015. * @param kind the vertex buffer kind
  29016. * @param updatable whether the data is updatable
  29017. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29018. * @param stride the stride (optional)
  29019. * @param instanced whether the buffer is instanced (optional)
  29020. * @param offset the offset of the data (optional)
  29021. * @param size the number of components (optional)
  29022. * @param type the type of the component (optional)
  29023. * @param normalized whether the data contains normalized data (optional)
  29024. * @param useBytes set to true if stride and offset are in bytes (optional)
  29025. */
  29026. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29027. if (normalized === void 0) { normalized = false; }
  29028. if (useBytes === void 0) { useBytes = false; }
  29029. if (data instanceof BABYLON.Buffer) {
  29030. this._buffer = data;
  29031. this._ownsBuffer = false;
  29032. }
  29033. else {
  29034. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29035. this._ownsBuffer = true;
  29036. }
  29037. this._kind = kind;
  29038. if (type == undefined) {
  29039. var data_1 = this.getData();
  29040. this.type = VertexBuffer.FLOAT;
  29041. if (data_1 instanceof Int8Array)
  29042. this.type = VertexBuffer.BYTE;
  29043. else if (data_1 instanceof Uint8Array)
  29044. this.type = VertexBuffer.UNSIGNED_BYTE;
  29045. else if (data_1 instanceof Int16Array)
  29046. this.type = VertexBuffer.SHORT;
  29047. else if (data_1 instanceof Uint16Array)
  29048. this.type = VertexBuffer.UNSIGNED_SHORT;
  29049. else if (data_1 instanceof Int32Array)
  29050. this.type = VertexBuffer.INT;
  29051. else if (data_1 instanceof Uint32Array)
  29052. this.type = VertexBuffer.UNSIGNED_INT;
  29053. }
  29054. else {
  29055. this.type = type;
  29056. }
  29057. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29058. if (useBytes) {
  29059. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29060. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29061. this.byteOffset = offset || 0;
  29062. }
  29063. else {
  29064. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29065. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29066. this.byteOffset = (offset || 0) * typeByteLength;
  29067. }
  29068. this.normalized = normalized;
  29069. this._instanced = instanced !== undefined ? instanced : false;
  29070. this._instanceDivisor = instanced ? 1 : 0;
  29071. }
  29072. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29073. /**
  29074. * Gets or sets the instance divisor when in instanced mode
  29075. */
  29076. get: function () {
  29077. return this._instanceDivisor;
  29078. },
  29079. set: function (value) {
  29080. this._instanceDivisor = value;
  29081. if (value == 0) {
  29082. this._instanced = false;
  29083. }
  29084. else {
  29085. this._instanced = true;
  29086. }
  29087. },
  29088. enumerable: true,
  29089. configurable: true
  29090. });
  29091. VertexBuffer.prototype._rebuild = function () {
  29092. if (!this._buffer) {
  29093. return;
  29094. }
  29095. this._buffer._rebuild();
  29096. };
  29097. /**
  29098. * Returns the kind of the VertexBuffer (string).
  29099. */
  29100. VertexBuffer.prototype.getKind = function () {
  29101. return this._kind;
  29102. };
  29103. // Properties
  29104. /**
  29105. * Boolean : is the VertexBuffer updatable ?
  29106. */
  29107. VertexBuffer.prototype.isUpdatable = function () {
  29108. return this._buffer.isUpdatable();
  29109. };
  29110. /**
  29111. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29112. */
  29113. VertexBuffer.prototype.getData = function () {
  29114. return this._buffer.getData();
  29115. };
  29116. /**
  29117. * Returns the WebGLBuffer associated to the VertexBuffer.
  29118. */
  29119. VertexBuffer.prototype.getBuffer = function () {
  29120. return this._buffer.getBuffer();
  29121. };
  29122. /**
  29123. * Returns the stride as a multiple of the type byte length.
  29124. * DEPRECATED. Use byteStride instead.
  29125. */
  29126. VertexBuffer.prototype.getStrideSize = function () {
  29127. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29128. };
  29129. /**
  29130. * Returns the offset as a multiple of the type byte length.
  29131. * DEPRECATED. Use byteOffset instead.
  29132. */
  29133. VertexBuffer.prototype.getOffset = function () {
  29134. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29135. };
  29136. /**
  29137. * Returns the number of components per vertex attribute (integer).
  29138. */
  29139. VertexBuffer.prototype.getSize = function () {
  29140. return this._size;
  29141. };
  29142. /**
  29143. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29144. */
  29145. VertexBuffer.prototype.getIsInstanced = function () {
  29146. return this._instanced;
  29147. };
  29148. /**
  29149. * Returns the instancing divisor, zero for non-instanced (integer).
  29150. */
  29151. VertexBuffer.prototype.getInstanceDivisor = function () {
  29152. return this._instanceDivisor;
  29153. };
  29154. // Methods
  29155. /**
  29156. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29157. * Returns the created WebGLBuffer.
  29158. */
  29159. VertexBuffer.prototype.create = function (data) {
  29160. return this._buffer.create(data);
  29161. };
  29162. /**
  29163. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29164. * This function will create a new buffer if the current one is not updatable
  29165. * Returns the updated WebGLBuffer.
  29166. */
  29167. VertexBuffer.prototype.update = function (data) {
  29168. return this._buffer.update(data);
  29169. };
  29170. /**
  29171. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29172. * Returns the directly updated WebGLBuffer.
  29173. * @param data the new data
  29174. * @param offset the new offset
  29175. * @param useBytes set to true if the offset is in bytes
  29176. */
  29177. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29178. if (useBytes === void 0) { useBytes = false; }
  29179. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29180. };
  29181. /**
  29182. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29183. */
  29184. VertexBuffer.prototype.dispose = function () {
  29185. if (this._ownsBuffer) {
  29186. this._buffer.dispose();
  29187. }
  29188. };
  29189. /**
  29190. * Enumerates each value of this vertex buffer as numbers.
  29191. * @param count the number of values to enumerate
  29192. * @param callback the callback function called for each value
  29193. */
  29194. VertexBuffer.prototype.forEach = function (count, callback) {
  29195. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29196. };
  29197. Object.defineProperty(VertexBuffer, "PositionKind", {
  29198. get: function () {
  29199. return VertexBuffer._PositionKind;
  29200. },
  29201. enumerable: true,
  29202. configurable: true
  29203. });
  29204. Object.defineProperty(VertexBuffer, "NormalKind", {
  29205. get: function () {
  29206. return VertexBuffer._NormalKind;
  29207. },
  29208. enumerable: true,
  29209. configurable: true
  29210. });
  29211. Object.defineProperty(VertexBuffer, "TangentKind", {
  29212. get: function () {
  29213. return VertexBuffer._TangentKind;
  29214. },
  29215. enumerable: true,
  29216. configurable: true
  29217. });
  29218. Object.defineProperty(VertexBuffer, "UVKind", {
  29219. get: function () {
  29220. return VertexBuffer._UVKind;
  29221. },
  29222. enumerable: true,
  29223. configurable: true
  29224. });
  29225. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29226. get: function () {
  29227. return VertexBuffer._UV2Kind;
  29228. },
  29229. enumerable: true,
  29230. configurable: true
  29231. });
  29232. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29233. get: function () {
  29234. return VertexBuffer._UV3Kind;
  29235. },
  29236. enumerable: true,
  29237. configurable: true
  29238. });
  29239. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29240. get: function () {
  29241. return VertexBuffer._UV4Kind;
  29242. },
  29243. enumerable: true,
  29244. configurable: true
  29245. });
  29246. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29247. get: function () {
  29248. return VertexBuffer._UV5Kind;
  29249. },
  29250. enumerable: true,
  29251. configurable: true
  29252. });
  29253. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29254. get: function () {
  29255. return VertexBuffer._UV6Kind;
  29256. },
  29257. enumerable: true,
  29258. configurable: true
  29259. });
  29260. Object.defineProperty(VertexBuffer, "ColorKind", {
  29261. get: function () {
  29262. return VertexBuffer._ColorKind;
  29263. },
  29264. enumerable: true,
  29265. configurable: true
  29266. });
  29267. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29268. get: function () {
  29269. return VertexBuffer._MatricesIndicesKind;
  29270. },
  29271. enumerable: true,
  29272. configurable: true
  29273. });
  29274. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29275. get: function () {
  29276. return VertexBuffer._MatricesWeightsKind;
  29277. },
  29278. enumerable: true,
  29279. configurable: true
  29280. });
  29281. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29282. get: function () {
  29283. return VertexBuffer._MatricesIndicesExtraKind;
  29284. },
  29285. enumerable: true,
  29286. configurable: true
  29287. });
  29288. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29289. get: function () {
  29290. return VertexBuffer._MatricesWeightsExtraKind;
  29291. },
  29292. enumerable: true,
  29293. configurable: true
  29294. });
  29295. /**
  29296. * Deduces the stride given a kind.
  29297. * @param kind The kind string to deduce
  29298. * @returns The deduced stride
  29299. */
  29300. VertexBuffer.DeduceStride = function (kind) {
  29301. switch (kind) {
  29302. case VertexBuffer.UVKind:
  29303. case VertexBuffer.UV2Kind:
  29304. case VertexBuffer.UV3Kind:
  29305. case VertexBuffer.UV4Kind:
  29306. case VertexBuffer.UV5Kind:
  29307. case VertexBuffer.UV6Kind:
  29308. return 2;
  29309. case VertexBuffer.NormalKind:
  29310. case VertexBuffer.PositionKind:
  29311. return 3;
  29312. case VertexBuffer.ColorKind:
  29313. case VertexBuffer.MatricesIndicesKind:
  29314. case VertexBuffer.MatricesIndicesExtraKind:
  29315. case VertexBuffer.MatricesWeightsKind:
  29316. case VertexBuffer.MatricesWeightsExtraKind:
  29317. case VertexBuffer.TangentKind:
  29318. return 4;
  29319. default:
  29320. throw new Error("Invalid kind '" + kind + "'");
  29321. }
  29322. };
  29323. /**
  29324. * Gets the byte length of the given type.
  29325. * @param type the type
  29326. * @returns the number of bytes
  29327. */
  29328. VertexBuffer.GetTypeByteLength = function (type) {
  29329. switch (type) {
  29330. case VertexBuffer.BYTE:
  29331. case VertexBuffer.UNSIGNED_BYTE:
  29332. return 1;
  29333. case VertexBuffer.SHORT:
  29334. case VertexBuffer.UNSIGNED_SHORT:
  29335. return 2;
  29336. case VertexBuffer.INT:
  29337. case VertexBuffer.FLOAT:
  29338. return 4;
  29339. default:
  29340. throw new Error("Invalid type '" + type + "'");
  29341. }
  29342. };
  29343. /**
  29344. * Enumerates each value of the given parameters as numbers.
  29345. * @param data the data to enumerate
  29346. * @param byteOffset the byte offset of the data
  29347. * @param byteStride the byte stride of the data
  29348. * @param componentCount the number of components per element
  29349. * @param componentType the type of the component
  29350. * @param count the total number of components
  29351. * @param normalized whether the data is normalized
  29352. * @param callback the callback function called for each value
  29353. */
  29354. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29355. if (data instanceof Array) {
  29356. var offset = byteOffset / 4;
  29357. var stride = byteStride / 4;
  29358. for (var index = 0; index < count; index += componentCount) {
  29359. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29360. callback(data[offset + componentIndex], index + componentIndex);
  29361. }
  29362. offset += stride;
  29363. }
  29364. }
  29365. else {
  29366. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29367. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29368. for (var index = 0; index < count; index += componentCount) {
  29369. var componentByteOffset = byteOffset;
  29370. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29371. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29372. callback(value, index + componentIndex);
  29373. componentByteOffset += componentByteLength;
  29374. }
  29375. byteOffset += byteStride;
  29376. }
  29377. }
  29378. };
  29379. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29380. switch (type) {
  29381. case VertexBuffer.BYTE: {
  29382. var value = dataView.getInt8(byteOffset);
  29383. if (normalized) {
  29384. value = (value + 0.5) / 127.5;
  29385. }
  29386. return value;
  29387. }
  29388. case VertexBuffer.UNSIGNED_BYTE: {
  29389. var value = dataView.getUint8(byteOffset);
  29390. if (normalized) {
  29391. value = value / 255;
  29392. }
  29393. return value;
  29394. }
  29395. case VertexBuffer.SHORT: {
  29396. var value = dataView.getInt16(byteOffset, true);
  29397. if (normalized) {
  29398. value = (value + 0.5) / 16383.5;
  29399. }
  29400. return value;
  29401. }
  29402. case VertexBuffer.UNSIGNED_SHORT: {
  29403. var value = dataView.getUint16(byteOffset, true);
  29404. if (normalized) {
  29405. value = value / 65535;
  29406. }
  29407. return value;
  29408. }
  29409. case VertexBuffer.FLOAT: {
  29410. return dataView.getFloat32(byteOffset, true);
  29411. }
  29412. default: {
  29413. throw new Error("Invalid component type " + type);
  29414. }
  29415. }
  29416. };
  29417. /**
  29418. * The byte type.
  29419. */
  29420. VertexBuffer.BYTE = 5120;
  29421. /**
  29422. * The unsigned byte type.
  29423. */
  29424. VertexBuffer.UNSIGNED_BYTE = 5121;
  29425. /**
  29426. * The short type.
  29427. */
  29428. VertexBuffer.SHORT = 5122;
  29429. /**
  29430. * The unsigned short type.
  29431. */
  29432. VertexBuffer.UNSIGNED_SHORT = 5123;
  29433. /**
  29434. * The integer type.
  29435. */
  29436. VertexBuffer.INT = 5124;
  29437. /**
  29438. * The unsigned integer type.
  29439. */
  29440. VertexBuffer.UNSIGNED_INT = 5125;
  29441. /**
  29442. * The float type.
  29443. */
  29444. VertexBuffer.FLOAT = 5126;
  29445. // Enums
  29446. VertexBuffer._PositionKind = "position";
  29447. VertexBuffer._NormalKind = "normal";
  29448. VertexBuffer._TangentKind = "tangent";
  29449. VertexBuffer._UVKind = "uv";
  29450. VertexBuffer._UV2Kind = "uv2";
  29451. VertexBuffer._UV3Kind = "uv3";
  29452. VertexBuffer._UV4Kind = "uv4";
  29453. VertexBuffer._UV5Kind = "uv5";
  29454. VertexBuffer._UV6Kind = "uv6";
  29455. VertexBuffer._ColorKind = "color";
  29456. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29457. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29458. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29459. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29460. return VertexBuffer;
  29461. }());
  29462. BABYLON.VertexBuffer = VertexBuffer;
  29463. })(BABYLON || (BABYLON = {}));
  29464. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29465. var BABYLON;
  29466. (function (BABYLON) {
  29467. /**
  29468. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29469. */
  29470. var DummyInternalTextureTracker = /** @class */ (function () {
  29471. function DummyInternalTextureTracker() {
  29472. /**
  29473. * Gets or set the previous tracker in the list
  29474. */
  29475. this.previous = null;
  29476. /**
  29477. * Gets or set the next tracker in the list
  29478. */
  29479. this.next = null;
  29480. }
  29481. return DummyInternalTextureTracker;
  29482. }());
  29483. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29484. })(BABYLON || (BABYLON = {}));
  29485. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29486. var BABYLON;
  29487. (function (BABYLON) {
  29488. /**
  29489. * Class used to store data associated with WebGL texture data for the engine
  29490. * This class should not be used directly
  29491. */
  29492. var InternalTexture = /** @class */ (function () {
  29493. /**
  29494. * Creates a new InternalTexture
  29495. * @param engine defines the engine to use
  29496. * @param dataSource defines the type of data that will be used
  29497. */
  29498. function InternalTexture(engine, dataSource) {
  29499. /**
  29500. * Observable called when the texture is loaded
  29501. */
  29502. this.onLoadedObservable = new BABYLON.Observable();
  29503. /**
  29504. * Gets or set the previous tracker in the list
  29505. */
  29506. this.previous = null;
  29507. /**
  29508. * Gets or set the next tracker in the list
  29509. */
  29510. this.next = null;
  29511. // Private
  29512. /** @ignore */
  29513. this._initialSlot = -1;
  29514. /** @ignore */
  29515. this._designatedSlot = -1;
  29516. /** @ignore */
  29517. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29518. /** @ignore */
  29519. this._comparisonFunction = 0;
  29520. /** @ignore */
  29521. this._references = 1;
  29522. this._engine = engine;
  29523. this._dataSource = dataSource;
  29524. this._webGLTexture = engine._createTexture();
  29525. }
  29526. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29527. /**
  29528. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29529. */
  29530. get: function () {
  29531. return this._dataSource;
  29532. },
  29533. enumerable: true,
  29534. configurable: true
  29535. });
  29536. /**
  29537. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29538. */
  29539. InternalTexture.prototype.incrementReferences = function () {
  29540. this._references++;
  29541. };
  29542. /**
  29543. * Change the size of the texture (not the size of the content)
  29544. * @param width defines the new width
  29545. * @param height defines the new height
  29546. * @param depth defines the new depth (1 by default)
  29547. */
  29548. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29549. if (depth === void 0) { depth = 1; }
  29550. this.width = width;
  29551. this.height = height;
  29552. this.depth = depth;
  29553. this.baseWidth = width;
  29554. this.baseHeight = height;
  29555. this.baseDepth = depth;
  29556. this._size = width * height * depth;
  29557. };
  29558. /** @ignore */
  29559. InternalTexture.prototype._rebuild = function () {
  29560. var _this = this;
  29561. var proxy;
  29562. this.isReady = false;
  29563. this._cachedCoordinatesMode = null;
  29564. this._cachedWrapU = null;
  29565. this._cachedWrapV = null;
  29566. this._cachedAnisotropicFilteringLevel = null;
  29567. switch (this._dataSource) {
  29568. case InternalTexture.DATASOURCE_TEMP:
  29569. return;
  29570. case InternalTexture.DATASOURCE_URL:
  29571. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29572. _this.isReady = true;
  29573. }, null, this._buffer, undefined, this.format);
  29574. proxy._swapAndDie(this);
  29575. return;
  29576. case InternalTexture.DATASOURCE_RAW:
  29577. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29578. proxy._swapAndDie(this);
  29579. this.isReady = true;
  29580. return;
  29581. case InternalTexture.DATASOURCE_RAW3D:
  29582. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29583. proxy._swapAndDie(this);
  29584. this.isReady = true;
  29585. return;
  29586. case InternalTexture.DATASOURCE_DYNAMIC:
  29587. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29588. proxy._swapAndDie(this);
  29589. // The engine will make sure to update content so no need to flag it as isReady = true
  29590. return;
  29591. case InternalTexture.DATASOURCE_RENDERTARGET:
  29592. var options = new BABYLON.RenderTargetCreationOptions();
  29593. options.generateDepthBuffer = this._generateDepthBuffer;
  29594. options.generateMipMaps = this.generateMipMaps;
  29595. options.generateStencilBuffer = this._generateStencilBuffer;
  29596. options.samplingMode = this.samplingMode;
  29597. options.type = this.type;
  29598. if (this.isCube) {
  29599. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29600. }
  29601. else {
  29602. var size = {
  29603. width: this.width,
  29604. height: this.height
  29605. };
  29606. proxy = this._engine.createRenderTargetTexture(size, options);
  29607. }
  29608. proxy._swapAndDie(this);
  29609. this.isReady = true;
  29610. return;
  29611. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29612. var depthTextureOptions = {
  29613. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29614. comparisonFunction: this._comparisonFunction,
  29615. generateStencil: this._generateStencilBuffer,
  29616. isCube: this.isCube
  29617. };
  29618. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29619. proxy._swapAndDie(this);
  29620. this.isReady = true;
  29621. return;
  29622. case InternalTexture.DATASOURCE_CUBE:
  29623. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29624. _this.isReady = true;
  29625. }, null, this.format, this._extension);
  29626. proxy._swapAndDie(this);
  29627. return;
  29628. case InternalTexture.DATASOURCE_CUBERAW:
  29629. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29630. proxy._swapAndDie(this);
  29631. this.isReady = true;
  29632. return;
  29633. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29634. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29635. if (proxy) {
  29636. proxy._swapAndDie(_this);
  29637. }
  29638. _this.isReady = true;
  29639. }, null, this.format, this._extension);
  29640. return;
  29641. }
  29642. };
  29643. InternalTexture.prototype._swapAndDie = function (target) {
  29644. target._webGLTexture = this._webGLTexture;
  29645. if (this._framebuffer) {
  29646. target._framebuffer = this._framebuffer;
  29647. }
  29648. if (this._depthStencilBuffer) {
  29649. target._depthStencilBuffer = this._depthStencilBuffer;
  29650. }
  29651. if (this._lodTextureHigh) {
  29652. if (target._lodTextureHigh) {
  29653. target._lodTextureHigh.dispose();
  29654. }
  29655. target._lodTextureHigh = this._lodTextureHigh;
  29656. }
  29657. if (this._lodTextureMid) {
  29658. if (target._lodTextureMid) {
  29659. target._lodTextureMid.dispose();
  29660. }
  29661. target._lodTextureMid = this._lodTextureMid;
  29662. }
  29663. if (this._lodTextureLow) {
  29664. if (target._lodTextureLow) {
  29665. target._lodTextureLow.dispose();
  29666. }
  29667. target._lodTextureLow = this._lodTextureLow;
  29668. }
  29669. var cache = this._engine.getLoadedTexturesCache();
  29670. var index = cache.indexOf(this);
  29671. if (index !== -1) {
  29672. cache.splice(index, 1);
  29673. }
  29674. };
  29675. /**
  29676. * Dispose the current allocated resources
  29677. */
  29678. InternalTexture.prototype.dispose = function () {
  29679. if (!this._webGLTexture) {
  29680. return;
  29681. }
  29682. this._references--;
  29683. if (this._references === 0) {
  29684. this._engine._releaseTexture(this);
  29685. this._webGLTexture = null;
  29686. this.previous = null;
  29687. this.next = null;
  29688. }
  29689. };
  29690. /**
  29691. * The source of the texture data is unknown
  29692. */
  29693. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29694. /**
  29695. * Texture data comes from an URL
  29696. */
  29697. InternalTexture.DATASOURCE_URL = 1;
  29698. /**
  29699. * Texture data is only used for temporary storage
  29700. */
  29701. InternalTexture.DATASOURCE_TEMP = 2;
  29702. /**
  29703. * Texture data comes from raw data (ArrayBuffer)
  29704. */
  29705. InternalTexture.DATASOURCE_RAW = 3;
  29706. /**
  29707. * Texture content is dynamic (video or dynamic texture)
  29708. */
  29709. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29710. /**
  29711. * Texture content is generated by rendering to it
  29712. */
  29713. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29714. /**
  29715. * Texture content is part of a multi render target process
  29716. */
  29717. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29718. /**
  29719. * Texture data comes from a cube data file
  29720. */
  29721. InternalTexture.DATASOURCE_CUBE = 7;
  29722. /**
  29723. * Texture data comes from a raw cube data
  29724. */
  29725. InternalTexture.DATASOURCE_CUBERAW = 8;
  29726. /**
  29727. * Texture data come from a prefiltered cube data file
  29728. */
  29729. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29730. /**
  29731. * Texture content is raw 3D data
  29732. */
  29733. InternalTexture.DATASOURCE_RAW3D = 10;
  29734. /**
  29735. * Texture content is a depth texture
  29736. */
  29737. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29738. return InternalTexture;
  29739. }());
  29740. BABYLON.InternalTexture = InternalTexture;
  29741. })(BABYLON || (BABYLON = {}));
  29742. //# sourceMappingURL=babylon.internalTexture.js.map
  29743. var BABYLON;
  29744. (function (BABYLON) {
  29745. var BaseTexture = /** @class */ (function () {
  29746. function BaseTexture(scene) {
  29747. this._hasAlpha = false;
  29748. this.getAlphaFromRGB = false;
  29749. this.level = 1;
  29750. this.coordinatesIndex = 0;
  29751. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29752. /**
  29753. * | Value | Type | Description |
  29754. * | ----- | ------------------ | ----------- |
  29755. * | 0 | CLAMP_ADDRESSMODE | |
  29756. * | 1 | WRAP_ADDRESSMODE | |
  29757. * | 2 | MIRROR_ADDRESSMODE | |
  29758. */
  29759. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29760. /**
  29761. * | Value | Type | Description |
  29762. * | ----- | ------------------ | ----------- |
  29763. * | 0 | CLAMP_ADDRESSMODE | |
  29764. * | 1 | WRAP_ADDRESSMODE | |
  29765. * | 2 | MIRROR_ADDRESSMODE | |
  29766. */
  29767. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29768. /**
  29769. * | Value | Type | Description |
  29770. * | ----- | ------------------ | ----------- |
  29771. * | 0 | CLAMP_ADDRESSMODE | |
  29772. * | 1 | WRAP_ADDRESSMODE | |
  29773. * | 2 | MIRROR_ADDRESSMODE | |
  29774. */
  29775. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29776. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29777. this.isCube = false;
  29778. this.is3D = false;
  29779. this.gammaSpace = true;
  29780. this.invertZ = false;
  29781. this.lodLevelInAlpha = false;
  29782. this.lodGenerationOffset = 0.0;
  29783. this.lodGenerationScale = 0.8;
  29784. this.isRenderTarget = false;
  29785. this.animations = new Array();
  29786. /**
  29787. * An event triggered when the texture is disposed.
  29788. */
  29789. this.onDisposeObservable = new BABYLON.Observable();
  29790. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29791. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29792. if (this._scene) {
  29793. this._scene.textures.push(this);
  29794. }
  29795. this._uid = null;
  29796. }
  29797. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29798. get: function () {
  29799. return this._hasAlpha;
  29800. },
  29801. set: function (value) {
  29802. if (this._hasAlpha === value) {
  29803. return;
  29804. }
  29805. this._hasAlpha = value;
  29806. if (this._scene) {
  29807. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29808. }
  29809. },
  29810. enumerable: true,
  29811. configurable: true
  29812. });
  29813. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29814. get: function () {
  29815. return this._coordinatesMode;
  29816. },
  29817. /**
  29818. * How a texture is mapped.
  29819. *
  29820. * | Value | Type | Description |
  29821. * | ----- | ----------------------------------- | ----------- |
  29822. * | 0 | EXPLICIT_MODE | |
  29823. * | 1 | SPHERICAL_MODE | |
  29824. * | 2 | PLANAR_MODE | |
  29825. * | 3 | CUBIC_MODE | |
  29826. * | 4 | PROJECTION_MODE | |
  29827. * | 5 | SKYBOX_MODE | |
  29828. * | 6 | INVCUBIC_MODE | |
  29829. * | 7 | EQUIRECTANGULAR_MODE | |
  29830. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29831. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29832. */
  29833. set: function (value) {
  29834. if (this._coordinatesMode === value) {
  29835. return;
  29836. }
  29837. this._coordinatesMode = value;
  29838. if (this._scene) {
  29839. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29840. }
  29841. },
  29842. enumerable: true,
  29843. configurable: true
  29844. });
  29845. Object.defineProperty(BaseTexture.prototype, "uid", {
  29846. get: function () {
  29847. if (!this._uid) {
  29848. this._uid = BABYLON.Tools.RandomId();
  29849. }
  29850. return this._uid;
  29851. },
  29852. enumerable: true,
  29853. configurable: true
  29854. });
  29855. BaseTexture.prototype.toString = function () {
  29856. return this.name;
  29857. };
  29858. BaseTexture.prototype.getClassName = function () {
  29859. return "BaseTexture";
  29860. };
  29861. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29862. set: function (callback) {
  29863. if (this._onDisposeObserver) {
  29864. this.onDisposeObservable.remove(this._onDisposeObserver);
  29865. }
  29866. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29867. },
  29868. enumerable: true,
  29869. configurable: true
  29870. });
  29871. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29872. get: function () {
  29873. return true;
  29874. },
  29875. enumerable: true,
  29876. configurable: true
  29877. });
  29878. BaseTexture.prototype.getScene = function () {
  29879. return this._scene;
  29880. };
  29881. BaseTexture.prototype.getTextureMatrix = function () {
  29882. return BABYLON.Matrix.IdentityReadOnly;
  29883. };
  29884. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29885. return BABYLON.Matrix.IdentityReadOnly;
  29886. };
  29887. BaseTexture.prototype.getInternalTexture = function () {
  29888. return this._texture;
  29889. };
  29890. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29891. return !this.isBlocking || this.isReady();
  29892. };
  29893. BaseTexture.prototype.isReady = function () {
  29894. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29895. this.delayLoad();
  29896. return false;
  29897. }
  29898. if (this._texture) {
  29899. return this._texture.isReady;
  29900. }
  29901. return false;
  29902. };
  29903. BaseTexture.prototype.getSize = function () {
  29904. if (this._texture && this._texture.width) {
  29905. return new BABYLON.Size(this._texture.width, this._texture.height);
  29906. }
  29907. if (this._texture && this._texture._size) {
  29908. return new BABYLON.Size(this._texture._size, this._texture._size);
  29909. }
  29910. return BABYLON.Size.Zero();
  29911. };
  29912. BaseTexture.prototype.getBaseSize = function () {
  29913. if (!this.isReady() || !this._texture)
  29914. return BABYLON.Size.Zero();
  29915. if (this._texture._size) {
  29916. return new BABYLON.Size(this._texture._size, this._texture._size);
  29917. }
  29918. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29919. };
  29920. BaseTexture.prototype.scale = function (ratio) {
  29921. };
  29922. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29923. get: function () {
  29924. return false;
  29925. },
  29926. enumerable: true,
  29927. configurable: true
  29928. });
  29929. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29930. if (!this._scene) {
  29931. return null;
  29932. }
  29933. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29934. for (var index = 0; index < texturesCache.length; index++) {
  29935. var texturesCacheEntry = texturesCache[index];
  29936. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29937. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29938. texturesCacheEntry.incrementReferences();
  29939. return texturesCacheEntry;
  29940. }
  29941. }
  29942. }
  29943. return null;
  29944. };
  29945. BaseTexture.prototype._rebuild = function () {
  29946. };
  29947. BaseTexture.prototype.delayLoad = function () {
  29948. };
  29949. BaseTexture.prototype.clone = function () {
  29950. return null;
  29951. };
  29952. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29953. get: function () {
  29954. if (!this._texture) {
  29955. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29956. }
  29957. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29958. },
  29959. enumerable: true,
  29960. configurable: true
  29961. });
  29962. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29963. get: function () {
  29964. if (!this._texture) {
  29965. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29966. }
  29967. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29968. },
  29969. enumerable: true,
  29970. configurable: true
  29971. });
  29972. BaseTexture.prototype.readPixels = function (faceIndex) {
  29973. if (faceIndex === void 0) { faceIndex = 0; }
  29974. if (!this._texture) {
  29975. return null;
  29976. }
  29977. var size = this.getSize();
  29978. var scene = this.getScene();
  29979. if (!scene) {
  29980. return null;
  29981. }
  29982. var engine = scene.getEngine();
  29983. if (this._texture.isCube) {
  29984. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29985. }
  29986. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29987. };
  29988. BaseTexture.prototype.releaseInternalTexture = function () {
  29989. if (this._texture) {
  29990. this._texture.dispose();
  29991. this._texture = null;
  29992. }
  29993. };
  29994. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29995. get: function () {
  29996. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29997. return null;
  29998. }
  29999. if (!this._texture._sphericalPolynomial) {
  30000. this._texture._sphericalPolynomial =
  30001. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30002. }
  30003. return this._texture._sphericalPolynomial;
  30004. },
  30005. set: function (value) {
  30006. if (this._texture) {
  30007. this._texture._sphericalPolynomial = value;
  30008. }
  30009. },
  30010. enumerable: true,
  30011. configurable: true
  30012. });
  30013. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30014. get: function () {
  30015. if (this._texture) {
  30016. return this._texture._lodTextureHigh;
  30017. }
  30018. return null;
  30019. },
  30020. enumerable: true,
  30021. configurable: true
  30022. });
  30023. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30024. get: function () {
  30025. if (this._texture) {
  30026. return this._texture._lodTextureMid;
  30027. }
  30028. return null;
  30029. },
  30030. enumerable: true,
  30031. configurable: true
  30032. });
  30033. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30034. get: function () {
  30035. if (this._texture) {
  30036. return this._texture._lodTextureLow;
  30037. }
  30038. return null;
  30039. },
  30040. enumerable: true,
  30041. configurable: true
  30042. });
  30043. BaseTexture.prototype.dispose = function () {
  30044. if (!this._scene) {
  30045. return;
  30046. }
  30047. // Animations
  30048. this._scene.stopAnimation(this);
  30049. // Remove from scene
  30050. this._scene._removePendingData(this);
  30051. var index = this._scene.textures.indexOf(this);
  30052. if (index >= 0) {
  30053. this._scene.textures.splice(index, 1);
  30054. }
  30055. if (this._texture === undefined) {
  30056. return;
  30057. }
  30058. // Release
  30059. this.releaseInternalTexture();
  30060. // Callback
  30061. this.onDisposeObservable.notifyObservers(this);
  30062. this.onDisposeObservable.clear();
  30063. };
  30064. BaseTexture.prototype.serialize = function () {
  30065. if (!this.name) {
  30066. return null;
  30067. }
  30068. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30069. // Animations
  30070. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30071. return serializationObject;
  30072. };
  30073. BaseTexture.WhenAllReady = function (textures, callback) {
  30074. var numRemaining = textures.length;
  30075. if (numRemaining === 0) {
  30076. callback();
  30077. return;
  30078. }
  30079. var _loop_1 = function () {
  30080. texture = textures[i];
  30081. if (texture.isReady()) {
  30082. if (--numRemaining === 0) {
  30083. callback();
  30084. }
  30085. }
  30086. else {
  30087. onLoadObservable = texture.onLoadObservable;
  30088. var onLoadCallback_1 = function () {
  30089. onLoadObservable.removeCallback(onLoadCallback_1);
  30090. if (--numRemaining === 0) {
  30091. callback();
  30092. }
  30093. };
  30094. onLoadObservable.add(onLoadCallback_1);
  30095. }
  30096. };
  30097. var texture, onLoadObservable;
  30098. for (var i = 0; i < textures.length; i++) {
  30099. _loop_1();
  30100. }
  30101. };
  30102. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30103. __decorate([
  30104. BABYLON.serialize()
  30105. ], BaseTexture.prototype, "name", void 0);
  30106. __decorate([
  30107. BABYLON.serialize("hasAlpha")
  30108. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30109. __decorate([
  30110. BABYLON.serialize()
  30111. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30112. __decorate([
  30113. BABYLON.serialize()
  30114. ], BaseTexture.prototype, "level", void 0);
  30115. __decorate([
  30116. BABYLON.serialize()
  30117. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30118. __decorate([
  30119. BABYLON.serialize("coordinatesMode")
  30120. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30121. __decorate([
  30122. BABYLON.serialize()
  30123. ], BaseTexture.prototype, "wrapU", void 0);
  30124. __decorate([
  30125. BABYLON.serialize()
  30126. ], BaseTexture.prototype, "wrapV", void 0);
  30127. __decorate([
  30128. BABYLON.serialize()
  30129. ], BaseTexture.prototype, "wrapR", void 0);
  30130. __decorate([
  30131. BABYLON.serialize()
  30132. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30133. __decorate([
  30134. BABYLON.serialize()
  30135. ], BaseTexture.prototype, "isCube", void 0);
  30136. __decorate([
  30137. BABYLON.serialize()
  30138. ], BaseTexture.prototype, "is3D", void 0);
  30139. __decorate([
  30140. BABYLON.serialize()
  30141. ], BaseTexture.prototype, "gammaSpace", void 0);
  30142. __decorate([
  30143. BABYLON.serialize()
  30144. ], BaseTexture.prototype, "invertZ", void 0);
  30145. __decorate([
  30146. BABYLON.serialize()
  30147. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30148. __decorate([
  30149. BABYLON.serialize()
  30150. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30151. __decorate([
  30152. BABYLON.serialize()
  30153. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30154. __decorate([
  30155. BABYLON.serialize()
  30156. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30157. return BaseTexture;
  30158. }());
  30159. BABYLON.BaseTexture = BaseTexture;
  30160. })(BABYLON || (BABYLON = {}));
  30161. //# sourceMappingURL=babylon.baseTexture.js.map
  30162. var BABYLON;
  30163. (function (BABYLON) {
  30164. var Texture = /** @class */ (function (_super) {
  30165. __extends(Texture, _super);
  30166. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30167. if (noMipmap === void 0) { noMipmap = false; }
  30168. if (invertY === void 0) { invertY = true; }
  30169. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30170. if (onLoad === void 0) { onLoad = null; }
  30171. if (onError === void 0) { onError = null; }
  30172. if (buffer === void 0) { buffer = null; }
  30173. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30174. var _this = _super.call(this, scene) || this;
  30175. _this.uOffset = 0;
  30176. _this.vOffset = 0;
  30177. _this.uScale = 1.0;
  30178. _this.vScale = 1.0;
  30179. _this.uAng = 0;
  30180. _this.vAng = 0;
  30181. _this.wAng = 0;
  30182. _this._isBlocking = true;
  30183. _this.name = url || "";
  30184. _this.url = url;
  30185. _this._noMipmap = noMipmap;
  30186. _this._invertY = invertY;
  30187. _this._samplingMode = samplingMode;
  30188. _this._buffer = buffer;
  30189. _this._deleteBuffer = deleteBuffer;
  30190. if (format) {
  30191. _this._format = format;
  30192. }
  30193. scene = _this.getScene();
  30194. if (!scene) {
  30195. return _this;
  30196. }
  30197. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30198. var load = function () {
  30199. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30200. _this.onLoadObservable.notifyObservers(_this);
  30201. }
  30202. if (onLoad) {
  30203. onLoad();
  30204. }
  30205. if (!_this.isBlocking && scene) {
  30206. scene.resetCachedMaterial();
  30207. }
  30208. };
  30209. if (!_this.url) {
  30210. _this._delayedOnLoad = load;
  30211. _this._delayedOnError = onError;
  30212. return _this;
  30213. }
  30214. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30215. if (!_this._texture) {
  30216. if (!scene.useDelayedTextureLoading) {
  30217. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30218. if (deleteBuffer) {
  30219. delete _this._buffer;
  30220. }
  30221. }
  30222. else {
  30223. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30224. _this._delayedOnLoad = load;
  30225. _this._delayedOnError = onError;
  30226. }
  30227. }
  30228. else {
  30229. if (_this._texture.isReady) {
  30230. BABYLON.Tools.SetImmediate(function () { return load(); });
  30231. }
  30232. else {
  30233. _this._texture.onLoadedObservable.add(load);
  30234. }
  30235. }
  30236. return _this;
  30237. }
  30238. Object.defineProperty(Texture.prototype, "noMipmap", {
  30239. get: function () {
  30240. return this._noMipmap;
  30241. },
  30242. enumerable: true,
  30243. configurable: true
  30244. });
  30245. Object.defineProperty(Texture.prototype, "isBlocking", {
  30246. get: function () {
  30247. return this._isBlocking;
  30248. },
  30249. set: function (value) {
  30250. this._isBlocking = value;
  30251. },
  30252. enumerable: true,
  30253. configurable: true
  30254. });
  30255. Object.defineProperty(Texture.prototype, "samplingMode", {
  30256. get: function () {
  30257. return this._samplingMode;
  30258. },
  30259. enumerable: true,
  30260. configurable: true
  30261. });
  30262. Texture.prototype.updateURL = function (url) {
  30263. this.url = url;
  30264. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30265. this.delayLoad();
  30266. };
  30267. Texture.prototype.delayLoad = function () {
  30268. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30269. return;
  30270. }
  30271. var scene = this.getScene();
  30272. if (!scene) {
  30273. return;
  30274. }
  30275. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30276. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30277. if (!this._texture) {
  30278. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30279. if (this._deleteBuffer) {
  30280. delete this._buffer;
  30281. }
  30282. }
  30283. else {
  30284. if (this._delayedOnLoad) {
  30285. if (this._texture.isReady) {
  30286. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30287. }
  30288. else {
  30289. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30290. }
  30291. }
  30292. }
  30293. this._delayedOnLoad = null;
  30294. this._delayedOnError = null;
  30295. };
  30296. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30297. if (!this._texture) {
  30298. return;
  30299. }
  30300. var scene = this.getScene();
  30301. if (!scene) {
  30302. return;
  30303. }
  30304. this._samplingMode = samplingMode;
  30305. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30306. };
  30307. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30308. x *= this.uScale;
  30309. y *= this.vScale;
  30310. x -= 0.5 * this.uScale;
  30311. y -= 0.5 * this.vScale;
  30312. z -= 0.5;
  30313. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30314. t.x += 0.5 * this.uScale + this.uOffset;
  30315. t.y += 0.5 * this.vScale + this.vOffset;
  30316. t.z += 0.5;
  30317. };
  30318. Texture.prototype.getTextureMatrix = function () {
  30319. var _this = this;
  30320. if (this.uOffset === this._cachedUOffset &&
  30321. this.vOffset === this._cachedVOffset &&
  30322. this.uScale === this._cachedUScale &&
  30323. this.vScale === this._cachedVScale &&
  30324. this.uAng === this._cachedUAng &&
  30325. this.vAng === this._cachedVAng &&
  30326. this.wAng === this._cachedWAng) {
  30327. return this._cachedTextureMatrix;
  30328. }
  30329. this._cachedUOffset = this.uOffset;
  30330. this._cachedVOffset = this.vOffset;
  30331. this._cachedUScale = this.uScale;
  30332. this._cachedVScale = this.vScale;
  30333. this._cachedUAng = this.uAng;
  30334. this._cachedVAng = this.vAng;
  30335. this._cachedWAng = this.wAng;
  30336. if (!this._cachedTextureMatrix) {
  30337. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30338. this._rowGenerationMatrix = new BABYLON.Matrix();
  30339. this._t0 = BABYLON.Vector3.Zero();
  30340. this._t1 = BABYLON.Vector3.Zero();
  30341. this._t2 = BABYLON.Vector3.Zero();
  30342. }
  30343. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30344. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30345. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30346. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30347. this._t1.subtractInPlace(this._t0);
  30348. this._t2.subtractInPlace(this._t0);
  30349. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30350. this._cachedTextureMatrix.m[0] = this._t1.x;
  30351. this._cachedTextureMatrix.m[1] = this._t1.y;
  30352. this._cachedTextureMatrix.m[2] = this._t1.z;
  30353. this._cachedTextureMatrix.m[4] = this._t2.x;
  30354. this._cachedTextureMatrix.m[5] = this._t2.y;
  30355. this._cachedTextureMatrix.m[6] = this._t2.z;
  30356. this._cachedTextureMatrix.m[8] = this._t0.x;
  30357. this._cachedTextureMatrix.m[9] = this._t0.y;
  30358. this._cachedTextureMatrix.m[10] = this._t0.z;
  30359. var scene = this.getScene();
  30360. if (!scene) {
  30361. return this._cachedTextureMatrix;
  30362. }
  30363. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30364. return mat.hasTexture(_this);
  30365. });
  30366. return this._cachedTextureMatrix;
  30367. };
  30368. Texture.prototype.getReflectionTextureMatrix = function () {
  30369. var _this = this;
  30370. var scene = this.getScene();
  30371. if (!scene) {
  30372. return this._cachedTextureMatrix;
  30373. }
  30374. if (this.uOffset === this._cachedUOffset &&
  30375. this.vOffset === this._cachedVOffset &&
  30376. this.uScale === this._cachedUScale &&
  30377. this.vScale === this._cachedVScale &&
  30378. this.coordinatesMode === this._cachedCoordinatesMode) {
  30379. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30380. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30381. return this._cachedTextureMatrix;
  30382. }
  30383. }
  30384. else {
  30385. return this._cachedTextureMatrix;
  30386. }
  30387. }
  30388. if (!this._cachedTextureMatrix) {
  30389. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30390. }
  30391. if (!this._projectionModeMatrix) {
  30392. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30393. }
  30394. this._cachedUOffset = this.uOffset;
  30395. this._cachedVOffset = this.vOffset;
  30396. this._cachedUScale = this.uScale;
  30397. this._cachedVScale = this.vScale;
  30398. this._cachedCoordinatesMode = this.coordinatesMode;
  30399. switch (this.coordinatesMode) {
  30400. case Texture.PLANAR_MODE:
  30401. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30402. this._cachedTextureMatrix[0] = this.uScale;
  30403. this._cachedTextureMatrix[5] = this.vScale;
  30404. this._cachedTextureMatrix[12] = this.uOffset;
  30405. this._cachedTextureMatrix[13] = this.vOffset;
  30406. break;
  30407. case Texture.PROJECTION_MODE:
  30408. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30409. this._projectionModeMatrix.m[0] = 0.5;
  30410. this._projectionModeMatrix.m[5] = -0.5;
  30411. this._projectionModeMatrix.m[10] = 0.0;
  30412. this._projectionModeMatrix.m[12] = 0.5;
  30413. this._projectionModeMatrix.m[13] = 0.5;
  30414. this._projectionModeMatrix.m[14] = 1.0;
  30415. this._projectionModeMatrix.m[15] = 1.0;
  30416. var projectionMatrix = scene.getProjectionMatrix();
  30417. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30418. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30419. break;
  30420. default:
  30421. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30422. break;
  30423. }
  30424. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30425. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30426. });
  30427. return this._cachedTextureMatrix;
  30428. };
  30429. Texture.prototype.clone = function () {
  30430. var _this = this;
  30431. return BABYLON.SerializationHelper.Clone(function () {
  30432. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30433. }, this);
  30434. };
  30435. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30436. get: function () {
  30437. if (!this._onLoadObservable) {
  30438. this._onLoadObservable = new BABYLON.Observable();
  30439. }
  30440. return this._onLoadObservable;
  30441. },
  30442. enumerable: true,
  30443. configurable: true
  30444. });
  30445. Texture.prototype.serialize = function () {
  30446. var serializationObject = _super.prototype.serialize.call(this);
  30447. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30448. serializationObject.base64String = this._buffer;
  30449. serializationObject.name = serializationObject.name.replace("data:", "");
  30450. }
  30451. serializationObject.invertY = this._invertY;
  30452. serializationObject.samplingMode = this.samplingMode;
  30453. return serializationObject;
  30454. };
  30455. Texture.prototype.getClassName = function () {
  30456. return "Texture";
  30457. };
  30458. Texture.prototype.dispose = function () {
  30459. _super.prototype.dispose.call(this);
  30460. if (this.onLoadObservable) {
  30461. this.onLoadObservable.clear();
  30462. this._onLoadObservable = null;
  30463. }
  30464. this._delayedOnLoad = null;
  30465. this._delayedOnError = null;
  30466. };
  30467. // Statics
  30468. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30469. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30470. if (onLoad === void 0) { onLoad = null; }
  30471. if (onError === void 0) { onError = null; }
  30472. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30473. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30474. };
  30475. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30476. if (parsedTexture.customType) {
  30477. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30478. // Update Sampling Mode
  30479. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30480. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30481. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30482. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30483. }
  30484. }
  30485. return parsedCustomTexture;
  30486. }
  30487. if (parsedTexture.isCube) {
  30488. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30489. }
  30490. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30491. return null;
  30492. }
  30493. var texture = BABYLON.SerializationHelper.Parse(function () {
  30494. var generateMipMaps = true;
  30495. if (parsedTexture.noMipmap) {
  30496. generateMipMaps = false;
  30497. }
  30498. if (parsedTexture.mirrorPlane) {
  30499. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30500. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30501. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30502. return mirrorTexture;
  30503. }
  30504. else if (parsedTexture.isRenderTarget) {
  30505. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30506. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30507. return renderTargetTexture;
  30508. }
  30509. else {
  30510. var texture;
  30511. if (parsedTexture.base64String) {
  30512. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30513. }
  30514. else {
  30515. var url = rootUrl + parsedTexture.name;
  30516. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30517. url = parsedTexture.url;
  30518. }
  30519. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30520. }
  30521. return texture;
  30522. }
  30523. }, parsedTexture, scene);
  30524. // Update Sampling Mode
  30525. if (parsedTexture.samplingMode) {
  30526. var sampling = parsedTexture.samplingMode;
  30527. if (texture._samplingMode !== sampling) {
  30528. texture.updateSamplingMode(sampling);
  30529. }
  30530. }
  30531. // Animations
  30532. if (parsedTexture.animations) {
  30533. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30534. var parsedAnimation = parsedTexture.animations[animationIndex];
  30535. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30536. }
  30537. }
  30538. return texture;
  30539. };
  30540. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30541. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30542. if (noMipmap === void 0) { noMipmap = false; }
  30543. if (invertY === void 0) { invertY = true; }
  30544. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30545. if (onLoad === void 0) { onLoad = null; }
  30546. if (onError === void 0) { onError = null; }
  30547. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30548. if (name.substr(0, 5) !== "data:") {
  30549. name = "data:" + name;
  30550. }
  30551. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30552. };
  30553. // Constants
  30554. Texture.NEAREST_SAMPLINGMODE = 1;
  30555. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30556. Texture.BILINEAR_SAMPLINGMODE = 2;
  30557. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30558. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30559. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30560. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30561. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30562. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30563. Texture.NEAREST_LINEAR = 7;
  30564. Texture.NEAREST_NEAREST = 8;
  30565. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30566. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30567. Texture.LINEAR_LINEAR = 11;
  30568. Texture.LINEAR_NEAREST = 12;
  30569. Texture.EXPLICIT_MODE = 0;
  30570. Texture.SPHERICAL_MODE = 1;
  30571. Texture.PLANAR_MODE = 2;
  30572. Texture.CUBIC_MODE = 3;
  30573. Texture.PROJECTION_MODE = 4;
  30574. Texture.SKYBOX_MODE = 5;
  30575. Texture.INVCUBIC_MODE = 6;
  30576. Texture.EQUIRECTANGULAR_MODE = 7;
  30577. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30578. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30579. Texture.CLAMP_ADDRESSMODE = 0;
  30580. Texture.WRAP_ADDRESSMODE = 1;
  30581. Texture.MIRROR_ADDRESSMODE = 2;
  30582. /**
  30583. * 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
  30584. */
  30585. Texture.UseSerializedUrlIfAny = false;
  30586. __decorate([
  30587. BABYLON.serialize()
  30588. ], Texture.prototype, "url", void 0);
  30589. __decorate([
  30590. BABYLON.serialize()
  30591. ], Texture.prototype, "uOffset", void 0);
  30592. __decorate([
  30593. BABYLON.serialize()
  30594. ], Texture.prototype, "vOffset", void 0);
  30595. __decorate([
  30596. BABYLON.serialize()
  30597. ], Texture.prototype, "uScale", void 0);
  30598. __decorate([
  30599. BABYLON.serialize()
  30600. ], Texture.prototype, "vScale", void 0);
  30601. __decorate([
  30602. BABYLON.serialize()
  30603. ], Texture.prototype, "uAng", void 0);
  30604. __decorate([
  30605. BABYLON.serialize()
  30606. ], Texture.prototype, "vAng", void 0);
  30607. __decorate([
  30608. BABYLON.serialize()
  30609. ], Texture.prototype, "wAng", void 0);
  30610. __decorate([
  30611. BABYLON.serialize()
  30612. ], Texture.prototype, "isBlocking", null);
  30613. return Texture;
  30614. }(BABYLON.BaseTexture));
  30615. BABYLON.Texture = Texture;
  30616. })(BABYLON || (BABYLON = {}));
  30617. //# sourceMappingURL=babylon.texture.js.map
  30618. var BABYLON;
  30619. (function (BABYLON) {
  30620. var _InstancesBatch = /** @class */ (function () {
  30621. function _InstancesBatch() {
  30622. this.mustReturn = false;
  30623. this.visibleInstances = new Array();
  30624. this.renderSelf = new Array();
  30625. }
  30626. return _InstancesBatch;
  30627. }());
  30628. BABYLON._InstancesBatch = _InstancesBatch;
  30629. var Mesh = /** @class */ (function (_super) {
  30630. __extends(Mesh, _super);
  30631. /**
  30632. * @constructor
  30633. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30634. * @param {Scene} scene The scene to add this mesh to.
  30635. * @param {Node} parent The parent of this mesh, if it has one
  30636. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30637. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30638. * When false, achieved by calling a clone(), also passing False.
  30639. * This will make creation of children, recursive.
  30640. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30641. */
  30642. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30643. if (scene === void 0) { scene = null; }
  30644. if (parent === void 0) { parent = null; }
  30645. if (source === void 0) { source = null; }
  30646. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30647. var _this = _super.call(this, name, scene) || this;
  30648. // Events
  30649. /**
  30650. * An event triggered before rendering the mesh
  30651. */
  30652. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30653. /**
  30654. * An event triggered after rendering the mesh
  30655. */
  30656. _this.onAfterRenderObservable = new BABYLON.Observable();
  30657. /**
  30658. * An event triggered before drawing the mesh
  30659. */
  30660. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30661. // Members
  30662. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30663. _this.instances = new Array();
  30664. _this._LODLevels = new Array();
  30665. _this._visibleInstances = {};
  30666. _this._renderIdForInstances = new Array();
  30667. _this._batchCache = new _InstancesBatch();
  30668. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30669. // Use by builder only to know what orientation were the mesh build in.
  30670. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30671. _this.overrideMaterialSideOrientation = null;
  30672. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30673. // Will be used to save a source mesh reference, If any
  30674. _this._source = null;
  30675. scene = _this.getScene();
  30676. if (source) {
  30677. // Source mesh
  30678. _this._source = source;
  30679. // Geometry
  30680. if (source._geometry) {
  30681. source._geometry.applyToMesh(_this);
  30682. }
  30683. // Deep copy
  30684. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30685. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30686. // Metadata
  30687. if (source.metadata && source.metadata.clone) {
  30688. _this.metadata = source.metadata.clone();
  30689. }
  30690. else {
  30691. _this.metadata = source.metadata;
  30692. }
  30693. // Tags
  30694. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30695. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30696. }
  30697. // Parent
  30698. _this.parent = source.parent;
  30699. // Pivot
  30700. _this.setPivotMatrix(source.getPivotMatrix());
  30701. _this.id = name + "." + source.id;
  30702. // Material
  30703. _this.material = source.material;
  30704. var index;
  30705. if (!doNotCloneChildren) {
  30706. // Children
  30707. var directDescendants = source.getDescendants(true);
  30708. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30709. var child = directDescendants[index_1];
  30710. if (child.clone) {
  30711. child.clone(name + "." + child.name, _this);
  30712. }
  30713. }
  30714. }
  30715. // Physics clone
  30716. var physicsEngine = _this.getScene().getPhysicsEngine();
  30717. if (clonePhysicsImpostor && physicsEngine) {
  30718. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30719. if (impostor) {
  30720. _this.physicsImpostor = impostor.clone(_this);
  30721. }
  30722. }
  30723. // Particles
  30724. for (index = 0; index < scene.particleSystems.length; index++) {
  30725. var system = scene.particleSystems[index];
  30726. if (system.emitter === source) {
  30727. system.clone(system.name, _this);
  30728. }
  30729. }
  30730. _this.computeWorldMatrix(true);
  30731. }
  30732. // Parent
  30733. if (parent !== null) {
  30734. _this.parent = parent;
  30735. }
  30736. return _this;
  30737. }
  30738. Object.defineProperty(Mesh, "FRONTSIDE", {
  30739. /**
  30740. * Mesh side orientation : usually the external or front surface
  30741. */
  30742. get: function () {
  30743. return Mesh._FRONTSIDE;
  30744. },
  30745. enumerable: true,
  30746. configurable: true
  30747. });
  30748. Object.defineProperty(Mesh, "BACKSIDE", {
  30749. /**
  30750. * Mesh side orientation : usually the internal or back surface
  30751. */
  30752. get: function () {
  30753. return Mesh._BACKSIDE;
  30754. },
  30755. enumerable: true,
  30756. configurable: true
  30757. });
  30758. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30759. /**
  30760. * Mesh side orientation : both internal and external or front and back surfaces
  30761. */
  30762. get: function () {
  30763. return Mesh._DOUBLESIDE;
  30764. },
  30765. enumerable: true,
  30766. configurable: true
  30767. });
  30768. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30769. /**
  30770. * Mesh side orientation : by default, `FRONTSIDE`
  30771. */
  30772. get: function () {
  30773. return Mesh._DEFAULTSIDE;
  30774. },
  30775. enumerable: true,
  30776. configurable: true
  30777. });
  30778. Object.defineProperty(Mesh, "NO_CAP", {
  30779. /**
  30780. * Mesh cap setting : no cap
  30781. */
  30782. get: function () {
  30783. return Mesh._NO_CAP;
  30784. },
  30785. enumerable: true,
  30786. configurable: true
  30787. });
  30788. Object.defineProperty(Mesh, "CAP_START", {
  30789. /**
  30790. * Mesh cap setting : one cap at the beginning of the mesh
  30791. */
  30792. get: function () {
  30793. return Mesh._CAP_START;
  30794. },
  30795. enumerable: true,
  30796. configurable: true
  30797. });
  30798. Object.defineProperty(Mesh, "CAP_END", {
  30799. /**
  30800. * Mesh cap setting : one cap at the end of the mesh
  30801. */
  30802. get: function () {
  30803. return Mesh._CAP_END;
  30804. },
  30805. enumerable: true,
  30806. configurable: true
  30807. });
  30808. Object.defineProperty(Mesh, "CAP_ALL", {
  30809. /**
  30810. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30811. */
  30812. get: function () {
  30813. return Mesh._CAP_ALL;
  30814. },
  30815. enumerable: true,
  30816. configurable: true
  30817. });
  30818. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30819. set: function (callback) {
  30820. if (this._onBeforeDrawObserver) {
  30821. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30822. }
  30823. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30824. },
  30825. enumerable: true,
  30826. configurable: true
  30827. });
  30828. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30829. get: function () {
  30830. return this._morphTargetManager;
  30831. },
  30832. set: function (value) {
  30833. if (this._morphTargetManager === value) {
  30834. return;
  30835. }
  30836. this._morphTargetManager = value;
  30837. this._syncGeometryWithMorphTargetManager();
  30838. },
  30839. enumerable: true,
  30840. configurable: true
  30841. });
  30842. Object.defineProperty(Mesh.prototype, "source", {
  30843. get: function () {
  30844. return this._source;
  30845. },
  30846. enumerable: true,
  30847. configurable: true
  30848. });
  30849. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30850. get: function () {
  30851. return this._unIndexed;
  30852. },
  30853. set: function (value) {
  30854. if (this._unIndexed !== value) {
  30855. this._unIndexed = value;
  30856. this._markSubMeshesAsAttributesDirty();
  30857. }
  30858. },
  30859. enumerable: true,
  30860. configurable: true
  30861. });
  30862. // Methods
  30863. /**
  30864. * Returns the string "Mesh".
  30865. */
  30866. Mesh.prototype.getClassName = function () {
  30867. return "Mesh";
  30868. };
  30869. /**
  30870. * Returns a string.
  30871. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30872. */
  30873. Mesh.prototype.toString = function (fullDetails) {
  30874. var ret = _super.prototype.toString.call(this, fullDetails);
  30875. ret += ", n vertices: " + this.getTotalVertices();
  30876. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30877. if (this.animations) {
  30878. for (var i = 0; i < this.animations.length; i++) {
  30879. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30880. }
  30881. }
  30882. if (fullDetails) {
  30883. if (this._geometry) {
  30884. var ib = this.getIndices();
  30885. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30886. if (vb && ib) {
  30887. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30888. }
  30889. }
  30890. else {
  30891. ret += ", flat shading: UNKNOWN";
  30892. }
  30893. }
  30894. return ret;
  30895. };
  30896. Mesh.prototype._unBindEffect = function () {
  30897. _super.prototype._unBindEffect.call(this);
  30898. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30899. var instance = _a[_i];
  30900. instance._unBindEffect();
  30901. }
  30902. };
  30903. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30904. /**
  30905. * True if the mesh has some Levels Of Details (LOD).
  30906. * Returns a boolean.
  30907. */
  30908. get: function () {
  30909. return this._LODLevels.length > 0;
  30910. },
  30911. enumerable: true,
  30912. configurable: true
  30913. });
  30914. /**
  30915. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30916. * @returns an array of {BABYLON.MeshLODLevel}
  30917. */
  30918. Mesh.prototype.getLODLevels = function () {
  30919. return this._LODLevels;
  30920. };
  30921. Mesh.prototype._sortLODLevels = function () {
  30922. this._LODLevels.sort(function (a, b) {
  30923. if (a.distance < b.distance) {
  30924. return 1;
  30925. }
  30926. if (a.distance > b.distance) {
  30927. return -1;
  30928. }
  30929. return 0;
  30930. });
  30931. };
  30932. /**
  30933. * Add a mesh as LOD level triggered at the given distance.
  30934. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30935. * @param {number} distance The distance from the center of the object to show this level
  30936. * @param {Mesh} mesh The mesh to be added as LOD level
  30937. * @return {Mesh} This mesh (for chaining)
  30938. */
  30939. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30940. if (mesh && mesh._masterMesh) {
  30941. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30942. return this;
  30943. }
  30944. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30945. this._LODLevels.push(level);
  30946. if (mesh) {
  30947. mesh._masterMesh = this;
  30948. }
  30949. this._sortLODLevels();
  30950. return this;
  30951. };
  30952. /**
  30953. * Returns the LOD level mesh at the passed distance or null if not found.
  30954. * It is related to the method `addLODLevel(distance, mesh)`.
  30955. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30956. * Returns an object Mesh or `null`.
  30957. */
  30958. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30959. for (var index = 0; index < this._LODLevels.length; index++) {
  30960. var level = this._LODLevels[index];
  30961. if (level.distance === distance) {
  30962. return level.mesh;
  30963. }
  30964. }
  30965. return null;
  30966. };
  30967. /**
  30968. * Remove a mesh from the LOD array
  30969. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30970. * @param {Mesh} mesh The mesh to be removed.
  30971. * @return {Mesh} This mesh (for chaining)
  30972. */
  30973. Mesh.prototype.removeLODLevel = function (mesh) {
  30974. for (var index = 0; index < this._LODLevels.length; index++) {
  30975. if (this._LODLevels[index].mesh === mesh) {
  30976. this._LODLevels.splice(index, 1);
  30977. if (mesh) {
  30978. mesh._masterMesh = null;
  30979. }
  30980. }
  30981. }
  30982. this._sortLODLevels();
  30983. return this;
  30984. };
  30985. /**
  30986. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30987. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30988. */
  30989. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30990. if (!this._LODLevels || this._LODLevels.length === 0) {
  30991. return this;
  30992. }
  30993. var bSphere;
  30994. if (boundingSphere) {
  30995. bSphere = boundingSphere;
  30996. }
  30997. else {
  30998. var boundingInfo = this.getBoundingInfo();
  30999. bSphere = boundingInfo.boundingSphere;
  31000. }
  31001. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31002. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31003. if (this.onLODLevelSelection) {
  31004. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31005. }
  31006. return this;
  31007. }
  31008. for (var index = 0; index < this._LODLevels.length; index++) {
  31009. var level = this._LODLevels[index];
  31010. if (level.distance < distanceToCamera) {
  31011. if (level.mesh) {
  31012. level.mesh._preActivate();
  31013. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31014. }
  31015. if (this.onLODLevelSelection) {
  31016. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31017. }
  31018. return level.mesh;
  31019. }
  31020. }
  31021. if (this.onLODLevelSelection) {
  31022. this.onLODLevelSelection(distanceToCamera, this, this);
  31023. }
  31024. return this;
  31025. };
  31026. Object.defineProperty(Mesh.prototype, "geometry", {
  31027. /**
  31028. * Returns the mesh internal Geometry object.
  31029. */
  31030. get: function () {
  31031. return this._geometry;
  31032. },
  31033. enumerable: true,
  31034. configurable: true
  31035. });
  31036. /**
  31037. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31038. */
  31039. Mesh.prototype.getTotalVertices = function () {
  31040. if (this._geometry === null || this._geometry === undefined) {
  31041. return 0;
  31042. }
  31043. return this._geometry.getTotalVertices();
  31044. };
  31045. /**
  31046. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31047. * 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.
  31048. * You can force the copy with forceCopy === true
  31049. * Returns null if the mesh has no geometry or no vertex buffer.
  31050. * Possible `kind` values :
  31051. * - BABYLON.VertexBuffer.PositionKind
  31052. * - BABYLON.VertexBuffer.UVKind
  31053. * - BABYLON.VertexBuffer.UV2Kind
  31054. * - BABYLON.VertexBuffer.UV3Kind
  31055. * - BABYLON.VertexBuffer.UV4Kind
  31056. * - BABYLON.VertexBuffer.UV5Kind
  31057. * - BABYLON.VertexBuffer.UV6Kind
  31058. * - BABYLON.VertexBuffer.ColorKind
  31059. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31060. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31061. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31062. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31063. */
  31064. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31065. if (!this._geometry) {
  31066. return null;
  31067. }
  31068. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31069. };
  31070. /**
  31071. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31072. * Returns `null` if the mesh has no geometry.
  31073. * Possible `kind` values :
  31074. * - BABYLON.VertexBuffer.PositionKind
  31075. * - BABYLON.VertexBuffer.UVKind
  31076. * - BABYLON.VertexBuffer.UV2Kind
  31077. * - BABYLON.VertexBuffer.UV3Kind
  31078. * - BABYLON.VertexBuffer.UV4Kind
  31079. * - BABYLON.VertexBuffer.UV5Kind
  31080. * - BABYLON.VertexBuffer.UV6Kind
  31081. * - BABYLON.VertexBuffer.ColorKind
  31082. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31083. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31084. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31085. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31086. */
  31087. Mesh.prototype.getVertexBuffer = function (kind) {
  31088. if (!this._geometry) {
  31089. return null;
  31090. }
  31091. return this._geometry.getVertexBuffer(kind);
  31092. };
  31093. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31094. if (!this._geometry) {
  31095. if (this._delayInfo) {
  31096. return this._delayInfo.indexOf(kind) !== -1;
  31097. }
  31098. return false;
  31099. }
  31100. return this._geometry.isVerticesDataPresent(kind);
  31101. };
  31102. /**
  31103. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31104. * Possible `kind` values :
  31105. * - BABYLON.VertexBuffer.PositionKind
  31106. * - BABYLON.VertexBuffer.UVKind
  31107. * - BABYLON.VertexBuffer.UV2Kind
  31108. * - BABYLON.VertexBuffer.UV3Kind
  31109. * - BABYLON.VertexBuffer.UV4Kind
  31110. * - BABYLON.VertexBuffer.UV5Kind
  31111. * - BABYLON.VertexBuffer.UV6Kind
  31112. * - BABYLON.VertexBuffer.ColorKind
  31113. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31114. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31115. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31116. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31117. */
  31118. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31119. if (!this._geometry) {
  31120. if (this._delayInfo) {
  31121. return this._delayInfo.indexOf(kind) !== -1;
  31122. }
  31123. return false;
  31124. }
  31125. return this._geometry.isVertexBufferUpdatable(kind);
  31126. };
  31127. /**
  31128. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31129. * Possible `kind` values :
  31130. * - BABYLON.VertexBuffer.PositionKind
  31131. * - BABYLON.VertexBuffer.UVKind
  31132. * - BABYLON.VertexBuffer.UV2Kind
  31133. * - BABYLON.VertexBuffer.UV3Kind
  31134. * - BABYLON.VertexBuffer.UV4Kind
  31135. * - BABYLON.VertexBuffer.UV5Kind
  31136. * - BABYLON.VertexBuffer.UV6Kind
  31137. * - BABYLON.VertexBuffer.ColorKind
  31138. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31139. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31140. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31141. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31142. */
  31143. Mesh.prototype.getVerticesDataKinds = function () {
  31144. if (!this._geometry) {
  31145. var result = new Array();
  31146. if (this._delayInfo) {
  31147. this._delayInfo.forEach(function (kind, index, array) {
  31148. result.push(kind);
  31149. });
  31150. }
  31151. return result;
  31152. }
  31153. return this._geometry.getVerticesDataKinds();
  31154. };
  31155. /**
  31156. * Returns a positive integer : the total number of indices in this mesh geometry.
  31157. * Returns zero if the mesh has no geometry.
  31158. */
  31159. Mesh.prototype.getTotalIndices = function () {
  31160. if (!this._geometry) {
  31161. return 0;
  31162. }
  31163. return this._geometry.getTotalIndices();
  31164. };
  31165. /**
  31166. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31167. * 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.
  31168. * Returns an empty array if the mesh has no geometry.
  31169. */
  31170. Mesh.prototype.getIndices = function (copyWhenShared) {
  31171. if (!this._geometry) {
  31172. return [];
  31173. }
  31174. return this._geometry.getIndices(copyWhenShared);
  31175. };
  31176. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31177. get: function () {
  31178. return this._masterMesh !== null && this._masterMesh !== undefined;
  31179. },
  31180. enumerable: true,
  31181. configurable: true
  31182. });
  31183. /**
  31184. * Determine if the current mesh is ready to be rendered
  31185. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31186. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31187. * @returns true if all associated assets are ready (material, textures, shaders)
  31188. */
  31189. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31190. if (completeCheck === void 0) { completeCheck = false; }
  31191. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31192. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31193. return false;
  31194. }
  31195. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31196. return false;
  31197. }
  31198. if (!this.subMeshes || this.subMeshes.length === 0) {
  31199. return true;
  31200. }
  31201. if (!completeCheck) {
  31202. return true;
  31203. }
  31204. var engine = this.getEngine();
  31205. var scene = this.getScene();
  31206. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31207. this.computeWorldMatrix();
  31208. var mat = this.material || scene.defaultMaterial;
  31209. if (mat) {
  31210. if (mat.storeEffectOnSubMeshes) {
  31211. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31212. var subMesh = _a[_i];
  31213. var effectiveMaterial = subMesh.getMaterial();
  31214. if (effectiveMaterial) {
  31215. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31216. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31217. return false;
  31218. }
  31219. }
  31220. else {
  31221. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31222. return false;
  31223. }
  31224. }
  31225. }
  31226. }
  31227. }
  31228. else {
  31229. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31230. return false;
  31231. }
  31232. }
  31233. }
  31234. // Shadows
  31235. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31236. var light = _c[_b];
  31237. var generator = light.getShadowGenerator();
  31238. if (generator) {
  31239. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31240. var subMesh = _e[_d];
  31241. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31242. return false;
  31243. }
  31244. }
  31245. }
  31246. }
  31247. // LOD
  31248. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31249. var lod = _g[_f];
  31250. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31251. return false;
  31252. }
  31253. }
  31254. return true;
  31255. };
  31256. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31257. /**
  31258. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31259. * This property is pertinent only for updatable parametric shapes.
  31260. */
  31261. get: function () {
  31262. return this._areNormalsFrozen;
  31263. },
  31264. enumerable: true,
  31265. configurable: true
  31266. });
  31267. /**
  31268. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31269. * It has no effect at all on other shapes.
  31270. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31271. * Returns the Mesh.
  31272. */
  31273. Mesh.prototype.freezeNormals = function () {
  31274. this._areNormalsFrozen = true;
  31275. return this;
  31276. };
  31277. /**
  31278. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31279. * It has no effect at all on other shapes.
  31280. * It reactivates the mesh normals computation if it was previously frozen.
  31281. * Returns the Mesh.
  31282. */
  31283. Mesh.prototype.unfreezeNormals = function () {
  31284. this._areNormalsFrozen = false;
  31285. return this;
  31286. };
  31287. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31288. /**
  31289. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31290. */
  31291. set: function (count) {
  31292. this._overridenInstanceCount = count;
  31293. },
  31294. enumerable: true,
  31295. configurable: true
  31296. });
  31297. // Methods
  31298. Mesh.prototype._preActivate = function () {
  31299. var sceneRenderId = this.getScene().getRenderId();
  31300. if (this._preActivateId === sceneRenderId) {
  31301. return this;
  31302. }
  31303. this._preActivateId = sceneRenderId;
  31304. this._visibleInstances = null;
  31305. return this;
  31306. };
  31307. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31308. if (this._visibleInstances) {
  31309. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31310. }
  31311. return this;
  31312. };
  31313. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31314. if (!this._visibleInstances) {
  31315. this._visibleInstances = {};
  31316. this._visibleInstances.defaultRenderId = renderId;
  31317. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31318. }
  31319. if (!this._visibleInstances[renderId]) {
  31320. this._visibleInstances[renderId] = new Array();
  31321. }
  31322. this._visibleInstances[renderId].push(instance);
  31323. return this;
  31324. };
  31325. /**
  31326. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31327. * This means the mesh underlying bounding box and sphere are recomputed.
  31328. * Returns the Mesh.
  31329. */
  31330. Mesh.prototype.refreshBoundingInfo = function () {
  31331. return this._refreshBoundingInfo(false);
  31332. };
  31333. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31334. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31335. return this;
  31336. }
  31337. var data = this._getPositionData(applySkeleton);
  31338. if (data) {
  31339. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31340. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31341. }
  31342. if (this.subMeshes) {
  31343. for (var index = 0; index < this.subMeshes.length; index++) {
  31344. this.subMeshes[index].refreshBoundingInfo();
  31345. }
  31346. }
  31347. this._updateBoundingInfo();
  31348. return this;
  31349. };
  31350. Mesh.prototype._getPositionData = function (applySkeleton) {
  31351. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31352. if (data && applySkeleton && this.skeleton) {
  31353. data = BABYLON.Tools.Slice(data);
  31354. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31355. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31356. if (matricesWeightsData && matricesIndicesData) {
  31357. var needExtras = this.numBoneInfluencers > 4;
  31358. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31359. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31360. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31361. var tempVector = BABYLON.Tmp.Vector3[0];
  31362. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31363. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31364. var matWeightIdx = 0;
  31365. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31366. finalMatrix.reset();
  31367. var inf;
  31368. var weight;
  31369. for (inf = 0; inf < 4; inf++) {
  31370. weight = matricesWeightsData[matWeightIdx + inf];
  31371. if (weight <= 0)
  31372. break;
  31373. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31374. finalMatrix.addToSelf(tempMatrix);
  31375. }
  31376. if (needExtras) {
  31377. for (inf = 0; inf < 4; inf++) {
  31378. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31379. if (weight <= 0)
  31380. break;
  31381. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31382. finalMatrix.addToSelf(tempMatrix);
  31383. }
  31384. }
  31385. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31386. tempVector.toArray(data, index);
  31387. }
  31388. }
  31389. }
  31390. return data;
  31391. };
  31392. Mesh.prototype._createGlobalSubMesh = function (force) {
  31393. var totalVertices = this.getTotalVertices();
  31394. if (!totalVertices || !this.getIndices()) {
  31395. return null;
  31396. }
  31397. // Check if we need to recreate the submeshes
  31398. if (this.subMeshes && this.subMeshes.length > 0) {
  31399. var ib = this.getIndices();
  31400. if (!ib) {
  31401. return null;
  31402. }
  31403. var totalIndices = ib.length;
  31404. var needToRecreate = false;
  31405. if (force) {
  31406. needToRecreate = true;
  31407. }
  31408. else {
  31409. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31410. var submesh = _a[_i];
  31411. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31412. needToRecreate = true;
  31413. break;
  31414. }
  31415. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31416. needToRecreate = true;
  31417. break;
  31418. }
  31419. }
  31420. }
  31421. if (!needToRecreate) {
  31422. return this.subMeshes[0];
  31423. }
  31424. }
  31425. this.releaseSubMeshes();
  31426. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31427. };
  31428. Mesh.prototype.subdivide = function (count) {
  31429. if (count < 1) {
  31430. return;
  31431. }
  31432. var totalIndices = this.getTotalIndices();
  31433. var subdivisionSize = (totalIndices / count) | 0;
  31434. var offset = 0;
  31435. // Ensure that subdivisionSize is a multiple of 3
  31436. while (subdivisionSize % 3 !== 0) {
  31437. subdivisionSize++;
  31438. }
  31439. this.releaseSubMeshes();
  31440. for (var index = 0; index < count; index++) {
  31441. if (offset >= totalIndices) {
  31442. break;
  31443. }
  31444. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31445. offset += subdivisionSize;
  31446. }
  31447. this.synchronizeInstances();
  31448. };
  31449. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31450. if (updatable === void 0) { updatable = false; }
  31451. if (!this._geometry) {
  31452. var vertexData = new BABYLON.VertexData();
  31453. vertexData.set(data, kind);
  31454. var scene = this.getScene();
  31455. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31456. }
  31457. else {
  31458. this._geometry.setVerticesData(kind, data, updatable, stride);
  31459. }
  31460. return this;
  31461. };
  31462. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31463. if (updatable === void 0) { updatable = true; }
  31464. var vb = this.getVertexBuffer(kind);
  31465. if (!vb || vb.isUpdatable() === updatable) {
  31466. return;
  31467. }
  31468. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31469. };
  31470. /**
  31471. * Sets the mesh VertexBuffer.
  31472. * Returns the Mesh.
  31473. */
  31474. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31475. if (!this._geometry) {
  31476. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31477. }
  31478. this._geometry.setVerticesBuffer(buffer);
  31479. return this;
  31480. };
  31481. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31482. if (!this._geometry) {
  31483. return this;
  31484. }
  31485. if (!makeItUnique) {
  31486. this._geometry.updateVerticesData(kind, data, updateExtends);
  31487. }
  31488. else {
  31489. this.makeGeometryUnique();
  31490. this.updateVerticesData(kind, data, updateExtends, false);
  31491. }
  31492. return this;
  31493. };
  31494. /**
  31495. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31496. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31497. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31498. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31499. * Returns the Mesh.
  31500. */
  31501. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31502. if (computeNormals === void 0) { computeNormals = true; }
  31503. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31504. if (!positions) {
  31505. return this;
  31506. }
  31507. positionFunction(positions);
  31508. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31509. if (computeNormals) {
  31510. var indices = this.getIndices();
  31511. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31512. if (!normals) {
  31513. return this;
  31514. }
  31515. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31516. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31517. }
  31518. return this;
  31519. };
  31520. /**
  31521. * Creates a un-shared specific occurence of the geometry for the mesh.
  31522. * Returns the Mesh.
  31523. */
  31524. Mesh.prototype.makeGeometryUnique = function () {
  31525. if (!this._geometry) {
  31526. return this;
  31527. }
  31528. var oldGeometry = this._geometry;
  31529. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31530. oldGeometry.releaseForMesh(this, true);
  31531. geometry.applyToMesh(this);
  31532. return this;
  31533. };
  31534. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31535. if (totalVertices === void 0) { totalVertices = null; }
  31536. if (updatable === void 0) { updatable = false; }
  31537. if (!this._geometry) {
  31538. var vertexData = new BABYLON.VertexData();
  31539. vertexData.indices = indices;
  31540. var scene = this.getScene();
  31541. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31542. }
  31543. else {
  31544. this._geometry.setIndices(indices, totalVertices, updatable);
  31545. }
  31546. return this;
  31547. };
  31548. /**
  31549. * Update the current index buffer
  31550. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31551. * Returns the Mesh.
  31552. */
  31553. Mesh.prototype.updateIndices = function (indices, offset) {
  31554. if (!this._geometry) {
  31555. return this;
  31556. }
  31557. this._geometry.updateIndices(indices, offset);
  31558. return this;
  31559. };
  31560. /**
  31561. * Invert the geometry to move from a right handed system to a left handed one.
  31562. * Returns the Mesh.
  31563. */
  31564. Mesh.prototype.toLeftHanded = function () {
  31565. if (!this._geometry) {
  31566. return this;
  31567. }
  31568. this._geometry.toLeftHanded();
  31569. return this;
  31570. };
  31571. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31572. if (!this._geometry) {
  31573. return this;
  31574. }
  31575. var engine = this.getScene().getEngine();
  31576. // Wireframe
  31577. var indexToBind;
  31578. if (this._unIndexed) {
  31579. indexToBind = null;
  31580. }
  31581. else {
  31582. switch (fillMode) {
  31583. case BABYLON.Material.PointFillMode:
  31584. indexToBind = null;
  31585. break;
  31586. case BABYLON.Material.WireFrameFillMode:
  31587. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31588. break;
  31589. default:
  31590. case BABYLON.Material.TriangleFillMode:
  31591. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31592. break;
  31593. }
  31594. }
  31595. // VBOs
  31596. this._geometry._bind(effect, indexToBind);
  31597. return this;
  31598. };
  31599. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31600. if (alternate === void 0) { alternate = false; }
  31601. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31602. return this;
  31603. }
  31604. this.onBeforeDrawObservable.notifyObservers(this);
  31605. var scene = this.getScene();
  31606. var engine = scene.getEngine();
  31607. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31608. // or triangles as points
  31609. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31610. }
  31611. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31612. // Triangles as wireframe
  31613. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31614. }
  31615. else {
  31616. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31617. }
  31618. if (scene._isAlternateRenderingEnabled && !alternate) {
  31619. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31620. if (!effect || !scene.activeCamera) {
  31621. return this;
  31622. }
  31623. scene._switchToAlternateCameraConfiguration(true);
  31624. this._effectiveMaterial.bindView(effect);
  31625. this._effectiveMaterial.bindViewProjection(effect);
  31626. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31627. this._draw(subMesh, fillMode, instancesCount, true);
  31628. engine.setViewport(scene.activeCamera.viewport);
  31629. scene._switchToAlternateCameraConfiguration(false);
  31630. this._effectiveMaterial.bindView(effect);
  31631. this._effectiveMaterial.bindViewProjection(effect);
  31632. }
  31633. return this;
  31634. };
  31635. /**
  31636. * Registers for this mesh a javascript function called just before the rendering process.
  31637. * This function is passed the current mesh.
  31638. * Return the Mesh.
  31639. */
  31640. Mesh.prototype.registerBeforeRender = function (func) {
  31641. this.onBeforeRenderObservable.add(func);
  31642. return this;
  31643. };
  31644. /**
  31645. * Disposes a previously registered javascript function called before the rendering.
  31646. * This function is passed the current mesh.
  31647. * Returns the Mesh.
  31648. */
  31649. Mesh.prototype.unregisterBeforeRender = function (func) {
  31650. this.onBeforeRenderObservable.removeCallback(func);
  31651. return this;
  31652. };
  31653. /**
  31654. * Registers for this mesh a javascript function called just after the rendering is complete.
  31655. * This function is passed the current mesh.
  31656. * Returns the Mesh.
  31657. */
  31658. Mesh.prototype.registerAfterRender = function (func) {
  31659. this.onAfterRenderObservable.add(func);
  31660. return this;
  31661. };
  31662. /**
  31663. * Disposes a previously registered javascript function called after the rendering.
  31664. * This function is passed the current mesh.
  31665. * Return the Mesh.
  31666. */
  31667. Mesh.prototype.unregisterAfterRender = function (func) {
  31668. this.onAfterRenderObservable.removeCallback(func);
  31669. return this;
  31670. };
  31671. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31672. var scene = this.getScene();
  31673. this._batchCache.mustReturn = false;
  31674. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31675. this._batchCache.visibleInstances[subMeshId] = null;
  31676. if (this._visibleInstances) {
  31677. var currentRenderId = scene.getRenderId();
  31678. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31679. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31680. var selfRenderId = this._renderId;
  31681. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31682. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31683. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31684. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31685. }
  31686. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31687. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31688. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31689. this._batchCache.mustReturn = true;
  31690. return this._batchCache;
  31691. }
  31692. if (currentRenderId !== selfRenderId) {
  31693. this._batchCache.renderSelf[subMeshId] = false;
  31694. }
  31695. }
  31696. this._renderIdForInstances[subMeshId] = currentRenderId;
  31697. }
  31698. return this._batchCache;
  31699. };
  31700. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31701. var visibleInstances = batch.visibleInstances[subMesh._id];
  31702. if (!visibleInstances) {
  31703. return this;
  31704. }
  31705. var matricesCount = visibleInstances.length + 1;
  31706. var bufferSize = matricesCount * 16 * 4;
  31707. var currentInstancesBufferSize = this._instancesBufferSize;
  31708. var instancesBuffer = this._instancesBuffer;
  31709. while (this._instancesBufferSize < bufferSize) {
  31710. this._instancesBufferSize *= 2;
  31711. }
  31712. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31713. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31714. }
  31715. var offset = 0;
  31716. var instancesCount = 0;
  31717. var world = this.getWorldMatrix();
  31718. if (batch.renderSelf[subMesh._id]) {
  31719. world.copyToArray(this._instancesData, offset);
  31720. offset += 16;
  31721. instancesCount++;
  31722. }
  31723. if (visibleInstances) {
  31724. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31725. var instance = visibleInstances[instanceIndex];
  31726. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31727. offset += 16;
  31728. instancesCount++;
  31729. }
  31730. }
  31731. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31732. if (instancesBuffer) {
  31733. instancesBuffer.dispose();
  31734. }
  31735. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31736. this._instancesBuffer = instancesBuffer;
  31737. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31738. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31739. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31740. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31741. }
  31742. else {
  31743. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31744. }
  31745. this._bind(subMesh, effect, fillMode);
  31746. this._draw(subMesh, fillMode, instancesCount);
  31747. engine.unbindInstanceAttributes();
  31748. return this;
  31749. };
  31750. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31751. var scene = this.getScene();
  31752. var engine = scene.getEngine();
  31753. if (hardwareInstancedRendering) {
  31754. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31755. }
  31756. else {
  31757. if (batch.renderSelf[subMesh._id]) {
  31758. // Draw
  31759. if (onBeforeDraw) {
  31760. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31761. }
  31762. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31763. }
  31764. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31765. if (visibleInstancesForSubMesh) {
  31766. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31767. var instance = visibleInstancesForSubMesh[instanceIndex];
  31768. // World
  31769. var world = instance.getWorldMatrix();
  31770. if (onBeforeDraw) {
  31771. onBeforeDraw(true, world, effectiveMaterial);
  31772. }
  31773. // Draw
  31774. this._draw(subMesh, fillMode);
  31775. }
  31776. }
  31777. }
  31778. return this;
  31779. };
  31780. /**
  31781. * Triggers the draw call for the mesh.
  31782. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31783. * Returns the Mesh.
  31784. */
  31785. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31786. this._checkOcclusionQuery();
  31787. if (this._isOccluded) {
  31788. return this;
  31789. }
  31790. var scene = this.getScene();
  31791. // Managing instances
  31792. var batch = this._getInstancesRenderList(subMesh._id);
  31793. if (batch.mustReturn) {
  31794. return this;
  31795. }
  31796. // Checking geometry state
  31797. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31798. return this;
  31799. }
  31800. this.onBeforeRenderObservable.notifyObservers(this);
  31801. var engine = scene.getEngine();
  31802. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31803. // Material
  31804. var material = subMesh.getMaterial();
  31805. if (!material) {
  31806. return this;
  31807. }
  31808. this._effectiveMaterial = material;
  31809. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31810. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31811. return this;
  31812. }
  31813. }
  31814. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31815. return this;
  31816. }
  31817. // Alpha mode
  31818. if (enableAlphaMode) {
  31819. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31820. }
  31821. // Outline - step 1
  31822. var savedDepthWrite = engine.getDepthWrite();
  31823. if (this.renderOutline) {
  31824. engine.setDepthWrite(false);
  31825. scene.getOutlineRenderer().render(subMesh, batch);
  31826. engine.setDepthWrite(savedDepthWrite);
  31827. }
  31828. var effect;
  31829. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31830. effect = subMesh.effect;
  31831. }
  31832. else {
  31833. effect = this._effectiveMaterial.getEffect();
  31834. }
  31835. if (!effect) {
  31836. return this;
  31837. }
  31838. var sideOrientation = this.overrideMaterialSideOrientation;
  31839. if (sideOrientation == null) {
  31840. sideOrientation = this._effectiveMaterial.sideOrientation;
  31841. if (this._getWorldMatrixDeterminant() < 0) {
  31842. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31843. }
  31844. }
  31845. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31846. if (this._effectiveMaterial.forceDepthWrite) {
  31847. engine.setDepthWrite(true);
  31848. }
  31849. // Bind
  31850. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31851. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31852. this._bind(subMesh, effect, fillMode);
  31853. }
  31854. var world = this.getWorldMatrix();
  31855. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31856. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31857. }
  31858. else {
  31859. this._effectiveMaterial.bind(world, this);
  31860. }
  31861. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31862. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31863. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31864. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31865. }
  31866. // Draw
  31867. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31868. // Unbind
  31869. this._effectiveMaterial.unbind();
  31870. // Outline - step 2
  31871. if (this.renderOutline && savedDepthWrite) {
  31872. engine.setDepthWrite(true);
  31873. engine.setColorWrite(false);
  31874. scene.getOutlineRenderer().render(subMesh, batch);
  31875. engine.setColorWrite(true);
  31876. }
  31877. // Overlay
  31878. if (this.renderOverlay) {
  31879. var currentMode = engine.getAlphaMode();
  31880. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31881. scene.getOutlineRenderer().render(subMesh, batch, true);
  31882. engine.setAlphaMode(currentMode);
  31883. }
  31884. this.onAfterRenderObservable.notifyObservers(this);
  31885. return this;
  31886. };
  31887. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31888. if (isInstance && effectiveMaterial) {
  31889. effectiveMaterial.bindOnlyWorldMatrix(world);
  31890. }
  31891. };
  31892. /**
  31893. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31894. */
  31895. Mesh.prototype.getEmittedParticleSystems = function () {
  31896. var results = new Array();
  31897. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31898. var particleSystem = this.getScene().particleSystems[index];
  31899. if (particleSystem.emitter === this) {
  31900. results.push(particleSystem);
  31901. }
  31902. }
  31903. return results;
  31904. };
  31905. /**
  31906. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31907. */
  31908. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31909. var results = new Array();
  31910. var descendants = this.getDescendants();
  31911. descendants.push(this);
  31912. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31913. var particleSystem = this.getScene().particleSystems[index];
  31914. var emitter = particleSystem.emitter;
  31915. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31916. results.push(particleSystem);
  31917. }
  31918. }
  31919. return results;
  31920. };
  31921. Mesh.prototype._checkDelayState = function () {
  31922. var scene = this.getScene();
  31923. if (this._geometry) {
  31924. this._geometry.load(scene);
  31925. }
  31926. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31927. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31928. this._queueLoad(scene);
  31929. }
  31930. return this;
  31931. };
  31932. Mesh.prototype._queueLoad = function (scene) {
  31933. var _this = this;
  31934. scene._addPendingData(this);
  31935. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31936. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31937. if (data instanceof ArrayBuffer) {
  31938. _this._delayLoadingFunction(data, _this);
  31939. }
  31940. else {
  31941. _this._delayLoadingFunction(JSON.parse(data), _this);
  31942. }
  31943. _this.instances.forEach(function (instance) {
  31944. instance._syncSubMeshes();
  31945. });
  31946. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31947. scene._removePendingData(_this);
  31948. }, function () { }, scene.database, getBinaryData);
  31949. return this;
  31950. };
  31951. /**
  31952. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31953. */
  31954. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31955. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31956. return false;
  31957. }
  31958. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31959. return false;
  31960. }
  31961. this._checkDelayState();
  31962. return true;
  31963. };
  31964. /**
  31965. * Sets the mesh material by the material or multiMaterial `id` property.
  31966. * The material `id` is a string identifying the material or the multiMaterial.
  31967. * This method returns the Mesh.
  31968. */
  31969. Mesh.prototype.setMaterialByID = function (id) {
  31970. var materials = this.getScene().materials;
  31971. var index;
  31972. for (index = materials.length - 1; index > -1; index--) {
  31973. if (materials[index].id === id) {
  31974. this.material = materials[index];
  31975. return this;
  31976. }
  31977. }
  31978. // Multi
  31979. var multiMaterials = this.getScene().multiMaterials;
  31980. for (index = multiMaterials.length - 1; index > -1; index--) {
  31981. if (multiMaterials[index].id === id) {
  31982. this.material = multiMaterials[index];
  31983. return this;
  31984. }
  31985. }
  31986. return this;
  31987. };
  31988. /**
  31989. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31990. */
  31991. Mesh.prototype.getAnimatables = function () {
  31992. var results = new Array();
  31993. if (this.material) {
  31994. results.push(this.material);
  31995. }
  31996. if (this.skeleton) {
  31997. results.push(this.skeleton);
  31998. }
  31999. return results;
  32000. };
  32001. /**
  32002. * Modifies the mesh geometry according to the passed transformation matrix.
  32003. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32004. * The mesh normals are modified accordingly the same transformation.
  32005. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  32006. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32007. * Returns the Mesh.
  32008. */
  32009. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32010. // Position
  32011. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32012. return this;
  32013. }
  32014. var submeshes = this.subMeshes.splice(0);
  32015. this._resetPointsArrayCache();
  32016. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32017. var temp = new Array();
  32018. var index;
  32019. for (index = 0; index < data.length; index += 3) {
  32020. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32021. }
  32022. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32023. // Normals
  32024. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32025. return this;
  32026. }
  32027. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32028. temp = [];
  32029. for (index = 0; index < data.length; index += 3) {
  32030. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32031. }
  32032. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32033. // flip faces?
  32034. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32035. this.flipFaces();
  32036. }
  32037. // Restore submeshes
  32038. this.releaseSubMeshes();
  32039. this.subMeshes = submeshes;
  32040. return this;
  32041. };
  32042. /**
  32043. * Modifies the mesh geometry according to its own current World Matrix.
  32044. * The mesh World Matrix is then reset.
  32045. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32046. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32047. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32048. * Returns the Mesh.
  32049. */
  32050. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32051. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32052. this.scaling.copyFromFloats(1, 1, 1);
  32053. this.position.copyFromFloats(0, 0, 0);
  32054. this.rotation.copyFromFloats(0, 0, 0);
  32055. //only if quaternion is already set
  32056. if (this.rotationQuaternion) {
  32057. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32058. }
  32059. this._worldMatrix = BABYLON.Matrix.Identity();
  32060. return this;
  32061. };
  32062. Object.defineProperty(Mesh.prototype, "_positions", {
  32063. // Cache
  32064. get: function () {
  32065. if (this._geometry) {
  32066. return this._geometry._positions;
  32067. }
  32068. return null;
  32069. },
  32070. enumerable: true,
  32071. configurable: true
  32072. });
  32073. Mesh.prototype._resetPointsArrayCache = function () {
  32074. if (this._geometry) {
  32075. this._geometry._resetPointsArrayCache();
  32076. }
  32077. return this;
  32078. };
  32079. Mesh.prototype._generatePointsArray = function () {
  32080. if (this._geometry) {
  32081. return this._geometry._generatePointsArray();
  32082. }
  32083. return false;
  32084. };
  32085. /**
  32086. * Returns a new Mesh object generated from the current mesh properties.
  32087. * This method must not get confused with createInstance().
  32088. * The parameter `name` is a string, the name given to the new mesh.
  32089. * The optional parameter `newParent` can be any Node object (default `null`).
  32090. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32091. * 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.
  32092. */
  32093. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32094. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32095. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32096. };
  32097. /**
  32098. * Releases resources associated with this mesh.
  32099. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32100. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32101. */
  32102. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32103. var _this = this;
  32104. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32105. this.morphTargetManager = null;
  32106. if (this._geometry) {
  32107. this._geometry.releaseForMesh(this, true);
  32108. }
  32109. // Sources
  32110. var meshes = this.getScene().meshes;
  32111. meshes.forEach(function (abstractMesh) {
  32112. var mesh = abstractMesh;
  32113. if (mesh._source && mesh._source === _this) {
  32114. mesh._source = null;
  32115. }
  32116. });
  32117. this._source = null;
  32118. // Instances
  32119. if (this._instancesBuffer) {
  32120. this._instancesBuffer.dispose();
  32121. this._instancesBuffer = null;
  32122. }
  32123. while (this.instances.length) {
  32124. this.instances[0].dispose();
  32125. }
  32126. // Effect layers.
  32127. var effectLayers = this.getScene().effectLayers;
  32128. for (var i = 0; i < effectLayers.length; i++) {
  32129. var effectLayer = effectLayers[i];
  32130. if (effectLayer) {
  32131. effectLayer._disposeMesh(this);
  32132. }
  32133. }
  32134. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32135. };
  32136. /**
  32137. * Modifies the mesh geometry according to a displacement map.
  32138. * 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.
  32139. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32140. * This method returns nothing.
  32141. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32142. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32143. * 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.
  32144. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32145. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32146. *
  32147. * Returns the Mesh.
  32148. */
  32149. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32150. var _this = this;
  32151. var scene = this.getScene();
  32152. var onload = function (img) {
  32153. // Getting height map data
  32154. var canvas = document.createElement("canvas");
  32155. var context = canvas.getContext("2d");
  32156. var heightMapWidth = img.width;
  32157. var heightMapHeight = img.height;
  32158. canvas.width = heightMapWidth;
  32159. canvas.height = heightMapHeight;
  32160. context.drawImage(img, 0, 0);
  32161. // Create VertexData from map data
  32162. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32163. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32164. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32165. //execute success callback, if set
  32166. if (onSuccess) {
  32167. onSuccess(_this);
  32168. }
  32169. };
  32170. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32171. return this;
  32172. };
  32173. /**
  32174. * Modifies the mesh geometry according to a displacementMap buffer.
  32175. * 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.
  32176. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32177. * This method returns nothing.
  32178. * 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.
  32179. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32180. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32181. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32182. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32183. *
  32184. * Returns the Mesh.
  32185. */
  32186. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32187. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32188. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32189. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32190. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32191. return this;
  32192. }
  32193. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32194. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32195. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32196. var position = BABYLON.Vector3.Zero();
  32197. var normal = BABYLON.Vector3.Zero();
  32198. var uv = BABYLON.Vector2.Zero();
  32199. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32200. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32201. for (var index = 0; index < positions.length; index += 3) {
  32202. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32203. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32204. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32205. // Compute height
  32206. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32207. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32208. var pos = (u + v * heightMapWidth) * 4;
  32209. var r = buffer[pos] / 255.0;
  32210. var g = buffer[pos + 1] / 255.0;
  32211. var b = buffer[pos + 2] / 255.0;
  32212. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32213. normal.normalize();
  32214. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32215. position = position.add(normal);
  32216. position.toArray(positions, index);
  32217. }
  32218. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32219. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32220. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32221. return this;
  32222. };
  32223. /**
  32224. * Modify the mesh to get a flat shading rendering.
  32225. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32226. * This method returns the Mesh.
  32227. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32228. */
  32229. Mesh.prototype.convertToFlatShadedMesh = function () {
  32230. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32231. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32232. var kinds = this.getVerticesDataKinds();
  32233. var vbs = {};
  32234. var data = {};
  32235. var newdata = {};
  32236. var updatableNormals = false;
  32237. var kindIndex;
  32238. var kind;
  32239. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32240. kind = kinds[kindIndex];
  32241. var vertexBuffer = this.getVertexBuffer(kind);
  32242. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32243. updatableNormals = vertexBuffer.isUpdatable();
  32244. kinds.splice(kindIndex, 1);
  32245. kindIndex--;
  32246. continue;
  32247. }
  32248. vbs[kind] = vertexBuffer;
  32249. data[kind] = vbs[kind].getData();
  32250. newdata[kind] = [];
  32251. }
  32252. // Save previous submeshes
  32253. var previousSubmeshes = this.subMeshes.slice(0);
  32254. var indices = this.getIndices();
  32255. var totalIndices = this.getTotalIndices();
  32256. // Generating unique vertices per face
  32257. var index;
  32258. for (index = 0; index < totalIndices; index++) {
  32259. var vertexIndex = indices[index];
  32260. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32261. kind = kinds[kindIndex];
  32262. var stride = vbs[kind].getStrideSize();
  32263. for (var offset = 0; offset < stride; offset++) {
  32264. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32265. }
  32266. }
  32267. }
  32268. // Updating faces & normal
  32269. var normals = [];
  32270. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32271. for (index = 0; index < totalIndices; index += 3) {
  32272. indices[index] = index;
  32273. indices[index + 1] = index + 1;
  32274. indices[index + 2] = index + 2;
  32275. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32276. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32277. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32278. var p1p2 = p1.subtract(p2);
  32279. var p3p2 = p3.subtract(p2);
  32280. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32281. // Store same normals for every vertex
  32282. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32283. normals.push(normal.x);
  32284. normals.push(normal.y);
  32285. normals.push(normal.z);
  32286. }
  32287. }
  32288. this.setIndices(indices);
  32289. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32290. // Updating vertex buffers
  32291. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32292. kind = kinds[kindIndex];
  32293. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32294. }
  32295. // Updating submeshes
  32296. this.releaseSubMeshes();
  32297. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32298. var previousOne = previousSubmeshes[submeshIndex];
  32299. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32300. }
  32301. this.synchronizeInstances();
  32302. return this;
  32303. };
  32304. /**
  32305. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32306. * In other words, more vertices, no more indices and a single bigger VBO.
  32307. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32308. * Returns the Mesh.
  32309. */
  32310. Mesh.prototype.convertToUnIndexedMesh = function () {
  32311. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32312. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32313. var kinds = this.getVerticesDataKinds();
  32314. var vbs = {};
  32315. var data = {};
  32316. var newdata = {};
  32317. var kindIndex;
  32318. var kind;
  32319. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32320. kind = kinds[kindIndex];
  32321. var vertexBuffer = this.getVertexBuffer(kind);
  32322. vbs[kind] = vertexBuffer;
  32323. data[kind] = vbs[kind].getData();
  32324. newdata[kind] = [];
  32325. }
  32326. // Save previous submeshes
  32327. var previousSubmeshes = this.subMeshes.slice(0);
  32328. var indices = this.getIndices();
  32329. var totalIndices = this.getTotalIndices();
  32330. // Generating unique vertices per face
  32331. var index;
  32332. for (index = 0; index < totalIndices; index++) {
  32333. var vertexIndex = indices[index];
  32334. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32335. kind = kinds[kindIndex];
  32336. var stride = vbs[kind].getStrideSize();
  32337. for (var offset = 0; offset < stride; offset++) {
  32338. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32339. }
  32340. }
  32341. }
  32342. // Updating indices
  32343. for (index = 0; index < totalIndices; index += 3) {
  32344. indices[index] = index;
  32345. indices[index + 1] = index + 1;
  32346. indices[index + 2] = index + 2;
  32347. }
  32348. this.setIndices(indices);
  32349. // Updating vertex buffers
  32350. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32351. kind = kinds[kindIndex];
  32352. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32353. }
  32354. // Updating submeshes
  32355. this.releaseSubMeshes();
  32356. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32357. var previousOne = previousSubmeshes[submeshIndex];
  32358. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32359. }
  32360. this._unIndexed = true;
  32361. this.synchronizeInstances();
  32362. return this;
  32363. };
  32364. /**
  32365. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32366. * This method returns the Mesh.
  32367. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32368. */
  32369. Mesh.prototype.flipFaces = function (flipNormals) {
  32370. if (flipNormals === void 0) { flipNormals = false; }
  32371. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32372. var i;
  32373. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32374. for (i = 0; i < vertex_data.normals.length; i++) {
  32375. vertex_data.normals[i] *= -1;
  32376. }
  32377. }
  32378. if (vertex_data.indices) {
  32379. var temp;
  32380. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32381. // reassign indices
  32382. temp = vertex_data.indices[i + 1];
  32383. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32384. vertex_data.indices[i + 2] = temp;
  32385. }
  32386. }
  32387. vertex_data.applyToMesh(this);
  32388. return this;
  32389. };
  32390. // Instances
  32391. /**
  32392. * Creates a new InstancedMesh object from the mesh model.
  32393. * An instance shares the same properties and the same material than its model.
  32394. * Only these properties of each instance can then be set individually :
  32395. * - position
  32396. * - rotation
  32397. * - rotationQuaternion
  32398. * - setPivotMatrix
  32399. * - scaling
  32400. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32401. * Warning : this method is not supported for Line mesh and LineSystem
  32402. */
  32403. Mesh.prototype.createInstance = function (name) {
  32404. return new BABYLON.InstancedMesh(name, this);
  32405. };
  32406. /**
  32407. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32408. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32409. * This method returns the Mesh.
  32410. */
  32411. Mesh.prototype.synchronizeInstances = function () {
  32412. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32413. var instance = this.instances[instanceIndex];
  32414. instance._syncSubMeshes();
  32415. }
  32416. return this;
  32417. };
  32418. /**
  32419. * Simplify the mesh according to the given array of settings.
  32420. * Function will return immediately and will simplify async. It returns the Mesh.
  32421. * @param settings a collection of simplification settings.
  32422. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32423. * @param type the type of simplification to run.
  32424. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32425. */
  32426. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32427. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32428. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32429. this.getScene().simplificationQueue.addTask({
  32430. settings: settings,
  32431. parallelProcessing: parallelProcessing,
  32432. mesh: this,
  32433. simplificationType: simplificationType,
  32434. successCallback: successCallback
  32435. });
  32436. return this;
  32437. };
  32438. /**
  32439. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32440. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32441. * This should be used together with the simplification to avoid disappearing triangles.
  32442. * Returns the Mesh.
  32443. * @param successCallback an optional success callback to be called after the optimization finished.
  32444. */
  32445. Mesh.prototype.optimizeIndices = function (successCallback) {
  32446. var _this = this;
  32447. var indices = this.getIndices();
  32448. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32449. if (!positions || !indices) {
  32450. return this;
  32451. }
  32452. var vectorPositions = new Array();
  32453. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32454. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32455. }
  32456. var dupes = new Array();
  32457. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32458. var realPos = vectorPositions.length - 1 - iteration;
  32459. var testedPosition = vectorPositions[realPos];
  32460. for (var j = 0; j < realPos; ++j) {
  32461. var againstPosition = vectorPositions[j];
  32462. if (testedPosition.equals(againstPosition)) {
  32463. dupes[realPos] = j;
  32464. break;
  32465. }
  32466. }
  32467. }, function () {
  32468. for (var i = 0; i < indices.length; ++i) {
  32469. indices[i] = dupes[indices[i]] || indices[i];
  32470. }
  32471. //indices are now reordered
  32472. var originalSubMeshes = _this.subMeshes.slice(0);
  32473. _this.setIndices(indices);
  32474. _this.subMeshes = originalSubMeshes;
  32475. if (successCallback) {
  32476. successCallback(_this);
  32477. }
  32478. });
  32479. return this;
  32480. };
  32481. Mesh.prototype.serialize = function (serializationObject) {
  32482. serializationObject.name = this.name;
  32483. serializationObject.id = this.id;
  32484. serializationObject.type = this.getClassName();
  32485. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32486. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32487. }
  32488. serializationObject.position = this.position.asArray();
  32489. if (this.rotationQuaternion) {
  32490. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32491. }
  32492. else if (this.rotation) {
  32493. serializationObject.rotation = this.rotation.asArray();
  32494. }
  32495. serializationObject.scaling = this.scaling.asArray();
  32496. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32497. serializationObject.isEnabled = this.isEnabled(false);
  32498. serializationObject.isVisible = this.isVisible;
  32499. serializationObject.infiniteDistance = this.infiniteDistance;
  32500. serializationObject.pickable = this.isPickable;
  32501. serializationObject.receiveShadows = this.receiveShadows;
  32502. serializationObject.billboardMode = this.billboardMode;
  32503. serializationObject.visibility = this.visibility;
  32504. serializationObject.checkCollisions = this.checkCollisions;
  32505. serializationObject.isBlocker = this.isBlocker;
  32506. // Parent
  32507. if (this.parent) {
  32508. serializationObject.parentId = this.parent.id;
  32509. }
  32510. // Geometry
  32511. serializationObject.isUnIndexed = this.isUnIndexed;
  32512. var geometry = this._geometry;
  32513. if (geometry) {
  32514. var geometryId = geometry.id;
  32515. serializationObject.geometryId = geometryId;
  32516. // SubMeshes
  32517. serializationObject.subMeshes = [];
  32518. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32519. var subMesh = this.subMeshes[subIndex];
  32520. serializationObject.subMeshes.push({
  32521. materialIndex: subMesh.materialIndex,
  32522. verticesStart: subMesh.verticesStart,
  32523. verticesCount: subMesh.verticesCount,
  32524. indexStart: subMesh.indexStart,
  32525. indexCount: subMesh.indexCount
  32526. });
  32527. }
  32528. }
  32529. // Material
  32530. if (this.material) {
  32531. serializationObject.materialId = this.material.id;
  32532. }
  32533. else {
  32534. this.material = null;
  32535. }
  32536. // Morph targets
  32537. if (this.morphTargetManager) {
  32538. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32539. }
  32540. // Skeleton
  32541. if (this.skeleton) {
  32542. serializationObject.skeletonId = this.skeleton.id;
  32543. }
  32544. // Physics
  32545. //TODO implement correct serialization for physics impostors.
  32546. var impostor = this.getPhysicsImpostor();
  32547. if (impostor) {
  32548. serializationObject.physicsMass = impostor.getParam("mass");
  32549. serializationObject.physicsFriction = impostor.getParam("friction");
  32550. serializationObject.physicsRestitution = impostor.getParam("mass");
  32551. serializationObject.physicsImpostor = impostor.type;
  32552. }
  32553. // Metadata
  32554. if (this.metadata) {
  32555. serializationObject.metadata = this.metadata;
  32556. }
  32557. // Instances
  32558. serializationObject.instances = [];
  32559. for (var index = 0; index < this.instances.length; index++) {
  32560. var instance = this.instances[index];
  32561. var serializationInstance = {
  32562. name: instance.name,
  32563. id: instance.id,
  32564. position: instance.position.asArray(),
  32565. scaling: instance.scaling.asArray()
  32566. };
  32567. if (instance.rotationQuaternion) {
  32568. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32569. }
  32570. else if (instance.rotation) {
  32571. serializationInstance.rotation = instance.rotation.asArray();
  32572. }
  32573. serializationObject.instances.push(serializationInstance);
  32574. // Animations
  32575. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32576. serializationInstance.ranges = instance.serializeAnimationRanges();
  32577. }
  32578. //
  32579. // Animations
  32580. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32581. serializationObject.ranges = this.serializeAnimationRanges();
  32582. // Layer mask
  32583. serializationObject.layerMask = this.layerMask;
  32584. // Alpha
  32585. serializationObject.alphaIndex = this.alphaIndex;
  32586. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32587. // Overlay
  32588. serializationObject.overlayAlpha = this.overlayAlpha;
  32589. serializationObject.overlayColor = this.overlayColor.asArray();
  32590. serializationObject.renderOverlay = this.renderOverlay;
  32591. // Fog
  32592. serializationObject.applyFog = this.applyFog;
  32593. // Action Manager
  32594. if (this.actionManager) {
  32595. serializationObject.actions = this.actionManager.serialize(this.name);
  32596. }
  32597. };
  32598. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32599. if (!this.geometry) {
  32600. return;
  32601. }
  32602. this._markSubMeshesAsAttributesDirty();
  32603. var morphTargetManager = this._morphTargetManager;
  32604. if (morphTargetManager && morphTargetManager.vertexCount) {
  32605. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32606. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32607. this.morphTargetManager = null;
  32608. return;
  32609. }
  32610. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32611. var morphTarget = morphTargetManager.getActiveTarget(index);
  32612. var positions = morphTarget.getPositions();
  32613. if (!positions) {
  32614. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32615. return;
  32616. }
  32617. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32618. var normals = morphTarget.getNormals();
  32619. if (normals) {
  32620. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32621. }
  32622. var tangents = morphTarget.getTangents();
  32623. if (tangents) {
  32624. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32625. }
  32626. }
  32627. }
  32628. else {
  32629. var index = 0;
  32630. // Positions
  32631. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32632. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32633. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32634. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32635. }
  32636. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32637. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32638. }
  32639. index++;
  32640. }
  32641. }
  32642. };
  32643. // Statics
  32644. /**
  32645. * Returns a new Mesh object parsed from the source provided.
  32646. * The parameter `parsedMesh` is the source.
  32647. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32648. */
  32649. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32650. var mesh;
  32651. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32652. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32653. }
  32654. else {
  32655. mesh = new Mesh(parsedMesh.name, scene);
  32656. }
  32657. mesh.id = parsedMesh.id;
  32658. if (BABYLON.Tags) {
  32659. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32660. }
  32661. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32662. if (parsedMesh.metadata !== undefined) {
  32663. mesh.metadata = parsedMesh.metadata;
  32664. }
  32665. if (parsedMesh.rotationQuaternion) {
  32666. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32667. }
  32668. else if (parsedMesh.rotation) {
  32669. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32670. }
  32671. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32672. if (parsedMesh.localMatrix) {
  32673. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32674. }
  32675. else if (parsedMesh.pivotMatrix) {
  32676. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32677. }
  32678. mesh.setEnabled(parsedMesh.isEnabled);
  32679. mesh.isVisible = parsedMesh.isVisible;
  32680. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32681. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32682. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32683. if (parsedMesh.applyFog !== undefined) {
  32684. mesh.applyFog = parsedMesh.applyFog;
  32685. }
  32686. if (parsedMesh.pickable !== undefined) {
  32687. mesh.isPickable = parsedMesh.pickable;
  32688. }
  32689. if (parsedMesh.alphaIndex !== undefined) {
  32690. mesh.alphaIndex = parsedMesh.alphaIndex;
  32691. }
  32692. mesh.receiveShadows = parsedMesh.receiveShadows;
  32693. mesh.billboardMode = parsedMesh.billboardMode;
  32694. if (parsedMesh.visibility !== undefined) {
  32695. mesh.visibility = parsedMesh.visibility;
  32696. }
  32697. mesh.checkCollisions = parsedMesh.checkCollisions;
  32698. if (parsedMesh.isBlocker !== undefined) {
  32699. mesh.isBlocker = parsedMesh.isBlocker;
  32700. }
  32701. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32702. // freezeWorldMatrix
  32703. if (parsedMesh.freezeWorldMatrix) {
  32704. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32705. }
  32706. // Parent
  32707. if (parsedMesh.parentId) {
  32708. mesh._waitingParentId = parsedMesh.parentId;
  32709. }
  32710. // Actions
  32711. if (parsedMesh.actions !== undefined) {
  32712. mesh._waitingActions = parsedMesh.actions;
  32713. }
  32714. // Overlay
  32715. if (parsedMesh.overlayAlpha !== undefined) {
  32716. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32717. }
  32718. if (parsedMesh.overlayColor !== undefined) {
  32719. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32720. }
  32721. if (parsedMesh.renderOverlay !== undefined) {
  32722. mesh.renderOverlay = parsedMesh.renderOverlay;
  32723. }
  32724. // Geometry
  32725. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32726. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32727. if (parsedMesh.delayLoadingFile) {
  32728. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32729. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32730. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32731. if (parsedMesh._binaryInfo) {
  32732. mesh._binaryInfo = parsedMesh._binaryInfo;
  32733. }
  32734. mesh._delayInfo = [];
  32735. if (parsedMesh.hasUVs) {
  32736. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32737. }
  32738. if (parsedMesh.hasUVs2) {
  32739. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32740. }
  32741. if (parsedMesh.hasUVs3) {
  32742. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32743. }
  32744. if (parsedMesh.hasUVs4) {
  32745. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32746. }
  32747. if (parsedMesh.hasUVs5) {
  32748. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32749. }
  32750. if (parsedMesh.hasUVs6) {
  32751. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32752. }
  32753. if (parsedMesh.hasColors) {
  32754. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32755. }
  32756. if (parsedMesh.hasMatricesIndices) {
  32757. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32758. }
  32759. if (parsedMesh.hasMatricesWeights) {
  32760. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32761. }
  32762. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32763. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32764. mesh._checkDelayState();
  32765. }
  32766. }
  32767. else {
  32768. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32769. }
  32770. // Material
  32771. if (parsedMesh.materialId) {
  32772. mesh.setMaterialByID(parsedMesh.materialId);
  32773. }
  32774. else {
  32775. mesh.material = null;
  32776. }
  32777. // Morph targets
  32778. if (parsedMesh.morphTargetManagerId > -1) {
  32779. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32780. }
  32781. // Skeleton
  32782. if (parsedMesh.skeletonId > -1) {
  32783. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32784. if (parsedMesh.numBoneInfluencers) {
  32785. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32786. }
  32787. }
  32788. // Animations
  32789. if (parsedMesh.animations) {
  32790. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32791. var parsedAnimation = parsedMesh.animations[animationIndex];
  32792. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32793. }
  32794. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32795. }
  32796. if (parsedMesh.autoAnimate) {
  32797. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32798. }
  32799. // Layer Mask
  32800. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32801. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32802. }
  32803. else {
  32804. mesh.layerMask = 0x0FFFFFFF;
  32805. }
  32806. // Physics
  32807. if (parsedMesh.physicsImpostor) {
  32808. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32809. mass: parsedMesh.physicsMass,
  32810. friction: parsedMesh.physicsFriction,
  32811. restitution: parsedMesh.physicsRestitution
  32812. }, scene);
  32813. }
  32814. // Instances
  32815. if (parsedMesh.instances) {
  32816. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32817. var parsedInstance = parsedMesh.instances[index];
  32818. var instance = mesh.createInstance(parsedInstance.name);
  32819. if (parsedInstance.id) {
  32820. instance.id = parsedInstance.id;
  32821. }
  32822. if (BABYLON.Tags) {
  32823. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32824. }
  32825. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32826. if (parsedInstance.parentId) {
  32827. instance._waitingParentId = parsedInstance.parentId;
  32828. }
  32829. if (parsedInstance.rotationQuaternion) {
  32830. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32831. }
  32832. else if (parsedInstance.rotation) {
  32833. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32834. }
  32835. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32836. instance.checkCollisions = mesh.checkCollisions;
  32837. if (parsedMesh.animations) {
  32838. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32839. parsedAnimation = parsedMesh.animations[animationIndex];
  32840. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32841. }
  32842. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32843. }
  32844. }
  32845. }
  32846. return mesh;
  32847. };
  32848. /**
  32849. * Creates a ribbon mesh.
  32850. * Please consider using the same method from the MeshBuilder class instead.
  32851. * 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.
  32852. *
  32853. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32854. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32855. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32856. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32857. * 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.
  32858. * 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.
  32859. * 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
  32860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32861. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32863. */
  32864. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32865. if (closeArray === void 0) { closeArray = false; }
  32866. if (updatable === void 0) { updatable = false; }
  32867. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32868. pathArray: pathArray,
  32869. closeArray: closeArray,
  32870. closePath: closePath,
  32871. offset: offset,
  32872. updatable: updatable,
  32873. sideOrientation: sideOrientation,
  32874. instance: instance
  32875. }, scene);
  32876. };
  32877. /**
  32878. * Creates a plane polygonal mesh. By default, this is a disc.
  32879. * Please consider using the same method from the MeshBuilder class instead.
  32880. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32881. * 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.
  32882. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32883. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32885. */
  32886. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32887. if (scene === void 0) { scene = null; }
  32888. var options = {
  32889. radius: radius,
  32890. tessellation: tessellation,
  32891. sideOrientation: sideOrientation,
  32892. updatable: updatable
  32893. };
  32894. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32895. };
  32896. /**
  32897. * Creates a box mesh.
  32898. * Please consider using the same method from the MeshBuilder class instead.
  32899. * The parameter `size` sets the size (float) of each box side (default 1).
  32900. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32901. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32903. */
  32904. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32905. if (scene === void 0) { scene = null; }
  32906. var options = {
  32907. size: size,
  32908. sideOrientation: sideOrientation,
  32909. updatable: updatable
  32910. };
  32911. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32912. };
  32913. /**
  32914. * Creates a sphere mesh.
  32915. * Please consider using the same method from the MeshBuilder class instead.
  32916. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32917. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32918. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32919. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32921. */
  32922. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32923. var options = {
  32924. segments: segments,
  32925. diameterX: diameter,
  32926. diameterY: diameter,
  32927. diameterZ: diameter,
  32928. sideOrientation: sideOrientation,
  32929. updatable: updatable
  32930. };
  32931. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32932. };
  32933. /**
  32934. * Creates a cylinder or a cone mesh.
  32935. * Please consider using the same method from the MeshBuilder class instead.
  32936. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32937. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32938. * 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.
  32939. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32940. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32944. */
  32945. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32946. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32947. if (scene !== undefined) {
  32948. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32949. updatable = scene;
  32950. }
  32951. scene = subdivisions;
  32952. subdivisions = 1;
  32953. }
  32954. var options = {
  32955. height: height,
  32956. diameterTop: diameterTop,
  32957. diameterBottom: diameterBottom,
  32958. tessellation: tessellation,
  32959. subdivisions: subdivisions,
  32960. sideOrientation: sideOrientation,
  32961. updatable: updatable
  32962. };
  32963. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32964. };
  32965. // Torus (Code from SharpDX.org)
  32966. /**
  32967. * Creates a torus mesh.
  32968. * Please consider using the same method from the MeshBuilder class instead.
  32969. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32970. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32971. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32973. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32975. */
  32976. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32977. var options = {
  32978. diameter: diameter,
  32979. thickness: thickness,
  32980. tessellation: tessellation,
  32981. sideOrientation: sideOrientation,
  32982. updatable: updatable
  32983. };
  32984. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32985. };
  32986. /**
  32987. * Creates a torus knot mesh.
  32988. * Please consider using the same method from the MeshBuilder class instead.
  32989. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32990. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32991. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32992. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32996. */
  32997. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32998. var options = {
  32999. radius: radius,
  33000. tube: tube,
  33001. radialSegments: radialSegments,
  33002. tubularSegments: tubularSegments,
  33003. p: p,
  33004. q: q,
  33005. sideOrientation: sideOrientation,
  33006. updatable: updatable
  33007. };
  33008. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33009. };
  33010. /**
  33011. * Creates a line mesh.
  33012. * Please consider using the same method from the MeshBuilder class instead.
  33013. * 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.
  33014. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33015. * The parameter `points` is an array successive Vector3.
  33016. * 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
  33017. * When updating an instance, remember that only point positions can change, not the number of points.
  33018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33019. */
  33020. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33021. if (scene === void 0) { scene = null; }
  33022. if (updatable === void 0) { updatable = false; }
  33023. if (instance === void 0) { instance = null; }
  33024. var options = {
  33025. points: points,
  33026. updatable: updatable,
  33027. instance: instance
  33028. };
  33029. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33030. };
  33031. /**
  33032. * Creates a dashed line mesh.
  33033. * Please consider using the same method from the MeshBuilder class instead.
  33034. * 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.
  33035. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33036. * The parameter `points` is an array successive Vector3.
  33037. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33038. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33039. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33040. * 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
  33041. * When updating an instance, remember that only point positions can change, not the number of points.
  33042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33043. */
  33044. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33045. if (scene === void 0) { scene = null; }
  33046. var options = {
  33047. points: points,
  33048. dashSize: dashSize,
  33049. gapSize: gapSize,
  33050. dashNb: dashNb,
  33051. updatable: updatable,
  33052. instance: instance
  33053. };
  33054. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33055. };
  33056. /**
  33057. * Creates a polygon mesh.
  33058. * Please consider using the same method from the MeshBuilder class instead.
  33059. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33060. * 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.
  33061. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33063. * Remember you can only change the shape positions, not their number when updating a polygon.
  33064. */
  33065. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33066. var options = {
  33067. shape: shape,
  33068. holes: holes,
  33069. updatable: updatable,
  33070. sideOrientation: sideOrientation
  33071. };
  33072. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33073. };
  33074. /**
  33075. * Creates an extruded polygon mesh, with depth in the Y direction.
  33076. * Please consider using the same method from the MeshBuilder class instead.
  33077. */
  33078. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33079. var options = {
  33080. shape: shape,
  33081. holes: holes,
  33082. depth: depth,
  33083. updatable: updatable,
  33084. sideOrientation: sideOrientation
  33085. };
  33086. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33087. };
  33088. /**
  33089. * Creates an extruded shape mesh.
  33090. * 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.
  33091. * Please consider using the same method from the MeshBuilder class instead.
  33092. *
  33093. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33094. * 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
  33095. * extruded along the Z axis.
  33096. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33097. * 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.
  33098. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33099. * 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
  33100. * 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
  33101. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33102. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33103. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33105. */
  33106. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33107. if (scene === void 0) { scene = null; }
  33108. var options = {
  33109. shape: shape,
  33110. path: path,
  33111. scale: scale,
  33112. rotation: rotation,
  33113. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33114. sideOrientation: sideOrientation,
  33115. instance: instance,
  33116. updatable: updatable
  33117. };
  33118. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33119. };
  33120. /**
  33121. * Creates an custom extruded shape mesh.
  33122. * 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.
  33123. * Please consider using the same method from the MeshBuilder class instead.
  33124. *
  33125. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33126. * 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
  33127. * extruded along the Z axis.
  33128. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33129. * 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
  33130. * and the distance of this point from the begining of the path :
  33131. * ```javascript
  33132. * var rotationFunction = function(i, distance) {
  33133. * // do things
  33134. * return rotationValue; }
  33135. * ```
  33136. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33137. * 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
  33138. * and the distance of this point from the begining of the path :
  33139. * ```javascript
  33140. * var scaleFunction = function(i, distance) {
  33141. * // do things
  33142. * return scaleValue;}
  33143. * ```
  33144. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33145. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33146. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33147. * 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
  33148. * 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
  33149. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33150. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33151. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33153. */
  33154. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33155. var options = {
  33156. shape: shape,
  33157. path: path,
  33158. scaleFunction: scaleFunction,
  33159. rotationFunction: rotationFunction,
  33160. ribbonCloseArray: ribbonCloseArray,
  33161. ribbonClosePath: ribbonClosePath,
  33162. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33163. sideOrientation: sideOrientation,
  33164. instance: instance,
  33165. updatable: updatable
  33166. };
  33167. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33168. };
  33169. /**
  33170. * Creates lathe mesh.
  33171. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33172. * Please consider using the same method from the MeshBuilder class instead.
  33173. * 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
  33174. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33175. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33176. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33177. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33178. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33179. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33180. */
  33181. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33182. var options = {
  33183. shape: shape,
  33184. radius: radius,
  33185. tessellation: tessellation,
  33186. sideOrientation: sideOrientation,
  33187. updatable: updatable
  33188. };
  33189. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33190. };
  33191. /**
  33192. * Creates a plane mesh.
  33193. * Please consider using the same method from the MeshBuilder class instead.
  33194. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33196. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33198. */
  33199. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33200. var options = {
  33201. size: size,
  33202. width: size,
  33203. height: size,
  33204. sideOrientation: sideOrientation,
  33205. updatable: updatable
  33206. };
  33207. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33208. };
  33209. /**
  33210. * Creates a ground mesh.
  33211. * Please consider using the same method from the MeshBuilder class instead.
  33212. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33213. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33215. */
  33216. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33217. var options = {
  33218. width: width,
  33219. height: height,
  33220. subdivisions: subdivisions,
  33221. updatable: updatable
  33222. };
  33223. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33224. };
  33225. /**
  33226. * Creates a tiled ground mesh.
  33227. * Please consider using the same method from the MeshBuilder class instead.
  33228. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33229. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33230. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33231. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33232. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33233. * numbers of subdivisions on the ground width and height of each tile.
  33234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33235. */
  33236. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33237. var options = {
  33238. xmin: xmin,
  33239. zmin: zmin,
  33240. xmax: xmax,
  33241. zmax: zmax,
  33242. subdivisions: subdivisions,
  33243. precision: precision,
  33244. updatable: updatable
  33245. };
  33246. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33247. };
  33248. /**
  33249. * Creates a ground mesh from a height map.
  33250. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33251. * Please consider using the same method from the MeshBuilder class instead.
  33252. * The parameter `url` sets the URL of the height map image resource.
  33253. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33254. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33255. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33256. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33257. * 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).
  33258. * This function is passed the newly built mesh :
  33259. * ```javascript
  33260. * function(mesh) { // do things
  33261. * return; }
  33262. * ```
  33263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33264. */
  33265. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33266. var options = {
  33267. width: width,
  33268. height: height,
  33269. subdivisions: subdivisions,
  33270. minHeight: minHeight,
  33271. maxHeight: maxHeight,
  33272. updatable: updatable,
  33273. onReady: onReady
  33274. };
  33275. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33276. };
  33277. /**
  33278. * Creates a tube mesh.
  33279. * 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.
  33280. * Please consider using the same method from the MeshBuilder class instead.
  33281. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33282. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33283. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33284. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33285. * 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.
  33286. * It must return a radius value (positive float) :
  33287. * ```javascript
  33288. * var radiusFunction = function(i, distance) {
  33289. * // do things
  33290. * return radius; }
  33291. * ```
  33292. * 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
  33293. * 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
  33294. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33295. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33296. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33297. */
  33298. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33299. var options = {
  33300. path: path,
  33301. radius: radius,
  33302. tessellation: tessellation,
  33303. radiusFunction: radiusFunction,
  33304. arc: 1,
  33305. cap: cap,
  33306. updatable: updatable,
  33307. sideOrientation: sideOrientation,
  33308. instance: instance
  33309. };
  33310. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33311. };
  33312. /**
  33313. * Creates a polyhedron mesh.
  33314. * Please consider using the same method from the MeshBuilder class instead.
  33315. * 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
  33316. * to choose the wanted type.
  33317. * The parameter `size` (positive float, default 1) sets the polygon size.
  33318. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33319. * 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`.
  33320. * 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
  33321. * 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)`).
  33322. * 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
  33323. * 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.
  33324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33327. */
  33328. Mesh.CreatePolyhedron = function (name, options, scene) {
  33329. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33330. };
  33331. /**
  33332. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33333. * Please consider using the same method from the MeshBuilder class instead.
  33334. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33335. * 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`).
  33336. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33337. * 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.
  33338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33339. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33341. */
  33342. Mesh.CreateIcoSphere = function (name, options, scene) {
  33343. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33344. };
  33345. /**
  33346. * Creates a decal mesh.
  33347. * Please consider using the same method from the MeshBuilder class instead.
  33348. * 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.
  33349. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33350. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33351. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33352. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33353. */
  33354. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33355. var options = {
  33356. position: position,
  33357. normal: normal,
  33358. size: size,
  33359. angle: angle
  33360. };
  33361. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33362. };
  33363. // Skeletons
  33364. /**
  33365. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33366. */
  33367. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33368. if (!this._sourcePositions) {
  33369. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33370. if (!source) {
  33371. return this._sourcePositions;
  33372. }
  33373. this._sourcePositions = new Float32Array(source);
  33374. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33375. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33376. }
  33377. }
  33378. return this._sourcePositions;
  33379. };
  33380. /**
  33381. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33382. */
  33383. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33384. if (!this._sourceNormals) {
  33385. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33386. if (!source) {
  33387. return this._sourceNormals;
  33388. }
  33389. this._sourceNormals = new Float32Array(source);
  33390. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33391. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33392. }
  33393. }
  33394. return this._sourceNormals;
  33395. };
  33396. /**
  33397. * Updates the vertex buffer by applying transformation from the bones.
  33398. * Returns the Mesh.
  33399. *
  33400. * @param {skeleton} skeleton to apply
  33401. */
  33402. Mesh.prototype.applySkeleton = function (skeleton) {
  33403. if (!this.geometry) {
  33404. return this;
  33405. }
  33406. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33407. return this;
  33408. }
  33409. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33410. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33411. return this;
  33412. }
  33413. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33414. return this;
  33415. }
  33416. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33417. return this;
  33418. }
  33419. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33420. return this;
  33421. }
  33422. if (!this._sourcePositions) {
  33423. var submeshes = this.subMeshes.slice();
  33424. this.setPositionsForCPUSkinning();
  33425. this.subMeshes = submeshes;
  33426. }
  33427. if (!this._sourceNormals) {
  33428. this.setNormalsForCPUSkinning();
  33429. }
  33430. // positionsData checks for not being Float32Array will only pass at most once
  33431. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33432. if (!positionsData) {
  33433. return this;
  33434. }
  33435. if (!(positionsData instanceof Float32Array)) {
  33436. positionsData = new Float32Array(positionsData);
  33437. }
  33438. // normalsData checks for not being Float32Array will only pass at most once
  33439. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33440. if (!normalsData) {
  33441. return this;
  33442. }
  33443. if (!(normalsData instanceof Float32Array)) {
  33444. normalsData = new Float32Array(normalsData);
  33445. }
  33446. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33447. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33448. if (!matricesWeightsData || !matricesIndicesData) {
  33449. return this;
  33450. }
  33451. var needExtras = this.numBoneInfluencers > 4;
  33452. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33453. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33454. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33455. var tempVector3 = BABYLON.Vector3.Zero();
  33456. var finalMatrix = new BABYLON.Matrix();
  33457. var tempMatrix = new BABYLON.Matrix();
  33458. var matWeightIdx = 0;
  33459. var inf;
  33460. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33461. var weight;
  33462. for (inf = 0; inf < 4; inf++) {
  33463. weight = matricesWeightsData[matWeightIdx + inf];
  33464. if (weight > 0) {
  33465. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33466. finalMatrix.addToSelf(tempMatrix);
  33467. }
  33468. else
  33469. break;
  33470. }
  33471. if (needExtras) {
  33472. for (inf = 0; inf < 4; inf++) {
  33473. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33474. if (weight > 0) {
  33475. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33476. finalMatrix.addToSelf(tempMatrix);
  33477. }
  33478. else
  33479. break;
  33480. }
  33481. }
  33482. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33483. tempVector3.toArray(positionsData, index);
  33484. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33485. tempVector3.toArray(normalsData, index);
  33486. finalMatrix.reset();
  33487. }
  33488. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33489. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33490. return this;
  33491. };
  33492. // Tools
  33493. /**
  33494. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33495. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33496. */
  33497. Mesh.MinMax = function (meshes) {
  33498. var minVector = null;
  33499. var maxVector = null;
  33500. meshes.forEach(function (mesh, index, array) {
  33501. var boundingInfo = mesh.getBoundingInfo();
  33502. var boundingBox = boundingInfo.boundingBox;
  33503. if (!minVector || !maxVector) {
  33504. minVector = boundingBox.minimumWorld;
  33505. maxVector = boundingBox.maximumWorld;
  33506. }
  33507. else {
  33508. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33509. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33510. }
  33511. });
  33512. if (!minVector || !maxVector) {
  33513. return {
  33514. min: BABYLON.Vector3.Zero(),
  33515. max: BABYLON.Vector3.Zero()
  33516. };
  33517. }
  33518. return {
  33519. min: minVector,
  33520. max: maxVector
  33521. };
  33522. };
  33523. /**
  33524. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33525. */
  33526. Mesh.Center = function (meshesOrMinMaxVector) {
  33527. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33528. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33529. };
  33530. /**
  33531. * Merge the array of meshes into a single mesh for performance reasons.
  33532. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33533. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33534. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33535. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33536. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33537. */
  33538. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33539. if (disposeSource === void 0) { disposeSource = true; }
  33540. var index;
  33541. if (!allow32BitsIndices) {
  33542. var totalVertices = 0;
  33543. // Counting vertices
  33544. for (index = 0; index < meshes.length; index++) {
  33545. if (meshes[index]) {
  33546. totalVertices += meshes[index].getTotalVertices();
  33547. if (totalVertices > 65536) {
  33548. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33549. return null;
  33550. }
  33551. }
  33552. }
  33553. }
  33554. // Merge
  33555. var vertexData = null;
  33556. var otherVertexData;
  33557. var indiceArray = new Array();
  33558. var source = null;
  33559. for (index = 0; index < meshes.length; index++) {
  33560. if (meshes[index]) {
  33561. meshes[index].computeWorldMatrix(true);
  33562. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33563. otherVertexData.transform(meshes[index].getWorldMatrix());
  33564. if (vertexData) {
  33565. vertexData.merge(otherVertexData);
  33566. }
  33567. else {
  33568. vertexData = otherVertexData;
  33569. source = meshes[index];
  33570. }
  33571. if (subdivideWithSubMeshes) {
  33572. indiceArray.push(meshes[index].getTotalIndices());
  33573. }
  33574. }
  33575. }
  33576. source = source;
  33577. if (!meshSubclass) {
  33578. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33579. }
  33580. vertexData.applyToMesh(meshSubclass);
  33581. // Setting properties
  33582. meshSubclass.material = source.material;
  33583. meshSubclass.checkCollisions = source.checkCollisions;
  33584. // Cleaning
  33585. if (disposeSource) {
  33586. for (index = 0; index < meshes.length; index++) {
  33587. if (meshes[index]) {
  33588. meshes[index].dispose();
  33589. }
  33590. }
  33591. }
  33592. // Subdivide
  33593. if (subdivideWithSubMeshes) {
  33594. //-- Suppresions du submesh global
  33595. meshSubclass.releaseSubMeshes();
  33596. index = 0;
  33597. var offset = 0;
  33598. //-- aplique la subdivision en fonction du tableau d'indices
  33599. while (index < indiceArray.length) {
  33600. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33601. offset += indiceArray[index];
  33602. index++;
  33603. }
  33604. }
  33605. return meshSubclass;
  33606. };
  33607. // Consts
  33608. Mesh._FRONTSIDE = 0;
  33609. Mesh._BACKSIDE = 1;
  33610. Mesh._DOUBLESIDE = 2;
  33611. Mesh._DEFAULTSIDE = 0;
  33612. Mesh._NO_CAP = 0;
  33613. Mesh._CAP_START = 1;
  33614. Mesh._CAP_END = 2;
  33615. Mesh._CAP_ALL = 3;
  33616. return Mesh;
  33617. }(BABYLON.AbstractMesh));
  33618. BABYLON.Mesh = Mesh;
  33619. })(BABYLON || (BABYLON = {}));
  33620. //# sourceMappingURL=babylon.mesh.js.map
  33621. var BABYLON;
  33622. (function (BABYLON) {
  33623. var BaseSubMesh = /** @class */ (function () {
  33624. function BaseSubMesh() {
  33625. }
  33626. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33627. get: function () {
  33628. return this._materialEffect;
  33629. },
  33630. enumerable: true,
  33631. configurable: true
  33632. });
  33633. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33634. if (defines === void 0) { defines = null; }
  33635. if (this._materialEffect === effect) {
  33636. if (!effect) {
  33637. this._materialDefines = null;
  33638. }
  33639. return;
  33640. }
  33641. this._materialDefines = defines;
  33642. this._materialEffect = effect;
  33643. };
  33644. return BaseSubMesh;
  33645. }());
  33646. BABYLON.BaseSubMesh = BaseSubMesh;
  33647. var SubMesh = /** @class */ (function (_super) {
  33648. __extends(SubMesh, _super);
  33649. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33650. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33651. var _this = _super.call(this) || this;
  33652. _this.materialIndex = materialIndex;
  33653. _this.verticesStart = verticesStart;
  33654. _this.verticesCount = verticesCount;
  33655. _this.indexStart = indexStart;
  33656. _this.indexCount = indexCount;
  33657. _this._renderId = 0;
  33658. _this._mesh = mesh;
  33659. _this._renderingMesh = renderingMesh || mesh;
  33660. mesh.subMeshes.push(_this);
  33661. _this._trianglePlanes = [];
  33662. _this._id = mesh.subMeshes.length - 1;
  33663. if (createBoundingBox) {
  33664. _this.refreshBoundingInfo();
  33665. mesh.computeWorldMatrix(true);
  33666. }
  33667. return _this;
  33668. }
  33669. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33670. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33671. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33672. };
  33673. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33674. get: function () {
  33675. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33676. },
  33677. enumerable: true,
  33678. configurable: true
  33679. });
  33680. /**
  33681. * Returns the submesh BoudingInfo object.
  33682. */
  33683. SubMesh.prototype.getBoundingInfo = function () {
  33684. if (this.IsGlobal) {
  33685. return this._mesh.getBoundingInfo();
  33686. }
  33687. return this._boundingInfo;
  33688. };
  33689. /**
  33690. * Sets the submesh BoundingInfo.
  33691. * Return the SubMesh.
  33692. */
  33693. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33694. this._boundingInfo = boundingInfo;
  33695. return this;
  33696. };
  33697. /**
  33698. * Returns the mesh of the current submesh.
  33699. */
  33700. SubMesh.prototype.getMesh = function () {
  33701. return this._mesh;
  33702. };
  33703. /**
  33704. * Returns the rendering mesh of the submesh.
  33705. */
  33706. SubMesh.prototype.getRenderingMesh = function () {
  33707. return this._renderingMesh;
  33708. };
  33709. /**
  33710. * Returns the submesh material.
  33711. */
  33712. SubMesh.prototype.getMaterial = function () {
  33713. var rootMaterial = this._renderingMesh.material;
  33714. if (rootMaterial === null || rootMaterial === undefined) {
  33715. return this._mesh.getScene().defaultMaterial;
  33716. }
  33717. else if (rootMaterial.getSubMaterial) {
  33718. var multiMaterial = rootMaterial;
  33719. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33720. if (this._currentMaterial !== effectiveMaterial) {
  33721. this._currentMaterial = effectiveMaterial;
  33722. this._materialDefines = null;
  33723. }
  33724. return effectiveMaterial;
  33725. }
  33726. return rootMaterial;
  33727. };
  33728. // Methods
  33729. /**
  33730. * Sets a new updated BoundingInfo object to the submesh.
  33731. * Returns the SubMesh.
  33732. */
  33733. SubMesh.prototype.refreshBoundingInfo = function () {
  33734. this._lastColliderWorldVertices = null;
  33735. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33736. return this;
  33737. }
  33738. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33739. if (!data) {
  33740. this._boundingInfo = this._mesh.getBoundingInfo();
  33741. return this;
  33742. }
  33743. var indices = this._renderingMesh.getIndices();
  33744. var extend;
  33745. //is this the only submesh?
  33746. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33747. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33748. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33749. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33750. }
  33751. else {
  33752. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33753. }
  33754. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33755. return this;
  33756. };
  33757. SubMesh.prototype._checkCollision = function (collider) {
  33758. var boundingInfo = this.getBoundingInfo();
  33759. return boundingInfo._checkCollision(collider);
  33760. };
  33761. /**
  33762. * Updates the submesh BoundingInfo.
  33763. * Returns the Submesh.
  33764. */
  33765. SubMesh.prototype.updateBoundingInfo = function (world) {
  33766. var boundingInfo = this.getBoundingInfo();
  33767. if (!boundingInfo) {
  33768. this.refreshBoundingInfo();
  33769. boundingInfo = this.getBoundingInfo();
  33770. }
  33771. boundingInfo.update(world);
  33772. return this;
  33773. };
  33774. /**
  33775. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33776. * Boolean returned.
  33777. */
  33778. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33779. var boundingInfo = this.getBoundingInfo();
  33780. if (!boundingInfo) {
  33781. return false;
  33782. }
  33783. return boundingInfo.isInFrustum(frustumPlanes);
  33784. };
  33785. /**
  33786. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33787. * Boolean returned.
  33788. */
  33789. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33790. var boundingInfo = this.getBoundingInfo();
  33791. if (!boundingInfo) {
  33792. return false;
  33793. }
  33794. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33795. };
  33796. /**
  33797. * Renders the submesh.
  33798. * Returns it.
  33799. */
  33800. SubMesh.prototype.render = function (enableAlphaMode) {
  33801. this._renderingMesh.render(this, enableAlphaMode);
  33802. return this;
  33803. };
  33804. /**
  33805. * Returns a new Index Buffer.
  33806. * Type returned : WebGLBuffer.
  33807. */
  33808. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33809. if (!this._linesIndexBuffer) {
  33810. var linesIndices = [];
  33811. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33812. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33813. }
  33814. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33815. this.linesIndexCount = linesIndices.length;
  33816. }
  33817. return this._linesIndexBuffer;
  33818. };
  33819. /**
  33820. * True is the passed Ray intersects the submesh bounding box.
  33821. * Boolean returned.
  33822. */
  33823. SubMesh.prototype.canIntersects = function (ray) {
  33824. var boundingInfo = this.getBoundingInfo();
  33825. if (!boundingInfo) {
  33826. return false;
  33827. }
  33828. return ray.intersectsBox(boundingInfo.boundingBox);
  33829. };
  33830. /**
  33831. * Returns an object IntersectionInfo.
  33832. */
  33833. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33834. var intersectInfo = null;
  33835. var material = this.getMaterial();
  33836. if (!material) {
  33837. return null;
  33838. }
  33839. switch (material.fillMode) {
  33840. case BABYLON.Material.PointListDrawMode:
  33841. case BABYLON.Material.LineListDrawMode:
  33842. case BABYLON.Material.LineLoopDrawMode:
  33843. case BABYLON.Material.LineStripDrawMode:
  33844. case BABYLON.Material.TriangleFanDrawMode:
  33845. case BABYLON.Material.TriangleStripDrawMode:
  33846. return null;
  33847. }
  33848. // LineMesh first as it's also a Mesh...
  33849. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33850. var lineMesh = this._mesh;
  33851. // Line test
  33852. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33853. var p0 = positions[indices[index]];
  33854. var p1 = positions[indices[index + 1]];
  33855. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33856. if (length < 0) {
  33857. continue;
  33858. }
  33859. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33860. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33861. if (fastCheck) {
  33862. break;
  33863. }
  33864. }
  33865. }
  33866. }
  33867. else {
  33868. // Triangles test
  33869. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33870. var p0 = positions[indices[index]];
  33871. var p1 = positions[indices[index + 1]];
  33872. var p2 = positions[indices[index + 2]];
  33873. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33874. if (currentIntersectInfo) {
  33875. if (currentIntersectInfo.distance < 0) {
  33876. continue;
  33877. }
  33878. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33879. intersectInfo = currentIntersectInfo;
  33880. intersectInfo.faceId = index / 3;
  33881. if (fastCheck) {
  33882. break;
  33883. }
  33884. }
  33885. }
  33886. }
  33887. }
  33888. return intersectInfo;
  33889. };
  33890. SubMesh.prototype._rebuild = function () {
  33891. if (this._linesIndexBuffer) {
  33892. this._linesIndexBuffer = null;
  33893. }
  33894. };
  33895. // Clone
  33896. /**
  33897. * Creates a new Submesh from the passed Mesh.
  33898. */
  33899. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33900. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33901. if (!this.IsGlobal) {
  33902. var boundingInfo = this.getBoundingInfo();
  33903. if (!boundingInfo) {
  33904. return result;
  33905. }
  33906. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33907. }
  33908. return result;
  33909. };
  33910. // Dispose
  33911. /**
  33912. * Disposes the Submesh.
  33913. * Returns nothing.
  33914. */
  33915. SubMesh.prototype.dispose = function () {
  33916. if (this._linesIndexBuffer) {
  33917. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33918. this._linesIndexBuffer = null;
  33919. }
  33920. // Remove from mesh
  33921. var index = this._mesh.subMeshes.indexOf(this);
  33922. this._mesh.subMeshes.splice(index, 1);
  33923. };
  33924. // Statics
  33925. /**
  33926. * Creates a new Submesh from the passed parameters :
  33927. * - materialIndex (integer) : the index of the main mesh material.
  33928. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33929. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33930. * - mesh (Mesh) : the main mesh to create the submesh from.
  33931. * - renderingMesh (optional Mesh) : rendering mesh.
  33932. */
  33933. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33934. var minVertexIndex = Number.MAX_VALUE;
  33935. var maxVertexIndex = -Number.MAX_VALUE;
  33936. renderingMesh = (renderingMesh || mesh);
  33937. var indices = renderingMesh.getIndices();
  33938. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33939. var vertexIndex = indices[index];
  33940. if (vertexIndex < minVertexIndex)
  33941. minVertexIndex = vertexIndex;
  33942. if (vertexIndex > maxVertexIndex)
  33943. maxVertexIndex = vertexIndex;
  33944. }
  33945. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33946. };
  33947. return SubMesh;
  33948. }(BaseSubMesh));
  33949. BABYLON.SubMesh = SubMesh;
  33950. })(BABYLON || (BABYLON = {}));
  33951. //# sourceMappingURL=babylon.subMesh.js.map
  33952. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33953. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33954. s = arguments[i];
  33955. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33956. t[p] = s[p];
  33957. }
  33958. return t;
  33959. };
  33960. var BABYLON;
  33961. (function (BABYLON) {
  33962. /**
  33963. * Manages the defines for the Material
  33964. */
  33965. var MaterialDefines = /** @class */ (function () {
  33966. function MaterialDefines() {
  33967. this._isDirty = true;
  33968. /** @ignore */
  33969. this._areLightsDirty = true;
  33970. /** @ignore */
  33971. this._areAttributesDirty = true;
  33972. /** @ignore */
  33973. this._areTexturesDirty = true;
  33974. /** @ignore */
  33975. this._areFresnelDirty = true;
  33976. /** @ignore */
  33977. this._areMiscDirty = true;
  33978. /** @ignore */
  33979. this._areImageProcessingDirty = true;
  33980. /** @ignore */
  33981. this._normals = false;
  33982. /** @ignore */
  33983. this._uvs = false;
  33984. /** @ignore */
  33985. this._needNormals = false;
  33986. /** @ignore */
  33987. this._needUVs = false;
  33988. }
  33989. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33990. /**
  33991. * Specifies if the material needs to be re-calculated
  33992. */
  33993. get: function () {
  33994. return this._isDirty;
  33995. },
  33996. enumerable: true,
  33997. configurable: true
  33998. });
  33999. /**
  34000. * Marks the material to indicate that it has been re-calculated
  34001. */
  34002. MaterialDefines.prototype.markAsProcessed = function () {
  34003. this._isDirty = false;
  34004. this._areAttributesDirty = false;
  34005. this._areTexturesDirty = false;
  34006. this._areFresnelDirty = false;
  34007. this._areLightsDirty = false;
  34008. this._areMiscDirty = false;
  34009. this._areImageProcessingDirty = false;
  34010. };
  34011. /**
  34012. * Marks the material to indicate that it needs to be re-calculated
  34013. */
  34014. MaterialDefines.prototype.markAsUnprocessed = function () {
  34015. this._isDirty = true;
  34016. };
  34017. /**
  34018. * Marks the material to indicate all of its defines need to be re-calculated
  34019. */
  34020. MaterialDefines.prototype.markAllAsDirty = function () {
  34021. this._areTexturesDirty = true;
  34022. this._areAttributesDirty = true;
  34023. this._areLightsDirty = true;
  34024. this._areFresnelDirty = true;
  34025. this._areMiscDirty = true;
  34026. this._areImageProcessingDirty = true;
  34027. this._isDirty = true;
  34028. };
  34029. /**
  34030. * Marks the material to indicate that image processing needs to be re-calculated
  34031. */
  34032. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34033. this._areImageProcessingDirty = true;
  34034. this._isDirty = true;
  34035. };
  34036. /**
  34037. * Marks the material to indicate the lights need to be re-calculated
  34038. */
  34039. MaterialDefines.prototype.markAsLightDirty = function () {
  34040. this._areLightsDirty = true;
  34041. this._isDirty = true;
  34042. };
  34043. /**
  34044. * Marks the attribute state as changed
  34045. */
  34046. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34047. this._areAttributesDirty = true;
  34048. this._isDirty = true;
  34049. };
  34050. /**
  34051. * Marks the texture state as changed
  34052. */
  34053. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34054. this._areTexturesDirty = true;
  34055. this._isDirty = true;
  34056. };
  34057. /**
  34058. * Marks the fresnel state as changed
  34059. */
  34060. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34061. this._areFresnelDirty = true;
  34062. this._isDirty = true;
  34063. };
  34064. /**
  34065. * Marks the misc state as changed
  34066. */
  34067. MaterialDefines.prototype.markAsMiscDirty = function () {
  34068. this._areMiscDirty = true;
  34069. this._isDirty = true;
  34070. };
  34071. /**
  34072. * Rebuilds the material defines
  34073. */
  34074. MaterialDefines.prototype.rebuild = function () {
  34075. if (this._keys) {
  34076. delete this._keys;
  34077. }
  34078. this._keys = [];
  34079. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34080. var key = _a[_i];
  34081. if (key[0] === "_") {
  34082. continue;
  34083. }
  34084. this._keys.push(key);
  34085. }
  34086. };
  34087. /**
  34088. * Specifies if two material defines are equal
  34089. * @param other - A material define instance to compare to
  34090. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34091. */
  34092. MaterialDefines.prototype.isEqual = function (other) {
  34093. if (this._keys.length !== other._keys.length) {
  34094. return false;
  34095. }
  34096. for (var index = 0; index < this._keys.length; index++) {
  34097. var prop = this._keys[index];
  34098. if (this[prop] !== other[prop]) {
  34099. return false;
  34100. }
  34101. }
  34102. return true;
  34103. };
  34104. /**
  34105. * Clones this instance's defines to another instance
  34106. * @param other - material defines to clone values to
  34107. */
  34108. MaterialDefines.prototype.cloneTo = function (other) {
  34109. if (this._keys.length !== other._keys.length) {
  34110. other._keys = this._keys.slice(0);
  34111. }
  34112. for (var index = 0; index < this._keys.length; index++) {
  34113. var prop = this._keys[index];
  34114. other[prop] = this[prop];
  34115. }
  34116. };
  34117. /**
  34118. * Resets the material define values
  34119. */
  34120. MaterialDefines.prototype.reset = function () {
  34121. for (var index = 0; index < this._keys.length; index++) {
  34122. var prop = this._keys[index];
  34123. var type = typeof this[prop];
  34124. switch (type) {
  34125. case "number":
  34126. this[prop] = 0;
  34127. break;
  34128. case "string":
  34129. this[prop] = "";
  34130. break;
  34131. default:
  34132. this[prop] = false;
  34133. break;
  34134. }
  34135. }
  34136. };
  34137. /**
  34138. * Converts the material define values to a string
  34139. * @returns - String of material define information
  34140. */
  34141. MaterialDefines.prototype.toString = function () {
  34142. var result = "";
  34143. for (var index = 0; index < this._keys.length; index++) {
  34144. var prop = this._keys[index];
  34145. var value = this[prop];
  34146. var type = typeof value;
  34147. switch (type) {
  34148. case "number":
  34149. case "string":
  34150. result += "#define " + prop + " " + value + "\n";
  34151. break;
  34152. default:
  34153. if (value) {
  34154. result += "#define " + prop + "\n";
  34155. }
  34156. break;
  34157. }
  34158. }
  34159. return result;
  34160. };
  34161. return MaterialDefines;
  34162. }());
  34163. BABYLON.MaterialDefines = MaterialDefines;
  34164. /**
  34165. * Base class for the main features of a material in Babylon.js
  34166. */
  34167. var Material = /** @class */ (function () {
  34168. /**
  34169. * Creates a material instance
  34170. * @param name defines the name of the material
  34171. * @param scene defines the scene to reference
  34172. * @param doNotAdd specifies if the material should be added to the scene
  34173. */
  34174. function Material(name, scene, doNotAdd) {
  34175. /**
  34176. * Specifies if the ready state should be checked on each call
  34177. */
  34178. this.checkReadyOnEveryCall = false;
  34179. /**
  34180. * Specifies if the ready state should be checked once
  34181. */
  34182. this.checkReadyOnlyOnce = false;
  34183. /**
  34184. * The state of the material
  34185. */
  34186. this.state = "";
  34187. /**
  34188. * The alpha value of the material
  34189. */
  34190. this._alpha = 1.0;
  34191. /**
  34192. * Specifies if back face culling is enabled
  34193. */
  34194. this._backFaceCulling = true;
  34195. /**
  34196. * Specifies if the material should be serialized
  34197. */
  34198. this.doNotSerialize = false;
  34199. /**
  34200. * Specifies if the effect should be stored on sub meshes
  34201. */
  34202. this.storeEffectOnSubMeshes = false;
  34203. /**
  34204. * An event triggered when the material is disposed
  34205. */
  34206. this.onDisposeObservable = new BABYLON.Observable();
  34207. /**
  34208. * An event triggered when the material is bound
  34209. */
  34210. this.onBindObservable = new BABYLON.Observable();
  34211. /**
  34212. * An event triggered when the material is unbound
  34213. */
  34214. this.onUnBindObservable = new BABYLON.Observable();
  34215. /**
  34216. * Stores the value of the alpha mode
  34217. */
  34218. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34219. /**
  34220. * Stores the state of the need depth pre-pass value
  34221. */
  34222. this._needDepthPrePass = false;
  34223. /**
  34224. * Specifies if depth writing should be disabled
  34225. */
  34226. this.disableDepthWrite = false;
  34227. /**
  34228. * Specifies if depth writing should be forced
  34229. */
  34230. this.forceDepthWrite = false;
  34231. /**
  34232. * Specifies if there should be a separate pass for culling
  34233. */
  34234. this.separateCullingPass = false;
  34235. /**
  34236. * Stores the state specifing if fog should be enabled
  34237. */
  34238. this._fogEnabled = true;
  34239. /**
  34240. * Stores the size of points
  34241. */
  34242. this.pointSize = 1.0;
  34243. /**
  34244. * Stores the z offset value
  34245. */
  34246. this.zOffset = 0;
  34247. /**
  34248. * Specifies if the material was previously ready
  34249. */
  34250. this._wasPreviouslyReady = false;
  34251. /**
  34252. * Stores the fill mode state
  34253. */
  34254. this._fillMode = Material.TriangleFillMode;
  34255. this.name = name;
  34256. this.id = name || BABYLON.Tools.RandomId();
  34257. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34258. if (this._scene.useRightHandedSystem) {
  34259. this.sideOrientation = Material.ClockWiseSideOrientation;
  34260. }
  34261. else {
  34262. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34263. }
  34264. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34265. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34266. if (!doNotAdd) {
  34267. this._scene.materials.push(this);
  34268. }
  34269. }
  34270. Object.defineProperty(Material, "TriangleFillMode", {
  34271. /**
  34272. * Returns the triangle fill mode
  34273. */
  34274. get: function () {
  34275. return Material._TriangleFillMode;
  34276. },
  34277. enumerable: true,
  34278. configurable: true
  34279. });
  34280. Object.defineProperty(Material, "WireFrameFillMode", {
  34281. /**
  34282. * Returns the wireframe mode
  34283. */
  34284. get: function () {
  34285. return Material._WireFrameFillMode;
  34286. },
  34287. enumerable: true,
  34288. configurable: true
  34289. });
  34290. Object.defineProperty(Material, "PointFillMode", {
  34291. /**
  34292. * Returns the point fill mode
  34293. */
  34294. get: function () {
  34295. return Material._PointFillMode;
  34296. },
  34297. enumerable: true,
  34298. configurable: true
  34299. });
  34300. Object.defineProperty(Material, "PointListDrawMode", {
  34301. /**
  34302. * Returns the point list draw mode
  34303. */
  34304. get: function () {
  34305. return Material._PointListDrawMode;
  34306. },
  34307. enumerable: true,
  34308. configurable: true
  34309. });
  34310. Object.defineProperty(Material, "LineListDrawMode", {
  34311. /**
  34312. * Returns the line list draw mode
  34313. */
  34314. get: function () {
  34315. return Material._LineListDrawMode;
  34316. },
  34317. enumerable: true,
  34318. configurable: true
  34319. });
  34320. Object.defineProperty(Material, "LineLoopDrawMode", {
  34321. /**
  34322. * Returns the line loop draw mode
  34323. */
  34324. get: function () {
  34325. return Material._LineLoopDrawMode;
  34326. },
  34327. enumerable: true,
  34328. configurable: true
  34329. });
  34330. Object.defineProperty(Material, "LineStripDrawMode", {
  34331. /**
  34332. * Returns the line strip draw mode
  34333. */
  34334. get: function () {
  34335. return Material._LineStripDrawMode;
  34336. },
  34337. enumerable: true,
  34338. configurable: true
  34339. });
  34340. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34341. /**
  34342. * Returns the triangle strip draw mode
  34343. */
  34344. get: function () {
  34345. return Material._TriangleStripDrawMode;
  34346. },
  34347. enumerable: true,
  34348. configurable: true
  34349. });
  34350. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34351. /**
  34352. * Returns the triangle fan draw mode
  34353. */
  34354. get: function () {
  34355. return Material._TriangleFanDrawMode;
  34356. },
  34357. enumerable: true,
  34358. configurable: true
  34359. });
  34360. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34361. /**
  34362. * Returns the clock-wise side orientation
  34363. */
  34364. get: function () {
  34365. return Material._ClockWiseSideOrientation;
  34366. },
  34367. enumerable: true,
  34368. configurable: true
  34369. });
  34370. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34371. /**
  34372. * Returns the counter clock-wise side orientation
  34373. */
  34374. get: function () {
  34375. return Material._CounterClockWiseSideOrientation;
  34376. },
  34377. enumerable: true,
  34378. configurable: true
  34379. });
  34380. Object.defineProperty(Material, "TextureDirtyFlag", {
  34381. /**
  34382. * Returns the dirty texture flag value
  34383. */
  34384. get: function () {
  34385. return Material._TextureDirtyFlag;
  34386. },
  34387. enumerable: true,
  34388. configurable: true
  34389. });
  34390. Object.defineProperty(Material, "LightDirtyFlag", {
  34391. /**
  34392. * Returns the dirty light flag value
  34393. */
  34394. get: function () {
  34395. return Material._LightDirtyFlag;
  34396. },
  34397. enumerable: true,
  34398. configurable: true
  34399. });
  34400. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34401. /**
  34402. * Returns the dirty fresnel flag value
  34403. */
  34404. get: function () {
  34405. return Material._FresnelDirtyFlag;
  34406. },
  34407. enumerable: true,
  34408. configurable: true
  34409. });
  34410. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34411. /**
  34412. * Returns the dirty attributes flag value
  34413. */
  34414. get: function () {
  34415. return Material._AttributesDirtyFlag;
  34416. },
  34417. enumerable: true,
  34418. configurable: true
  34419. });
  34420. Object.defineProperty(Material, "MiscDirtyFlag", {
  34421. /**
  34422. * Returns the dirty misc flag value
  34423. */
  34424. get: function () {
  34425. return Material._MiscDirtyFlag;
  34426. },
  34427. enumerable: true,
  34428. configurable: true
  34429. });
  34430. Object.defineProperty(Material.prototype, "alpha", {
  34431. /**
  34432. * Gets the alpha value of the material
  34433. */
  34434. get: function () {
  34435. return this._alpha;
  34436. },
  34437. /**
  34438. * Sets the alpha value of the material
  34439. */
  34440. set: function (value) {
  34441. if (this._alpha === value) {
  34442. return;
  34443. }
  34444. this._alpha = value;
  34445. this.markAsDirty(Material.MiscDirtyFlag);
  34446. },
  34447. enumerable: true,
  34448. configurable: true
  34449. });
  34450. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34451. /**
  34452. * Gets the back-face culling state
  34453. */
  34454. get: function () {
  34455. return this._backFaceCulling;
  34456. },
  34457. /**
  34458. * Sets the back-face culling state
  34459. */
  34460. set: function (value) {
  34461. if (this._backFaceCulling === value) {
  34462. return;
  34463. }
  34464. this._backFaceCulling = value;
  34465. this.markAsDirty(Material.TextureDirtyFlag);
  34466. },
  34467. enumerable: true,
  34468. configurable: true
  34469. });
  34470. Object.defineProperty(Material.prototype, "onDispose", {
  34471. /**
  34472. * Called during a dispose event
  34473. */
  34474. set: function (callback) {
  34475. if (this._onDisposeObserver) {
  34476. this.onDisposeObservable.remove(this._onDisposeObserver);
  34477. }
  34478. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34479. },
  34480. enumerable: true,
  34481. configurable: true
  34482. });
  34483. Object.defineProperty(Material.prototype, "onBind", {
  34484. /**
  34485. * Called during a bind event
  34486. */
  34487. set: function (callback) {
  34488. if (this._onBindObserver) {
  34489. this.onBindObservable.remove(this._onBindObserver);
  34490. }
  34491. this._onBindObserver = this.onBindObservable.add(callback);
  34492. },
  34493. enumerable: true,
  34494. configurable: true
  34495. });
  34496. Object.defineProperty(Material.prototype, "alphaMode", {
  34497. /**
  34498. * Gets the value of the alpha mode
  34499. */
  34500. get: function () {
  34501. return this._alphaMode;
  34502. },
  34503. /**
  34504. * Sets the value of the alpha mode.
  34505. *
  34506. * | Value | Type | Description |
  34507. * | --- | --- | --- |
  34508. * | 0 | ALPHA_DISABLE | |
  34509. * | 1 | ALPHA_ADD | |
  34510. * | 2 | ALPHA_COMBINE | |
  34511. * | 3 | ALPHA_SUBTRACT | |
  34512. * | 4 | ALPHA_MULTIPLY | |
  34513. * | 5 | ALPHA_MAXIMIZED | |
  34514. * | 6 | ALPHA_ONEONE | |
  34515. * | 7 | ALPHA_PREMULTIPLIED | |
  34516. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34517. * | 9 | ALPHA_INTERPOLATE | |
  34518. * | 10 | ALPHA_SCREENMODE | |
  34519. *
  34520. */
  34521. set: function (value) {
  34522. if (this._alphaMode === value) {
  34523. return;
  34524. }
  34525. this._alphaMode = value;
  34526. this.markAsDirty(Material.TextureDirtyFlag);
  34527. },
  34528. enumerable: true,
  34529. configurable: true
  34530. });
  34531. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34532. /**
  34533. * Gets the depth pre-pass value
  34534. */
  34535. get: function () {
  34536. return this._needDepthPrePass;
  34537. },
  34538. /**
  34539. * Sets the need depth pre-pass value
  34540. */
  34541. set: function (value) {
  34542. if (this._needDepthPrePass === value) {
  34543. return;
  34544. }
  34545. this._needDepthPrePass = value;
  34546. if (this._needDepthPrePass) {
  34547. this.checkReadyOnEveryCall = true;
  34548. }
  34549. },
  34550. enumerable: true,
  34551. configurable: true
  34552. });
  34553. Object.defineProperty(Material.prototype, "fogEnabled", {
  34554. /**
  34555. * Gets the value of the fog enabled state
  34556. */
  34557. get: function () {
  34558. return this._fogEnabled;
  34559. },
  34560. /**
  34561. * Sets the state for enabling fog
  34562. */
  34563. set: function (value) {
  34564. if (this._fogEnabled === value) {
  34565. return;
  34566. }
  34567. this._fogEnabled = value;
  34568. this.markAsDirty(Material.MiscDirtyFlag);
  34569. },
  34570. enumerable: true,
  34571. configurable: true
  34572. });
  34573. Object.defineProperty(Material.prototype, "wireframe", {
  34574. /**
  34575. * Gets a value specifying if wireframe mode is enabled
  34576. */
  34577. get: function () {
  34578. switch (this._fillMode) {
  34579. case Material.WireFrameFillMode:
  34580. case Material.LineListDrawMode:
  34581. case Material.LineLoopDrawMode:
  34582. case Material.LineStripDrawMode:
  34583. return true;
  34584. }
  34585. return this._scene.forceWireframe;
  34586. },
  34587. /**
  34588. * Sets the state of wireframe mode
  34589. */
  34590. set: function (value) {
  34591. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34592. },
  34593. enumerable: true,
  34594. configurable: true
  34595. });
  34596. Object.defineProperty(Material.prototype, "pointsCloud", {
  34597. /**
  34598. * Gets the value specifying if point clouds are enabled
  34599. */
  34600. get: function () {
  34601. switch (this._fillMode) {
  34602. case Material.PointFillMode:
  34603. case Material.PointListDrawMode:
  34604. return true;
  34605. }
  34606. return this._scene.forcePointsCloud;
  34607. },
  34608. /**
  34609. * Sets the state of point cloud mode
  34610. */
  34611. set: function (value) {
  34612. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34613. },
  34614. enumerable: true,
  34615. configurable: true
  34616. });
  34617. Object.defineProperty(Material.prototype, "fillMode", {
  34618. /**
  34619. * Gets the material fill mode
  34620. */
  34621. get: function () {
  34622. return this._fillMode;
  34623. },
  34624. /**
  34625. * Sets the material fill mode
  34626. */
  34627. set: function (value) {
  34628. if (this._fillMode === value) {
  34629. return;
  34630. }
  34631. this._fillMode = value;
  34632. this.markAsDirty(Material.MiscDirtyFlag);
  34633. },
  34634. enumerable: true,
  34635. configurable: true
  34636. });
  34637. /**
  34638. * Returns a string representation of the current material
  34639. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34640. * @returns a string with material information
  34641. */
  34642. Material.prototype.toString = function (fullDetails) {
  34643. var ret = "Name: " + this.name;
  34644. if (fullDetails) {
  34645. }
  34646. return ret;
  34647. };
  34648. /**
  34649. * Gets the class name of the material
  34650. * @returns a string with the class name of the material
  34651. */
  34652. Material.prototype.getClassName = function () {
  34653. return "Material";
  34654. };
  34655. Object.defineProperty(Material.prototype, "isFrozen", {
  34656. /**
  34657. * Specifies if updates for the material been locked
  34658. */
  34659. get: function () {
  34660. return this.checkReadyOnlyOnce;
  34661. },
  34662. enumerable: true,
  34663. configurable: true
  34664. });
  34665. /**
  34666. * Locks updates for the material
  34667. */
  34668. Material.prototype.freeze = function () {
  34669. this.checkReadyOnlyOnce = true;
  34670. };
  34671. /**
  34672. * Unlocks updates for the material
  34673. */
  34674. Material.prototype.unfreeze = function () {
  34675. this.checkReadyOnlyOnce = false;
  34676. };
  34677. /**
  34678. * Specifies if the material is ready to be used
  34679. * @param mesh defines the mesh to check
  34680. * @param useInstances specifies if instances should be used
  34681. * @returns a boolean indicating if the material is ready to be used
  34682. */
  34683. Material.prototype.isReady = function (mesh, useInstances) {
  34684. return true;
  34685. };
  34686. /**
  34687. * Specifies that the submesh is ready to be used
  34688. * @param mesh defines the mesh to check
  34689. * @param subMesh defines which submesh to check
  34690. * @param useInstances specifies that instances should be used
  34691. * @returns a boolean indicating that the submesh is ready or not
  34692. */
  34693. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34694. return false;
  34695. };
  34696. /**
  34697. * Returns the material effect
  34698. * @returns the effect associated with the material
  34699. */
  34700. Material.prototype.getEffect = function () {
  34701. return this._effect;
  34702. };
  34703. /**
  34704. * Returns the current scene
  34705. * @returns a Scene
  34706. */
  34707. Material.prototype.getScene = function () {
  34708. return this._scene;
  34709. };
  34710. /**
  34711. * Specifies if the material will require alpha blending
  34712. * @returns a boolean specifying if alpha blending is needed
  34713. */
  34714. Material.prototype.needAlphaBlending = function () {
  34715. return (this.alpha < 1.0);
  34716. };
  34717. /**
  34718. * Specifies if the mesh will require alpha blending
  34719. * @param mesh defines the mesh to check
  34720. * @returns a boolean specifying if alpha blending is needed for the mesh
  34721. */
  34722. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34723. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34724. };
  34725. /**
  34726. * Specifies if this material should be rendered in alpha test mode
  34727. * @returns a boolean specifying if an alpha test is needed.
  34728. */
  34729. Material.prototype.needAlphaTesting = function () {
  34730. return false;
  34731. };
  34732. /**
  34733. * Gets the texture used for the alpha test
  34734. * @returns the texture to use for alpha testing
  34735. */
  34736. Material.prototype.getAlphaTestTexture = function () {
  34737. return null;
  34738. };
  34739. /**
  34740. * Marks the material to indicate that it needs to be re-calculated
  34741. */
  34742. Material.prototype.markDirty = function () {
  34743. this._wasPreviouslyReady = false;
  34744. };
  34745. /** @ignore */
  34746. Material.prototype._preBind = function (effect, overrideOrientation) {
  34747. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34748. var engine = this._scene.getEngine();
  34749. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34750. var reverse = orientation === Material.ClockWiseSideOrientation;
  34751. engine.enableEffect(effect ? effect : this._effect);
  34752. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34753. return reverse;
  34754. };
  34755. /**
  34756. * Binds the material to the mesh
  34757. * @param world defines the world transformation matrix
  34758. * @param mesh defines the mesh to bind the material to
  34759. */
  34760. Material.prototype.bind = function (world, mesh) {
  34761. };
  34762. /**
  34763. * Binds the submesh to the material
  34764. * @param world defines the world transformation matrix
  34765. * @param mesh defines the mesh containing the submesh
  34766. * @param subMesh defines the submesh to bind the material to
  34767. */
  34768. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34769. };
  34770. /**
  34771. * Binds the world matrix to the material
  34772. * @param world defines the world transformation matrix
  34773. */
  34774. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34775. };
  34776. /**
  34777. * Binds the scene's uniform buffer to the effect.
  34778. * @param effect defines the effect to bind to the scene uniform buffer
  34779. * @param sceneUbo defines the uniform buffer storing scene data
  34780. */
  34781. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34782. sceneUbo.bindToEffect(effect, "Scene");
  34783. };
  34784. /**
  34785. * Binds the view matrix to the effect
  34786. * @param effect defines the effect to bind the view matrix to
  34787. */
  34788. Material.prototype.bindView = function (effect) {
  34789. if (!this._useUBO) {
  34790. effect.setMatrix("view", this.getScene().getViewMatrix());
  34791. }
  34792. else {
  34793. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34794. }
  34795. };
  34796. /**
  34797. * Binds the view projection matrix to the effect
  34798. * @param effect defines the effect to bind the view projection matrix to
  34799. */
  34800. Material.prototype.bindViewProjection = function (effect) {
  34801. if (!this._useUBO) {
  34802. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34803. }
  34804. else {
  34805. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34806. }
  34807. };
  34808. /**
  34809. * Specifies if material alpha testing should be turned on for the mesh
  34810. * @param mesh defines the mesh to check
  34811. */
  34812. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34813. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34814. };
  34815. /**
  34816. * Processes to execute after binding the material to a mesh
  34817. * @param mesh defines the rendered mesh
  34818. */
  34819. Material.prototype._afterBind = function (mesh) {
  34820. this._scene._cachedMaterial = this;
  34821. if (mesh) {
  34822. this._scene._cachedVisibility = mesh.visibility;
  34823. }
  34824. else {
  34825. this._scene._cachedVisibility = 1;
  34826. }
  34827. if (mesh) {
  34828. this.onBindObservable.notifyObservers(mesh);
  34829. }
  34830. if (this.disableDepthWrite) {
  34831. var engine = this._scene.getEngine();
  34832. this._cachedDepthWriteState = engine.getDepthWrite();
  34833. engine.setDepthWrite(false);
  34834. }
  34835. };
  34836. /**
  34837. * Unbinds the material from the mesh
  34838. */
  34839. Material.prototype.unbind = function () {
  34840. this.onUnBindObservable.notifyObservers(this);
  34841. if (this.disableDepthWrite) {
  34842. var engine = this._scene.getEngine();
  34843. engine.setDepthWrite(this._cachedDepthWriteState);
  34844. }
  34845. };
  34846. /**
  34847. * Gets the active textures from the material
  34848. * @returns an array of textures
  34849. */
  34850. Material.prototype.getActiveTextures = function () {
  34851. return [];
  34852. };
  34853. /**
  34854. * Specifies if the material uses a texture
  34855. * @param texture defines the texture to check against the material
  34856. * @returns a boolean specifying if the material uses the texture
  34857. */
  34858. Material.prototype.hasTexture = function (texture) {
  34859. return false;
  34860. };
  34861. /**
  34862. * Makes a duplicate of the material, and gives it a new name
  34863. * @param name defines the new name for the duplicated material
  34864. * @returns the cloned material
  34865. */
  34866. Material.prototype.clone = function (name) {
  34867. return null;
  34868. };
  34869. /**
  34870. * Gets the meshes bound to the material
  34871. * @returns an array of meshes bound to the material
  34872. */
  34873. Material.prototype.getBindedMeshes = function () {
  34874. var result = new Array();
  34875. for (var index = 0; index < this._scene.meshes.length; index++) {
  34876. var mesh = this._scene.meshes[index];
  34877. if (mesh.material === this) {
  34878. result.push(mesh);
  34879. }
  34880. }
  34881. return result;
  34882. };
  34883. /**
  34884. * Force shader compilation
  34885. * @param mesh defines the mesh associated with this material
  34886. * @param onCompiled defines a function to execute once the material is compiled
  34887. * @param options defines the options to configure the compilation
  34888. */
  34889. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34890. var _this = this;
  34891. var localOptions = __assign({ clipPlane: false }, options);
  34892. var subMesh = new BABYLON.BaseSubMesh();
  34893. var scene = this.getScene();
  34894. var checkReady = function () {
  34895. if (!_this._scene || !_this._scene.getEngine()) {
  34896. return;
  34897. }
  34898. if (subMesh._materialDefines) {
  34899. subMesh._materialDefines._renderId = -1;
  34900. }
  34901. var clipPlaneState = scene.clipPlane;
  34902. if (localOptions.clipPlane) {
  34903. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34904. }
  34905. if (_this.storeEffectOnSubMeshes) {
  34906. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34907. if (onCompiled) {
  34908. onCompiled(_this);
  34909. }
  34910. }
  34911. else {
  34912. setTimeout(checkReady, 16);
  34913. }
  34914. }
  34915. else {
  34916. if (_this.isReady(mesh)) {
  34917. if (onCompiled) {
  34918. onCompiled(_this);
  34919. }
  34920. }
  34921. else {
  34922. setTimeout(checkReady, 16);
  34923. }
  34924. }
  34925. if (localOptions.clipPlane) {
  34926. scene.clipPlane = clipPlaneState;
  34927. }
  34928. };
  34929. checkReady();
  34930. };
  34931. /**
  34932. * Force shader compilation
  34933. * @param mesh defines the mesh that will use this material
  34934. * @param options defines additional options for compiling the shaders
  34935. * @returns a promise that resolves when the compilation completes
  34936. */
  34937. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34938. var _this = this;
  34939. return new Promise(function (resolve) {
  34940. _this.forceCompilation(mesh, function () {
  34941. resolve();
  34942. }, options);
  34943. });
  34944. };
  34945. /**
  34946. * Marks a define in the material to indicate that it needs to be re-computed
  34947. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34948. */
  34949. Material.prototype.markAsDirty = function (flag) {
  34950. if (flag & Material.TextureDirtyFlag) {
  34951. this._markAllSubMeshesAsTexturesDirty();
  34952. }
  34953. if (flag & Material.LightDirtyFlag) {
  34954. this._markAllSubMeshesAsLightsDirty();
  34955. }
  34956. if (flag & Material.FresnelDirtyFlag) {
  34957. this._markAllSubMeshesAsFresnelDirty();
  34958. }
  34959. if (flag & Material.AttributesDirtyFlag) {
  34960. this._markAllSubMeshesAsAttributesDirty();
  34961. }
  34962. if (flag & Material.MiscDirtyFlag) {
  34963. this._markAllSubMeshesAsMiscDirty();
  34964. }
  34965. this.getScene().resetCachedMaterial();
  34966. };
  34967. /**
  34968. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34969. * @param func defines a function which checks material defines against the submeshes
  34970. */
  34971. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34972. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34973. var mesh = _a[_i];
  34974. if (!mesh.subMeshes) {
  34975. continue;
  34976. }
  34977. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34978. var subMesh = _c[_b];
  34979. if (subMesh.getMaterial() !== this) {
  34980. continue;
  34981. }
  34982. if (!subMesh._materialDefines) {
  34983. continue;
  34984. }
  34985. func(subMesh._materialDefines);
  34986. }
  34987. }
  34988. };
  34989. /**
  34990. * Indicates that image processing needs to be re-calculated for all submeshes
  34991. */
  34992. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34993. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34994. };
  34995. /**
  34996. * Indicates that textures need to be re-calculated for all submeshes
  34997. */
  34998. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34999. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35000. };
  35001. /**
  35002. * Indicates that fresnel needs to be re-calculated for all submeshes
  35003. */
  35004. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35005. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35006. };
  35007. /**
  35008. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35009. */
  35010. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35011. this._markAllSubMeshesAsDirty(function (defines) {
  35012. defines.markAsFresnelDirty();
  35013. defines.markAsMiscDirty();
  35014. });
  35015. };
  35016. /**
  35017. * Indicates that lights need to be re-calculated for all submeshes
  35018. */
  35019. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35020. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35021. };
  35022. /**
  35023. * Indicates that attributes need to be re-calculated for all submeshes
  35024. */
  35025. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35026. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35027. };
  35028. /**
  35029. * Indicates that misc needs to be re-calculated for all submeshes
  35030. */
  35031. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35032. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35033. };
  35034. /**
  35035. * Indicates that textures and misc need to be re-calculated for all submeshes
  35036. */
  35037. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35038. this._markAllSubMeshesAsDirty(function (defines) {
  35039. defines.markAsTexturesDirty();
  35040. defines.markAsMiscDirty();
  35041. });
  35042. };
  35043. /**
  35044. * Disposes the material
  35045. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35046. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35047. */
  35048. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35049. // Animations
  35050. this.getScene().stopAnimation(this);
  35051. this.getScene().freeProcessedMaterials();
  35052. // Remove from scene
  35053. var index = this._scene.materials.indexOf(this);
  35054. if (index >= 0) {
  35055. this._scene.materials.splice(index, 1);
  35056. }
  35057. // Remove from meshes
  35058. for (index = 0; index < this._scene.meshes.length; index++) {
  35059. var mesh = this._scene.meshes[index];
  35060. if (mesh.material === this) {
  35061. mesh.material = null;
  35062. if (mesh.geometry) {
  35063. var geometry = (mesh.geometry);
  35064. if (this.storeEffectOnSubMeshes) {
  35065. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35066. var subMesh = _a[_i];
  35067. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35068. if (forceDisposeEffect && subMesh._materialEffect) {
  35069. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35070. }
  35071. }
  35072. }
  35073. else {
  35074. geometry._releaseVertexArrayObject(this._effect);
  35075. }
  35076. }
  35077. }
  35078. }
  35079. this._uniformBuffer.dispose();
  35080. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35081. if (forceDisposeEffect && this._effect) {
  35082. if (!this.storeEffectOnSubMeshes) {
  35083. this._scene.getEngine()._releaseEffect(this._effect);
  35084. }
  35085. this._effect = null;
  35086. }
  35087. // Callback
  35088. this.onDisposeObservable.notifyObservers(this);
  35089. this.onDisposeObservable.clear();
  35090. this.onBindObservable.clear();
  35091. this.onUnBindObservable.clear();
  35092. };
  35093. /**
  35094. * Serializes this material
  35095. * @returns the serialized material object
  35096. */
  35097. Material.prototype.serialize = function () {
  35098. return BABYLON.SerializationHelper.Serialize(this);
  35099. };
  35100. /**
  35101. * Creates a MultiMaterial from parsed MultiMaterial data.
  35102. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35103. * @param scene defines the hosting scene
  35104. * @returns a new MultiMaterial
  35105. */
  35106. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35107. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35108. multiMaterial.id = parsedMultiMaterial.id;
  35109. if (BABYLON.Tags) {
  35110. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35111. }
  35112. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35113. var subMatId = parsedMultiMaterial.materials[matIndex];
  35114. if (subMatId) {
  35115. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35116. }
  35117. else {
  35118. multiMaterial.subMaterials.push(null);
  35119. }
  35120. }
  35121. return multiMaterial;
  35122. };
  35123. /**
  35124. * Creates a material from parsed material data
  35125. * @param parsedMaterial defines parsed material data
  35126. * @param scene defines the hosting scene
  35127. * @param rootUrl defines the root URL to use to load textures
  35128. * @returns a new material
  35129. */
  35130. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35131. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35132. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35133. }
  35134. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35135. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35136. if (!BABYLON.LegacyPBRMaterial) {
  35137. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35138. return;
  35139. }
  35140. }
  35141. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35142. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35143. ;
  35144. };
  35145. // Triangle views
  35146. Material._TriangleFillMode = 0;
  35147. Material._WireFrameFillMode = 1;
  35148. Material._PointFillMode = 2;
  35149. // Draw modes
  35150. Material._PointListDrawMode = 3;
  35151. Material._LineListDrawMode = 4;
  35152. Material._LineLoopDrawMode = 5;
  35153. Material._LineStripDrawMode = 6;
  35154. Material._TriangleStripDrawMode = 7;
  35155. Material._TriangleFanDrawMode = 8;
  35156. /**
  35157. * Stores the clock-wise side orientation
  35158. */
  35159. Material._ClockWiseSideOrientation = 0;
  35160. /**
  35161. * Stores the counter clock-wise side orientation
  35162. */
  35163. Material._CounterClockWiseSideOrientation = 1;
  35164. /**
  35165. * The dirty texture flag value
  35166. */
  35167. Material._TextureDirtyFlag = 1;
  35168. /**
  35169. * The dirty light flag value
  35170. */
  35171. Material._LightDirtyFlag = 2;
  35172. /**
  35173. * The dirty fresnel flag value
  35174. */
  35175. Material._FresnelDirtyFlag = 4;
  35176. /**
  35177. * The dirty attribute flag value
  35178. */
  35179. Material._AttributesDirtyFlag = 8;
  35180. /**
  35181. * The dirty misc flag value
  35182. */
  35183. Material._MiscDirtyFlag = 16;
  35184. __decorate([
  35185. BABYLON.serialize()
  35186. ], Material.prototype, "id", void 0);
  35187. __decorate([
  35188. BABYLON.serialize()
  35189. ], Material.prototype, "name", void 0);
  35190. __decorate([
  35191. BABYLON.serialize()
  35192. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35193. __decorate([
  35194. BABYLON.serialize()
  35195. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35196. __decorate([
  35197. BABYLON.serialize()
  35198. ], Material.prototype, "state", void 0);
  35199. __decorate([
  35200. BABYLON.serialize("alpha")
  35201. ], Material.prototype, "_alpha", void 0);
  35202. __decorate([
  35203. BABYLON.serialize("backFaceCulling")
  35204. ], Material.prototype, "_backFaceCulling", void 0);
  35205. __decorate([
  35206. BABYLON.serialize()
  35207. ], Material.prototype, "sideOrientation", void 0);
  35208. __decorate([
  35209. BABYLON.serialize("alphaMode")
  35210. ], Material.prototype, "_alphaMode", void 0);
  35211. __decorate([
  35212. BABYLON.serialize()
  35213. ], Material.prototype, "_needDepthPrePass", void 0);
  35214. __decorate([
  35215. BABYLON.serialize()
  35216. ], Material.prototype, "disableDepthWrite", void 0);
  35217. __decorate([
  35218. BABYLON.serialize()
  35219. ], Material.prototype, "forceDepthWrite", void 0);
  35220. __decorate([
  35221. BABYLON.serialize()
  35222. ], Material.prototype, "separateCullingPass", void 0);
  35223. __decorate([
  35224. BABYLON.serialize("fogEnabled")
  35225. ], Material.prototype, "_fogEnabled", void 0);
  35226. __decorate([
  35227. BABYLON.serialize()
  35228. ], Material.prototype, "pointSize", void 0);
  35229. __decorate([
  35230. BABYLON.serialize()
  35231. ], Material.prototype, "zOffset", void 0);
  35232. __decorate([
  35233. BABYLON.serialize()
  35234. ], Material.prototype, "wireframe", null);
  35235. __decorate([
  35236. BABYLON.serialize()
  35237. ], Material.prototype, "pointsCloud", null);
  35238. __decorate([
  35239. BABYLON.serialize()
  35240. ], Material.prototype, "fillMode", null);
  35241. return Material;
  35242. }());
  35243. BABYLON.Material = Material;
  35244. })(BABYLON || (BABYLON = {}));
  35245. //# sourceMappingURL=babylon.material.js.map
  35246. var BABYLON;
  35247. (function (BABYLON) {
  35248. var UniformBuffer = /** @class */ (function () {
  35249. /**
  35250. * Uniform buffer objects.
  35251. *
  35252. * Handles blocks of uniform on the GPU.
  35253. *
  35254. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35255. *
  35256. * For more information, please refer to :
  35257. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35258. */
  35259. function UniformBuffer(engine, data, dynamic) {
  35260. this._engine = engine;
  35261. this._noUBO = !engine.supportsUniformBuffers;
  35262. this._dynamic = dynamic;
  35263. this._data = data || [];
  35264. this._uniformLocations = {};
  35265. this._uniformSizes = {};
  35266. this._uniformLocationPointer = 0;
  35267. this._needSync = false;
  35268. if (this._noUBO) {
  35269. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35270. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35271. this.updateFloat = this._updateFloatForEffect;
  35272. this.updateFloat2 = this._updateFloat2ForEffect;
  35273. this.updateFloat3 = this._updateFloat3ForEffect;
  35274. this.updateFloat4 = this._updateFloat4ForEffect;
  35275. this.updateMatrix = this._updateMatrixForEffect;
  35276. this.updateVector3 = this._updateVector3ForEffect;
  35277. this.updateVector4 = this._updateVector4ForEffect;
  35278. this.updateColor3 = this._updateColor3ForEffect;
  35279. this.updateColor4 = this._updateColor4ForEffect;
  35280. }
  35281. else {
  35282. this._engine._uniformBuffers.push(this);
  35283. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35284. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35285. this.updateFloat = this._updateFloatForUniform;
  35286. this.updateFloat2 = this._updateFloat2ForUniform;
  35287. this.updateFloat3 = this._updateFloat3ForUniform;
  35288. this.updateFloat4 = this._updateFloat4ForUniform;
  35289. this.updateMatrix = this._updateMatrixForUniform;
  35290. this.updateVector3 = this._updateVector3ForUniform;
  35291. this.updateVector4 = this._updateVector4ForUniform;
  35292. this.updateColor3 = this._updateColor3ForUniform;
  35293. this.updateColor4 = this._updateColor4ForUniform;
  35294. }
  35295. }
  35296. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35297. // Properties
  35298. /**
  35299. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35300. * or just falling back on setUniformXXX calls.
  35301. */
  35302. get: function () {
  35303. return !this._noUBO;
  35304. },
  35305. enumerable: true,
  35306. configurable: true
  35307. });
  35308. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35309. /**
  35310. * Indicates if the WebGL underlying uniform buffer is in sync
  35311. * with the javascript cache data.
  35312. */
  35313. get: function () {
  35314. return !this._needSync;
  35315. },
  35316. enumerable: true,
  35317. configurable: true
  35318. });
  35319. /**
  35320. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35321. * Also, a dynamic UniformBuffer will disable cache verification and always
  35322. * update the underlying WebGL uniform buffer to the GPU.
  35323. */
  35324. UniformBuffer.prototype.isDynamic = function () {
  35325. return this._dynamic !== undefined;
  35326. };
  35327. /**
  35328. * The data cache on JS side.
  35329. */
  35330. UniformBuffer.prototype.getData = function () {
  35331. return this._bufferData;
  35332. };
  35333. /**
  35334. * The underlying WebGL Uniform buffer.
  35335. */
  35336. UniformBuffer.prototype.getBuffer = function () {
  35337. return this._buffer;
  35338. };
  35339. /**
  35340. * std140 layout specifies how to align data within an UBO structure.
  35341. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35342. * for specs.
  35343. */
  35344. UniformBuffer.prototype._fillAlignment = function (size) {
  35345. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35346. // and 4x4 matrices
  35347. // TODO : change if other types are used
  35348. var alignment;
  35349. if (size <= 2) {
  35350. alignment = size;
  35351. }
  35352. else {
  35353. alignment = 4;
  35354. }
  35355. if ((this._uniformLocationPointer % alignment) !== 0) {
  35356. var oldPointer = this._uniformLocationPointer;
  35357. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35358. var diff = this._uniformLocationPointer - oldPointer;
  35359. for (var i = 0; i < diff; i++) {
  35360. this._data.push(0);
  35361. }
  35362. }
  35363. };
  35364. /**
  35365. * Adds an uniform in the buffer.
  35366. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35367. * for the layout to be correct !
  35368. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35369. * @param {number|number[]} size Data size, or data directly.
  35370. */
  35371. UniformBuffer.prototype.addUniform = function (name, size) {
  35372. if (this._noUBO) {
  35373. return;
  35374. }
  35375. if (this._uniformLocations[name] !== undefined) {
  35376. // Already existing uniform
  35377. return;
  35378. }
  35379. // This function must be called in the order of the shader layout !
  35380. // size can be the size of the uniform, or data directly
  35381. var data;
  35382. if (size instanceof Array) {
  35383. data = size;
  35384. size = data.length;
  35385. }
  35386. else {
  35387. size = size;
  35388. data = [];
  35389. // Fill with zeros
  35390. for (var i = 0; i < size; i++) {
  35391. data.push(0);
  35392. }
  35393. }
  35394. this._fillAlignment(size);
  35395. this._uniformSizes[name] = size;
  35396. this._uniformLocations[name] = this._uniformLocationPointer;
  35397. this._uniformLocationPointer += size;
  35398. for (var i = 0; i < size; i++) {
  35399. this._data.push(data[i]);
  35400. }
  35401. this._needSync = true;
  35402. };
  35403. /**
  35404. * Wrapper for addUniform.
  35405. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35406. * @param {Matrix} mat A 4x4 matrix.
  35407. */
  35408. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35409. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35410. };
  35411. /**
  35412. * Wrapper for addUniform.
  35413. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35414. * @param {number} x
  35415. * @param {number} y
  35416. */
  35417. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35418. var temp = [x, y];
  35419. this.addUniform(name, temp);
  35420. };
  35421. /**
  35422. * Wrapper for addUniform.
  35423. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35424. * @param {number} x
  35425. * @param {number} y
  35426. * @param {number} z
  35427. */
  35428. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35429. var temp = [x, y, z];
  35430. this.addUniform(name, temp);
  35431. };
  35432. /**
  35433. * Wrapper for addUniform.
  35434. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35435. * @param {Color3} color
  35436. */
  35437. UniformBuffer.prototype.addColor3 = function (name, color) {
  35438. var temp = new Array();
  35439. color.toArray(temp);
  35440. this.addUniform(name, temp);
  35441. };
  35442. /**
  35443. * Wrapper for addUniform.
  35444. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35445. * @param {Color3} color
  35446. * @param {number} alpha
  35447. */
  35448. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35449. var temp = new Array();
  35450. color.toArray(temp);
  35451. temp.push(alpha);
  35452. this.addUniform(name, temp);
  35453. };
  35454. /**
  35455. * Wrapper for addUniform.
  35456. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35457. * @param {Vector3} vector
  35458. */
  35459. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35460. var temp = new Array();
  35461. vector.toArray(temp);
  35462. this.addUniform(name, temp);
  35463. };
  35464. /**
  35465. * Wrapper for addUniform.
  35466. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35467. */
  35468. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35469. this.addUniform(name, 12);
  35470. };
  35471. /**
  35472. * Wrapper for addUniform.
  35473. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35474. */
  35475. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35476. this.addUniform(name, 8);
  35477. };
  35478. /**
  35479. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35480. */
  35481. UniformBuffer.prototype.create = function () {
  35482. if (this._noUBO) {
  35483. return;
  35484. }
  35485. if (this._buffer) {
  35486. return; // nothing to do
  35487. }
  35488. // See spec, alignment must be filled as a vec4
  35489. this._fillAlignment(4);
  35490. this._bufferData = new Float32Array(this._data);
  35491. this._rebuild();
  35492. this._needSync = true;
  35493. };
  35494. UniformBuffer.prototype._rebuild = function () {
  35495. if (this._noUBO) {
  35496. return;
  35497. }
  35498. if (this._dynamic) {
  35499. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35500. }
  35501. else {
  35502. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35503. }
  35504. };
  35505. /**
  35506. * Updates the WebGL Uniform Buffer on the GPU.
  35507. * If the `dynamic` flag is set to true, no cache comparison is done.
  35508. * Otherwise, the buffer will be updated only if the cache differs.
  35509. */
  35510. UniformBuffer.prototype.update = function () {
  35511. if (!this._buffer) {
  35512. this.create();
  35513. return;
  35514. }
  35515. if (!this._dynamic && !this._needSync) {
  35516. return;
  35517. }
  35518. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35519. this._needSync = false;
  35520. };
  35521. /**
  35522. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35523. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35524. * @param {number[]|Float32Array} data Flattened data
  35525. * @param {number} size Size of the data.
  35526. */
  35527. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35528. var location = this._uniformLocations[uniformName];
  35529. if (location === undefined) {
  35530. if (this._buffer) {
  35531. // Cannot add an uniform if the buffer is already created
  35532. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35533. return;
  35534. }
  35535. this.addUniform(uniformName, size);
  35536. location = this._uniformLocations[uniformName];
  35537. }
  35538. if (!this._buffer) {
  35539. this.create();
  35540. }
  35541. if (!this._dynamic) {
  35542. // Cache for static uniform buffers
  35543. var changed = false;
  35544. for (var i = 0; i < size; i++) {
  35545. if (this._bufferData[location + i] !== data[i]) {
  35546. changed = true;
  35547. this._bufferData[location + i] = data[i];
  35548. }
  35549. }
  35550. this._needSync = this._needSync || changed;
  35551. }
  35552. else {
  35553. // No cache for dynamic
  35554. for (var i = 0; i < size; i++) {
  35555. this._bufferData[location + i] = data[i];
  35556. }
  35557. }
  35558. };
  35559. // Update methods
  35560. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35561. // To match std140, matrix must be realigned
  35562. for (var i = 0; i < 3; i++) {
  35563. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35564. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35565. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35566. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35567. }
  35568. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35569. };
  35570. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35571. this._currentEffect.setMatrix3x3(name, matrix);
  35572. };
  35573. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35574. this._currentEffect.setMatrix2x2(name, matrix);
  35575. };
  35576. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35577. // To match std140, matrix must be realigned
  35578. for (var i = 0; i < 2; i++) {
  35579. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35580. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35581. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35582. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35583. }
  35584. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35585. };
  35586. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35587. this._currentEffect.setFloat(name, x);
  35588. };
  35589. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35590. UniformBuffer._tempBuffer[0] = x;
  35591. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35592. };
  35593. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35594. if (suffix === void 0) { suffix = ""; }
  35595. this._currentEffect.setFloat2(name + suffix, x, y);
  35596. };
  35597. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35598. if (suffix === void 0) { suffix = ""; }
  35599. UniformBuffer._tempBuffer[0] = x;
  35600. UniformBuffer._tempBuffer[1] = y;
  35601. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35602. };
  35603. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35604. if (suffix === void 0) { suffix = ""; }
  35605. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35606. };
  35607. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35608. if (suffix === void 0) { suffix = ""; }
  35609. UniformBuffer._tempBuffer[0] = x;
  35610. UniformBuffer._tempBuffer[1] = y;
  35611. UniformBuffer._tempBuffer[2] = z;
  35612. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35613. };
  35614. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35615. if (suffix === void 0) { suffix = ""; }
  35616. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35617. };
  35618. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35619. if (suffix === void 0) { suffix = ""; }
  35620. UniformBuffer._tempBuffer[0] = x;
  35621. UniformBuffer._tempBuffer[1] = y;
  35622. UniformBuffer._tempBuffer[2] = z;
  35623. UniformBuffer._tempBuffer[3] = w;
  35624. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35625. };
  35626. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35627. this._currentEffect.setMatrix(name, mat);
  35628. };
  35629. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35630. this.updateUniform(name, mat.toArray(), 16);
  35631. };
  35632. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35633. this._currentEffect.setVector3(name, vector);
  35634. };
  35635. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35636. vector.toArray(UniformBuffer._tempBuffer);
  35637. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35638. };
  35639. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35640. this._currentEffect.setVector4(name, vector);
  35641. };
  35642. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35643. vector.toArray(UniformBuffer._tempBuffer);
  35644. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35645. };
  35646. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35647. if (suffix === void 0) { suffix = ""; }
  35648. this._currentEffect.setColor3(name + suffix, color);
  35649. };
  35650. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35651. if (suffix === void 0) { suffix = ""; }
  35652. color.toArray(UniformBuffer._tempBuffer);
  35653. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35654. };
  35655. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35656. if (suffix === void 0) { suffix = ""; }
  35657. this._currentEffect.setColor4(name + suffix, color, alpha);
  35658. };
  35659. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35660. if (suffix === void 0) { suffix = ""; }
  35661. color.toArray(UniformBuffer._tempBuffer);
  35662. UniformBuffer._tempBuffer[3] = alpha;
  35663. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35664. };
  35665. /**
  35666. * Sets a sampler uniform on the effect.
  35667. * @param {string} name Name of the sampler.
  35668. * @param {Texture} texture
  35669. */
  35670. UniformBuffer.prototype.setTexture = function (name, texture) {
  35671. this._currentEffect.setTexture(name, texture);
  35672. };
  35673. /**
  35674. * Directly updates the value of the uniform in the cache AND on the GPU.
  35675. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35676. * @param {number[]|Float32Array} data Flattened data
  35677. */
  35678. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35679. this.updateUniform(uniformName, data, data.length);
  35680. this.update();
  35681. };
  35682. /**
  35683. * Binds this uniform buffer to an effect.
  35684. * @param {Effect} effect
  35685. * @param {string} name Name of the uniform block in the shader.
  35686. */
  35687. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35688. this._currentEffect = effect;
  35689. if (this._noUBO || !this._buffer) {
  35690. return;
  35691. }
  35692. effect.bindUniformBuffer(this._buffer, name);
  35693. };
  35694. /**
  35695. * Disposes the uniform buffer.
  35696. */
  35697. UniformBuffer.prototype.dispose = function () {
  35698. if (this._noUBO) {
  35699. return;
  35700. }
  35701. var index = this._engine._uniformBuffers.indexOf(this);
  35702. if (index !== -1) {
  35703. this._engine._uniformBuffers.splice(index, 1);
  35704. }
  35705. if (!this._buffer) {
  35706. return;
  35707. }
  35708. if (this._engine._releaseBuffer(this._buffer)) {
  35709. this._buffer = null;
  35710. }
  35711. };
  35712. // Pool for avoiding memory leaks
  35713. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35714. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35715. return UniformBuffer;
  35716. }());
  35717. BABYLON.UniformBuffer = UniformBuffer;
  35718. })(BABYLON || (BABYLON = {}));
  35719. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35720. var BABYLON;
  35721. (function (BABYLON) {
  35722. /**
  35723. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35724. */
  35725. var VertexData = /** @class */ (function () {
  35726. function VertexData() {
  35727. }
  35728. /**
  35729. * Uses the passed data array to set the set the values for the specified kind of data
  35730. * @param data a linear array of floating numbers
  35731. * @param kind the type of data that is being set, eg positions, colors etc
  35732. */
  35733. VertexData.prototype.set = function (data, kind) {
  35734. switch (kind) {
  35735. case BABYLON.VertexBuffer.PositionKind:
  35736. this.positions = data;
  35737. break;
  35738. case BABYLON.VertexBuffer.NormalKind:
  35739. this.normals = data;
  35740. break;
  35741. case BABYLON.VertexBuffer.TangentKind:
  35742. this.tangents = data;
  35743. break;
  35744. case BABYLON.VertexBuffer.UVKind:
  35745. this.uvs = data;
  35746. break;
  35747. case BABYLON.VertexBuffer.UV2Kind:
  35748. this.uvs2 = data;
  35749. break;
  35750. case BABYLON.VertexBuffer.UV3Kind:
  35751. this.uvs3 = data;
  35752. break;
  35753. case BABYLON.VertexBuffer.UV4Kind:
  35754. this.uvs4 = data;
  35755. break;
  35756. case BABYLON.VertexBuffer.UV5Kind:
  35757. this.uvs5 = data;
  35758. break;
  35759. case BABYLON.VertexBuffer.UV6Kind:
  35760. this.uvs6 = data;
  35761. break;
  35762. case BABYLON.VertexBuffer.ColorKind:
  35763. this.colors = data;
  35764. break;
  35765. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35766. this.matricesIndices = data;
  35767. break;
  35768. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35769. this.matricesWeights = data;
  35770. break;
  35771. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35772. this.matricesIndicesExtra = data;
  35773. break;
  35774. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35775. this.matricesWeightsExtra = data;
  35776. break;
  35777. }
  35778. };
  35779. /**
  35780. * Associates the vertexData to the passed Mesh.
  35781. * Sets it as updatable or not (default `false`)
  35782. * @param mesh the mesh the vertexData is applied to
  35783. * @param updatable when used and having the value true allows new data to update the vertexData
  35784. * @returns the VertexData
  35785. */
  35786. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35787. this._applyTo(mesh, updatable);
  35788. return this;
  35789. };
  35790. /**
  35791. * Associates the vertexData to the passed Geometry.
  35792. * Sets it as updatable or not (default `false`)
  35793. * @param geometry the geometry the vertexData is applied to
  35794. * @param updatable when used and having the value true allows new data to update the vertexData
  35795. * @returns VertexData
  35796. */
  35797. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35798. this._applyTo(geometry, updatable);
  35799. return this;
  35800. };
  35801. /**
  35802. * Updates the associated mesh
  35803. * @param mesh the mesh to be updated
  35804. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35805. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  35806. * @returns VertexData
  35807. */
  35808. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35809. this._update(mesh);
  35810. return this;
  35811. };
  35812. /**
  35813. * Updates the associated geometry
  35814. * @param geometry the geometry to be updated
  35815. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35816. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  35817. * @returns VertexData.
  35818. */
  35819. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35820. this._update(geometry);
  35821. return this;
  35822. };
  35823. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35824. if (updatable === void 0) { updatable = false; }
  35825. if (this.positions) {
  35826. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35827. }
  35828. if (this.normals) {
  35829. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35830. }
  35831. if (this.tangents) {
  35832. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35833. }
  35834. if (this.uvs) {
  35835. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35836. }
  35837. if (this.uvs2) {
  35838. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35839. }
  35840. if (this.uvs3) {
  35841. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35842. }
  35843. if (this.uvs4) {
  35844. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35845. }
  35846. if (this.uvs5) {
  35847. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35848. }
  35849. if (this.uvs6) {
  35850. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35851. }
  35852. if (this.colors) {
  35853. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35854. }
  35855. if (this.matricesIndices) {
  35856. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35857. }
  35858. if (this.matricesWeights) {
  35859. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35860. }
  35861. if (this.matricesIndicesExtra) {
  35862. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35863. }
  35864. if (this.matricesWeightsExtra) {
  35865. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35866. }
  35867. if (this.indices) {
  35868. meshOrGeometry.setIndices(this.indices, null, updatable);
  35869. }
  35870. return this;
  35871. };
  35872. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35873. if (this.positions) {
  35874. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35875. }
  35876. if (this.normals) {
  35877. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35878. }
  35879. if (this.tangents) {
  35880. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35881. }
  35882. if (this.uvs) {
  35883. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35884. }
  35885. if (this.uvs2) {
  35886. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35887. }
  35888. if (this.uvs3) {
  35889. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35890. }
  35891. if (this.uvs4) {
  35892. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35893. }
  35894. if (this.uvs5) {
  35895. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35896. }
  35897. if (this.uvs6) {
  35898. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35899. }
  35900. if (this.colors) {
  35901. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35902. }
  35903. if (this.matricesIndices) {
  35904. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35905. }
  35906. if (this.matricesWeights) {
  35907. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35908. }
  35909. if (this.matricesIndicesExtra) {
  35910. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35911. }
  35912. if (this.matricesWeightsExtra) {
  35913. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35914. }
  35915. if (this.indices) {
  35916. meshOrGeometry.setIndices(this.indices, null);
  35917. }
  35918. return this;
  35919. };
  35920. /**
  35921. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35922. * @param matrix the transforming matrix
  35923. * @returns the VertexData
  35924. */
  35925. VertexData.prototype.transform = function (matrix) {
  35926. var transformed = BABYLON.Vector3.Zero();
  35927. var index;
  35928. if (this.positions) {
  35929. var position = BABYLON.Vector3.Zero();
  35930. for (index = 0; index < this.positions.length; index += 3) {
  35931. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35932. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35933. this.positions[index] = transformed.x;
  35934. this.positions[index + 1] = transformed.y;
  35935. this.positions[index + 2] = transformed.z;
  35936. }
  35937. }
  35938. if (this.normals) {
  35939. var normal = BABYLON.Vector3.Zero();
  35940. for (index = 0; index < this.normals.length; index += 3) {
  35941. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35942. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35943. this.normals[index] = transformed.x;
  35944. this.normals[index + 1] = transformed.y;
  35945. this.normals[index + 2] = transformed.z;
  35946. }
  35947. }
  35948. if (this.tangents) {
  35949. var tangent = BABYLON.Vector4.Zero();
  35950. var tangentTransformed = BABYLON.Vector4.Zero();
  35951. for (index = 0; index < this.tangents.length; index += 4) {
  35952. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35953. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35954. this.tangents[index] = tangentTransformed.x;
  35955. this.tangents[index + 1] = tangentTransformed.y;
  35956. this.tangents[index + 2] = tangentTransformed.z;
  35957. this.tangents[index + 3] = tangentTransformed.w;
  35958. }
  35959. }
  35960. return this;
  35961. };
  35962. /**
  35963. * Merges the passed VertexData into the current one
  35964. * @param other the VertexData to be merged into the current one
  35965. * @returns the modified VertexData
  35966. */
  35967. VertexData.prototype.merge = function (other) {
  35968. this._validate();
  35969. other._validate();
  35970. if (!this.normals !== !other.normals ||
  35971. !this.tangents !== !other.tangents ||
  35972. !this.uvs !== !other.uvs ||
  35973. !this.uvs2 !== !other.uvs2 ||
  35974. !this.uvs3 !== !other.uvs3 ||
  35975. !this.uvs4 !== !other.uvs4 ||
  35976. !this.uvs5 !== !other.uvs5 ||
  35977. !this.uvs6 !== !other.uvs6 ||
  35978. !this.colors !== !other.colors ||
  35979. !this.matricesIndices !== !other.matricesIndices ||
  35980. !this.matricesWeights !== !other.matricesWeights ||
  35981. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35982. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35983. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35984. }
  35985. if (other.indices) {
  35986. if (!this.indices) {
  35987. this.indices = [];
  35988. }
  35989. var offset = this.positions ? this.positions.length / 3 : 0;
  35990. for (var index = 0; index < other.indices.length; index++) {
  35991. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35992. this.indices.push(other.indices[index] + offset);
  35993. }
  35994. }
  35995. this.positions = this._mergeElement(this.positions, other.positions);
  35996. this.normals = this._mergeElement(this.normals, other.normals);
  35997. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35998. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35999. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36000. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36001. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36002. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36003. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36004. this.colors = this._mergeElement(this.colors, other.colors);
  36005. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36006. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36007. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36008. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36009. return this;
  36010. };
  36011. VertexData.prototype._mergeElement = function (source, other) {
  36012. if (!source) {
  36013. return other;
  36014. }
  36015. if (!other) {
  36016. return source;
  36017. }
  36018. var len = other.length + source.length;
  36019. var isSrcTypedArray = source instanceof Float32Array;
  36020. var isOthTypedArray = other instanceof Float32Array;
  36021. // use non-loop method when the source is Float32Array
  36022. if (isSrcTypedArray) {
  36023. var ret32 = new Float32Array(len);
  36024. ret32.set(source);
  36025. ret32.set(other, source.length);
  36026. return ret32;
  36027. // source is number[], when other is also use concat
  36028. }
  36029. else if (!isOthTypedArray) {
  36030. return source.concat(other);
  36031. // source is a number[], but other is a Float32Array, loop required
  36032. }
  36033. else {
  36034. var ret = source.slice(0); // copy source to a separate array
  36035. for (var i = 0, len = other.length; i < len; i++) {
  36036. ret.push(other[i]);
  36037. }
  36038. return ret;
  36039. }
  36040. };
  36041. VertexData.prototype._validate = function () {
  36042. if (!this.positions) {
  36043. throw new Error("Positions are required");
  36044. }
  36045. var getElementCount = function (kind, values) {
  36046. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36047. if ((values.length % stride) !== 0) {
  36048. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36049. }
  36050. return values.length / stride;
  36051. };
  36052. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36053. var validateElementCount = function (kind, values) {
  36054. var elementCount = getElementCount(kind, values);
  36055. if (elementCount !== positionsElementCount) {
  36056. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36057. }
  36058. };
  36059. if (this.normals)
  36060. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36061. if (this.tangents)
  36062. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36063. if (this.uvs)
  36064. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36065. if (this.uvs2)
  36066. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36067. if (this.uvs3)
  36068. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36069. if (this.uvs4)
  36070. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36071. if (this.uvs5)
  36072. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36073. if (this.uvs6)
  36074. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36075. if (this.colors)
  36076. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36077. if (this.matricesIndices)
  36078. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36079. if (this.matricesWeights)
  36080. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36081. if (this.matricesIndicesExtra)
  36082. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36083. if (this.matricesWeightsExtra)
  36084. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36085. };
  36086. /**
  36087. * Serializes the VertexData
  36088. * @returns a serialized object
  36089. */
  36090. VertexData.prototype.serialize = function () {
  36091. var serializationObject = this.serialize();
  36092. if (this.positions) {
  36093. serializationObject.positions = this.positions;
  36094. }
  36095. if (this.normals) {
  36096. serializationObject.normals = this.normals;
  36097. }
  36098. if (this.tangents) {
  36099. serializationObject.tangents = this.tangents;
  36100. }
  36101. if (this.uvs) {
  36102. serializationObject.uvs = this.uvs;
  36103. }
  36104. if (this.uvs2) {
  36105. serializationObject.uvs2 = this.uvs2;
  36106. }
  36107. if (this.uvs3) {
  36108. serializationObject.uvs3 = this.uvs3;
  36109. }
  36110. if (this.uvs4) {
  36111. serializationObject.uvs4 = this.uvs4;
  36112. }
  36113. if (this.uvs5) {
  36114. serializationObject.uvs5 = this.uvs5;
  36115. }
  36116. if (this.uvs6) {
  36117. serializationObject.uvs6 = this.uvs6;
  36118. }
  36119. if (this.colors) {
  36120. serializationObject.colors = this.colors;
  36121. }
  36122. if (this.matricesIndices) {
  36123. serializationObject.matricesIndices = this.matricesIndices;
  36124. serializationObject.matricesIndices._isExpanded = true;
  36125. }
  36126. if (this.matricesWeights) {
  36127. serializationObject.matricesWeights = this.matricesWeights;
  36128. }
  36129. if (this.matricesIndicesExtra) {
  36130. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36131. serializationObject.matricesIndicesExtra._isExpanded = true;
  36132. }
  36133. if (this.matricesWeightsExtra) {
  36134. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36135. }
  36136. serializationObject.indices = this.indices;
  36137. return serializationObject;
  36138. };
  36139. // Statics
  36140. /**
  36141. * Extracts the vertexData from a mesh
  36142. * @param mesh the mesh from which to extract the VertexData
  36143. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36144. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36145. * @returns the object VertexData associated to the passed mesh
  36146. */
  36147. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36148. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36149. };
  36150. /**
  36151. * Extracts the vertexData from the geometry
  36152. * @param geometry the geometry from which to extract the VertexData
  36153. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36154. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36155. * @returns the object VertexData associated to the passed mesh
  36156. */
  36157. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36158. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36159. };
  36160. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36161. var result = new VertexData();
  36162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36163. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36164. }
  36165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36166. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36167. }
  36168. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36169. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36170. }
  36171. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36172. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36173. }
  36174. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36175. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36176. }
  36177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36178. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36179. }
  36180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36181. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36182. }
  36183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36184. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36185. }
  36186. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36187. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36188. }
  36189. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36190. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36191. }
  36192. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36193. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36194. }
  36195. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36196. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36197. }
  36198. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36199. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36200. }
  36201. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36202. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36203. }
  36204. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36205. return result;
  36206. };
  36207. /**
  36208. * Creates the VertexData for a Ribbon
  36209. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36210. * * pathArray array of paths, each of which an array of successive Vector3
  36211. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36212. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36213. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36214. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36215. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36216. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36217. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36218. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36219. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36220. * @returns the VertexData of the ribbon
  36221. */
  36222. VertexData.CreateRibbon = function (options) {
  36223. var pathArray = options.pathArray;
  36224. var closeArray = options.closeArray || false;
  36225. var closePath = options.closePath || false;
  36226. var invertUV = options.invertUV || false;
  36227. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36228. var offset = options.offset || defaultOffset;
  36229. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36230. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36231. var customUV = options.uvs;
  36232. var customColors = options.colors;
  36233. var positions = [];
  36234. var indices = [];
  36235. var normals = [];
  36236. var uvs = [];
  36237. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36238. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36239. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36240. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36241. var minlg; // minimal length among all paths from pathArray
  36242. var lg = []; // array of path lengths : nb of vertex per path
  36243. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36244. var p; // path iterator
  36245. var i; // point iterator
  36246. var j; // point iterator
  36247. // if single path in pathArray
  36248. if (pathArray.length < 2) {
  36249. var ar1 = [];
  36250. var ar2 = [];
  36251. for (i = 0; i < pathArray[0].length - offset; i++) {
  36252. ar1.push(pathArray[0][i]);
  36253. ar2.push(pathArray[0][i + offset]);
  36254. }
  36255. pathArray = [ar1, ar2];
  36256. }
  36257. // positions and horizontal distances (u)
  36258. var idc = 0;
  36259. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36260. var path;
  36261. var l;
  36262. minlg = pathArray[0].length;
  36263. var vectlg;
  36264. var dist;
  36265. for (p = 0; p < pathArray.length; p++) {
  36266. uTotalDistance[p] = 0;
  36267. us[p] = [0];
  36268. path = pathArray[p];
  36269. l = path.length;
  36270. minlg = (minlg < l) ? minlg : l;
  36271. j = 0;
  36272. while (j < l) {
  36273. positions.push(path[j].x, path[j].y, path[j].z);
  36274. if (j > 0) {
  36275. vectlg = path[j].subtract(path[j - 1]).length();
  36276. dist = vectlg + uTotalDistance[p];
  36277. us[p].push(dist);
  36278. uTotalDistance[p] = dist;
  36279. }
  36280. j++;
  36281. }
  36282. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36283. j--;
  36284. positions.push(path[0].x, path[0].y, path[0].z);
  36285. vectlg = path[j].subtract(path[0]).length();
  36286. dist = vectlg + uTotalDistance[p];
  36287. us[p].push(dist);
  36288. uTotalDistance[p] = dist;
  36289. }
  36290. lg[p] = l + closePathCorr;
  36291. idx[p] = idc;
  36292. idc += (l + closePathCorr);
  36293. }
  36294. // vertical distances (v)
  36295. var path1;
  36296. var path2;
  36297. var vertex1 = null;
  36298. var vertex2 = null;
  36299. for (i = 0; i < minlg + closePathCorr; i++) {
  36300. vTotalDistance[i] = 0;
  36301. vs[i] = [0];
  36302. for (p = 0; p < pathArray.length - 1; p++) {
  36303. path1 = pathArray[p];
  36304. path2 = pathArray[p + 1];
  36305. if (i === minlg) { // closePath
  36306. vertex1 = path1[0];
  36307. vertex2 = path2[0];
  36308. }
  36309. else {
  36310. vertex1 = path1[i];
  36311. vertex2 = path2[i];
  36312. }
  36313. vectlg = vertex2.subtract(vertex1).length();
  36314. dist = vectlg + vTotalDistance[i];
  36315. vs[i].push(dist);
  36316. vTotalDistance[i] = dist;
  36317. }
  36318. if (closeArray && vertex2 && vertex1) {
  36319. path1 = pathArray[p];
  36320. path2 = pathArray[0];
  36321. if (i === minlg) { // closePath
  36322. vertex2 = path2[0];
  36323. }
  36324. vectlg = vertex2.subtract(vertex1).length();
  36325. dist = vectlg + vTotalDistance[i];
  36326. vTotalDistance[i] = dist;
  36327. }
  36328. }
  36329. // uvs
  36330. var u;
  36331. var v;
  36332. if (customUV) {
  36333. for (p = 0; p < customUV.length; p++) {
  36334. uvs.push(customUV[p].x, customUV[p].y);
  36335. }
  36336. }
  36337. else {
  36338. for (p = 0; p < pathArray.length; p++) {
  36339. for (i = 0; i < minlg + closePathCorr; i++) {
  36340. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36341. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36342. if (invertUV) {
  36343. uvs.push(v, u);
  36344. }
  36345. else {
  36346. uvs.push(u, v);
  36347. }
  36348. }
  36349. }
  36350. }
  36351. // indices
  36352. p = 0; // path index
  36353. var pi = 0; // positions array index
  36354. var l1 = lg[p] - 1; // path1 length
  36355. var l2 = lg[p + 1] - 1; // path2 length
  36356. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36357. var shft = idx[1] - idx[0]; // shift
  36358. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36359. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36360. // 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
  36361. indices.push(pi, pi + shft, pi + 1);
  36362. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36363. pi += 1;
  36364. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36365. p++;
  36366. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36367. shft = idx[0] - idx[p];
  36368. l1 = lg[p] - 1;
  36369. l2 = lg[0] - 1;
  36370. }
  36371. else {
  36372. shft = idx[p + 1] - idx[p];
  36373. l1 = lg[p] - 1;
  36374. l2 = lg[p + 1] - 1;
  36375. }
  36376. pi = idx[p];
  36377. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36378. }
  36379. }
  36380. // normals
  36381. VertexData.ComputeNormals(positions, indices, normals);
  36382. if (closePath) { // update both the first and last vertex normals to their average value
  36383. var indexFirst = 0;
  36384. var indexLast = 0;
  36385. for (p = 0; p < pathArray.length; p++) {
  36386. indexFirst = idx[p] * 3;
  36387. if (p + 1 < pathArray.length) {
  36388. indexLast = (idx[p + 1] - 1) * 3;
  36389. }
  36390. else {
  36391. indexLast = normals.length - 3;
  36392. }
  36393. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36394. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36395. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36396. normals[indexLast] = normals[indexFirst];
  36397. normals[indexLast + 1] = normals[indexFirst + 1];
  36398. normals[indexLast + 2] = normals[indexFirst + 2];
  36399. }
  36400. }
  36401. // sides
  36402. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36403. // Colors
  36404. var colors = null;
  36405. if (customColors) {
  36406. colors = new Float32Array(customColors.length * 4);
  36407. for (var c = 0; c < customColors.length; c++) {
  36408. colors[c * 4] = customColors[c].r;
  36409. colors[c * 4 + 1] = customColors[c].g;
  36410. colors[c * 4 + 2] = customColors[c].b;
  36411. colors[c * 4 + 3] = customColors[c].a;
  36412. }
  36413. }
  36414. // Result
  36415. var vertexData = new VertexData();
  36416. var positions32 = new Float32Array(positions);
  36417. var normals32 = new Float32Array(normals);
  36418. var uvs32 = new Float32Array(uvs);
  36419. vertexData.indices = indices;
  36420. vertexData.positions = positions32;
  36421. vertexData.normals = normals32;
  36422. vertexData.uvs = uvs32;
  36423. if (colors) {
  36424. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36425. }
  36426. if (closePath) {
  36427. vertexData._idx = idx;
  36428. }
  36429. return vertexData;
  36430. };
  36431. /**
  36432. * Creates the VertexData for a box
  36433. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36434. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36435. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36436. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36437. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36438. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36439. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36440. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36441. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36442. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36443. * @returns the VertexData of the box
  36444. */
  36445. VertexData.CreateBox = function (options) {
  36446. var normalsSource = [
  36447. new BABYLON.Vector3(0, 0, 1),
  36448. new BABYLON.Vector3(0, 0, -1),
  36449. new BABYLON.Vector3(1, 0, 0),
  36450. new BABYLON.Vector3(-1, 0, 0),
  36451. new BABYLON.Vector3(0, 1, 0),
  36452. new BABYLON.Vector3(0, -1, 0)
  36453. ];
  36454. var indices = [];
  36455. var positions = [];
  36456. var normals = [];
  36457. var uvs = [];
  36458. var width = options.width || options.size || 1;
  36459. var height = options.height || options.size || 1;
  36460. var depth = options.depth || options.size || 1;
  36461. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36462. var faceUV = options.faceUV || new Array(6);
  36463. var faceColors = options.faceColors;
  36464. var colors = [];
  36465. // default face colors and UV if undefined
  36466. for (var f = 0; f < 6; f++) {
  36467. if (faceUV[f] === undefined) {
  36468. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36469. }
  36470. if (faceColors && faceColors[f] === undefined) {
  36471. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36472. }
  36473. }
  36474. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36475. // Create each face in turn.
  36476. for (var index = 0; index < normalsSource.length; index++) {
  36477. var normal = normalsSource[index];
  36478. // Get two vectors perpendicular to the face normal and to each other.
  36479. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36480. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36481. // Six indices (two triangles) per face.
  36482. var verticesLength = positions.length / 3;
  36483. indices.push(verticesLength);
  36484. indices.push(verticesLength + 1);
  36485. indices.push(verticesLength + 2);
  36486. indices.push(verticesLength);
  36487. indices.push(verticesLength + 2);
  36488. indices.push(verticesLength + 3);
  36489. // Four vertices per face.
  36490. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36491. positions.push(vertex.x, vertex.y, vertex.z);
  36492. normals.push(normal.x, normal.y, normal.z);
  36493. uvs.push(faceUV[index].z, faceUV[index].w);
  36494. if (faceColors) {
  36495. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36496. }
  36497. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36498. positions.push(vertex.x, vertex.y, vertex.z);
  36499. normals.push(normal.x, normal.y, normal.z);
  36500. uvs.push(faceUV[index].x, faceUV[index].w);
  36501. if (faceColors) {
  36502. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36503. }
  36504. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36505. positions.push(vertex.x, vertex.y, vertex.z);
  36506. normals.push(normal.x, normal.y, normal.z);
  36507. uvs.push(faceUV[index].x, faceUV[index].y);
  36508. if (faceColors) {
  36509. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36510. }
  36511. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36512. positions.push(vertex.x, vertex.y, vertex.z);
  36513. normals.push(normal.x, normal.y, normal.z);
  36514. uvs.push(faceUV[index].z, faceUV[index].y);
  36515. if (faceColors) {
  36516. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36517. }
  36518. }
  36519. // sides
  36520. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36521. // Result
  36522. var vertexData = new VertexData();
  36523. vertexData.indices = indices;
  36524. vertexData.positions = positions;
  36525. vertexData.normals = normals;
  36526. vertexData.uvs = uvs;
  36527. if (faceColors) {
  36528. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36529. vertexData.colors = totalColors;
  36530. }
  36531. return vertexData;
  36532. };
  36533. /**
  36534. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36535. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36536. * * segments sets the number of horizontal strips optional, default 32
  36537. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36538. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36539. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36540. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36541. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36542. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36543. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36544. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36545. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36546. * @returns the VertexData of the ellipsoid
  36547. */
  36548. VertexData.CreateSphere = function (options) {
  36549. var segments = options.segments || 32;
  36550. var diameterX = options.diameterX || options.diameter || 1;
  36551. var diameterY = options.diameterY || options.diameter || 1;
  36552. var diameterZ = options.diameterZ || options.diameter || 1;
  36553. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36554. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36555. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36556. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36557. var totalZRotationSteps = 2 + segments;
  36558. var totalYRotationSteps = 2 * totalZRotationSteps;
  36559. var indices = [];
  36560. var positions = [];
  36561. var normals = [];
  36562. var uvs = [];
  36563. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36564. var normalizedZ = zRotationStep / totalZRotationSteps;
  36565. var angleZ = normalizedZ * Math.PI * slice;
  36566. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36567. var normalizedY = yRotationStep / totalYRotationSteps;
  36568. var angleY = normalizedY * Math.PI * 2 * arc;
  36569. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36570. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36571. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36572. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36573. var vertex = complete.multiply(radius);
  36574. var normal = complete.divide(radius).normalize();
  36575. positions.push(vertex.x, vertex.y, vertex.z);
  36576. normals.push(normal.x, normal.y, normal.z);
  36577. uvs.push(normalizedY, normalizedZ);
  36578. }
  36579. if (zRotationStep > 0) {
  36580. var verticesCount = positions.length / 3;
  36581. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36582. indices.push((firstIndex));
  36583. indices.push((firstIndex + 1));
  36584. indices.push(firstIndex + totalYRotationSteps + 1);
  36585. indices.push((firstIndex + totalYRotationSteps + 1));
  36586. indices.push((firstIndex + 1));
  36587. indices.push((firstIndex + totalYRotationSteps + 2));
  36588. }
  36589. }
  36590. }
  36591. // Sides
  36592. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36593. // Result
  36594. var vertexData = new VertexData();
  36595. vertexData.indices = indices;
  36596. vertexData.positions = positions;
  36597. vertexData.normals = normals;
  36598. vertexData.uvs = uvs;
  36599. return vertexData;
  36600. };
  36601. /**
  36602. * Creates the VertexData for a cylinder, cone or prism
  36603. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36604. * * height sets the height (y direction) of the cylinder, optional, default 2
  36605. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36606. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36607. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36608. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36609. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36610. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  36611. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36612. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36613. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36614. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36615. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36616. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36617. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36618. * @returns the VertexData of the cylinder, cone or prism
  36619. */
  36620. VertexData.CreateCylinder = function (options) {
  36621. var height = options.height || 2;
  36622. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36623. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36624. var tessellation = options.tessellation || 24;
  36625. var subdivisions = options.subdivisions || 1;
  36626. var hasRings = options.hasRings ? true : false;
  36627. var enclose = options.enclose ? true : false;
  36628. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36629. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36630. var faceUV = options.faceUV || new Array(3);
  36631. var faceColors = options.faceColors;
  36632. // default face colors and UV if undefined
  36633. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36634. var ringNb = (hasRings) ? subdivisions : 1;
  36635. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36636. var f;
  36637. for (f = 0; f < surfaceNb; f++) {
  36638. if (faceColors && faceColors[f] === undefined) {
  36639. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36640. }
  36641. }
  36642. for (f = 0; f < surfaceNb; f++) {
  36643. if (faceUV && faceUV[f] === undefined) {
  36644. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36645. }
  36646. }
  36647. var indices = new Array();
  36648. var positions = new Array();
  36649. var normals = new Array();
  36650. var uvs = new Array();
  36651. var colors = new Array();
  36652. var angle_step = Math.PI * 2 * arc / tessellation;
  36653. var angle;
  36654. var h;
  36655. var radius;
  36656. var tan = (diameterBottom - diameterTop) / 2 / height;
  36657. var ringVertex = BABYLON.Vector3.Zero();
  36658. var ringNormal = BABYLON.Vector3.Zero();
  36659. var ringFirstVertex = BABYLON.Vector3.Zero();
  36660. var ringFirstNormal = BABYLON.Vector3.Zero();
  36661. var quadNormal = BABYLON.Vector3.Zero();
  36662. var Y = BABYLON.Axis.Y;
  36663. // positions, normals, uvs
  36664. var i;
  36665. var j;
  36666. var r;
  36667. var ringIdx = 1;
  36668. var s = 1; // surface index
  36669. var cs = 0;
  36670. var v = 0;
  36671. for (i = 0; i <= subdivisions; i++) {
  36672. h = i / subdivisions;
  36673. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36674. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36675. for (r = 0; r < ringIdx; r++) {
  36676. if (hasRings) {
  36677. s += r;
  36678. }
  36679. if (enclose) {
  36680. s += 2 * r;
  36681. }
  36682. for (j = 0; j <= tessellation; j++) {
  36683. angle = j * angle_step;
  36684. // position
  36685. ringVertex.x = Math.cos(-angle) * radius;
  36686. ringVertex.y = -height / 2 + h * height;
  36687. ringVertex.z = Math.sin(-angle) * radius;
  36688. // normal
  36689. if (diameterTop === 0 && i === subdivisions) {
  36690. // if no top cap, reuse former normals
  36691. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36692. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36693. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36694. }
  36695. else {
  36696. ringNormal.x = ringVertex.x;
  36697. ringNormal.z = ringVertex.z;
  36698. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36699. ringNormal.normalize();
  36700. }
  36701. // keep first ring vertex values for enclose
  36702. if (j === 0) {
  36703. ringFirstVertex.copyFrom(ringVertex);
  36704. ringFirstNormal.copyFrom(ringNormal);
  36705. }
  36706. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36707. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36708. if (hasRings) {
  36709. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36710. }
  36711. else {
  36712. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36713. }
  36714. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36715. if (faceColors) {
  36716. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36717. }
  36718. }
  36719. // if enclose, add four vertices and their dedicated normals
  36720. if (arc !== 1 && enclose) {
  36721. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36722. positions.push(0, ringVertex.y, 0);
  36723. positions.push(0, ringVertex.y, 0);
  36724. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36725. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36726. quadNormal.normalize();
  36727. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36728. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36729. quadNormal.normalize();
  36730. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36731. if (hasRings) {
  36732. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36733. }
  36734. else {
  36735. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36736. }
  36737. uvs.push(faceUV[s + 1].x, v);
  36738. uvs.push(faceUV[s + 1].z, v);
  36739. if (hasRings) {
  36740. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36741. }
  36742. else {
  36743. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36744. }
  36745. uvs.push(faceUV[s + 2].x, v);
  36746. uvs.push(faceUV[s + 2].z, v);
  36747. if (faceColors) {
  36748. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36749. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36750. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36751. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36752. }
  36753. }
  36754. if (cs !== s) {
  36755. cs = s;
  36756. }
  36757. }
  36758. }
  36759. // indices
  36760. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36761. var s;
  36762. i = 0;
  36763. for (s = 0; s < subdivisions; s++) {
  36764. var i0 = 0;
  36765. var i1 = 0;
  36766. var i2 = 0;
  36767. var i3 = 0;
  36768. for (j = 0; j < tessellation; j++) {
  36769. i0 = i * (e + 1) + j;
  36770. i1 = (i + 1) * (e + 1) + j;
  36771. i2 = i * (e + 1) + (j + 1);
  36772. i3 = (i + 1) * (e + 1) + (j + 1);
  36773. indices.push(i0, i1, i2);
  36774. indices.push(i3, i2, i1);
  36775. }
  36776. if (arc !== 1 && enclose) { // if enclose, add two quads
  36777. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36778. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36779. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36780. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36781. }
  36782. i = (hasRings) ? (i + 2) : (i + 1);
  36783. }
  36784. // Caps
  36785. var createCylinderCap = function (isTop) {
  36786. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36787. if (radius === 0) {
  36788. return;
  36789. }
  36790. // Cap positions, normals & uvs
  36791. var angle;
  36792. var circleVector;
  36793. var i;
  36794. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36795. var c = null;
  36796. if (faceColors) {
  36797. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36798. }
  36799. // cap center
  36800. var vbase = positions.length / 3;
  36801. var offset = isTop ? height / 2 : -height / 2;
  36802. var center = new BABYLON.Vector3(0, offset, 0);
  36803. positions.push(center.x, center.y, center.z);
  36804. normals.push(0, isTop ? 1 : -1, 0);
  36805. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36806. if (c) {
  36807. colors.push(c.r, c.g, c.b, c.a);
  36808. }
  36809. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36810. for (i = 0; i <= tessellation; i++) {
  36811. angle = Math.PI * 2 * i * arc / tessellation;
  36812. var cos = Math.cos(-angle);
  36813. var sin = Math.sin(-angle);
  36814. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36815. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36816. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36817. normals.push(0, isTop ? 1 : -1, 0);
  36818. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36819. if (c) {
  36820. colors.push(c.r, c.g, c.b, c.a);
  36821. }
  36822. }
  36823. // Cap indices
  36824. for (i = 0; i < tessellation; i++) {
  36825. if (!isTop) {
  36826. indices.push(vbase);
  36827. indices.push(vbase + (i + 1));
  36828. indices.push(vbase + (i + 2));
  36829. }
  36830. else {
  36831. indices.push(vbase);
  36832. indices.push(vbase + (i + 2));
  36833. indices.push(vbase + (i + 1));
  36834. }
  36835. }
  36836. };
  36837. // add caps to geometry
  36838. createCylinderCap(false);
  36839. createCylinderCap(true);
  36840. // Sides
  36841. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36842. var vertexData = new VertexData();
  36843. vertexData.indices = indices;
  36844. vertexData.positions = positions;
  36845. vertexData.normals = normals;
  36846. vertexData.uvs = uvs;
  36847. if (faceColors) {
  36848. vertexData.colors = colors;
  36849. }
  36850. return vertexData;
  36851. };
  36852. /**
  36853. * Creates the VertexData for a torus
  36854. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36855. * * diameter the diameter of the torus, optional default 1
  36856. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36857. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36858. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36859. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36860. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36861. * @returns the VertexData of the torus
  36862. */
  36863. VertexData.CreateTorus = function (options) {
  36864. var indices = [];
  36865. var positions = [];
  36866. var normals = [];
  36867. var uvs = [];
  36868. var diameter = options.diameter || 1;
  36869. var thickness = options.thickness || 0.5;
  36870. var tessellation = options.tessellation || 16;
  36871. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36872. var stride = tessellation + 1;
  36873. for (var i = 0; i <= tessellation; i++) {
  36874. var u = i / tessellation;
  36875. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36876. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36877. for (var j = 0; j <= tessellation; j++) {
  36878. var v = 1 - j / tessellation;
  36879. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36880. var dx = Math.cos(innerAngle);
  36881. var dy = Math.sin(innerAngle);
  36882. // Create a vertex.
  36883. var normal = new BABYLON.Vector3(dx, dy, 0);
  36884. var position = normal.scale(thickness / 2);
  36885. var textureCoordinate = new BABYLON.Vector2(u, v);
  36886. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36887. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36888. positions.push(position.x, position.y, position.z);
  36889. normals.push(normal.x, normal.y, normal.z);
  36890. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36891. // And create indices for two triangles.
  36892. var nextI = (i + 1) % stride;
  36893. var nextJ = (j + 1) % stride;
  36894. indices.push(i * stride + j);
  36895. indices.push(i * stride + nextJ);
  36896. indices.push(nextI * stride + j);
  36897. indices.push(i * stride + nextJ);
  36898. indices.push(nextI * stride + nextJ);
  36899. indices.push(nextI * stride + j);
  36900. }
  36901. }
  36902. // Sides
  36903. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36904. // Result
  36905. var vertexData = new VertexData();
  36906. vertexData.indices = indices;
  36907. vertexData.positions = positions;
  36908. vertexData.normals = normals;
  36909. vertexData.uvs = uvs;
  36910. return vertexData;
  36911. };
  36912. /**
  36913. * Creates the VertexData of the LineSystem
  36914. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36915. * - lines an array of lines, each line being an array of successive Vector3
  36916. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36917. * @returns the VertexData of the LineSystem
  36918. */
  36919. VertexData.CreateLineSystem = function (options) {
  36920. var indices = [];
  36921. var positions = [];
  36922. var lines = options.lines;
  36923. var colors = options.colors;
  36924. var vertexColors = [];
  36925. var idx = 0;
  36926. for (var l = 0; l < lines.length; l++) {
  36927. var points = lines[l];
  36928. for (var index = 0; index < points.length; index++) {
  36929. positions.push(points[index].x, points[index].y, points[index].z);
  36930. if (colors) {
  36931. var color = colors[l];
  36932. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36933. }
  36934. if (index > 0) {
  36935. indices.push(idx - 1);
  36936. indices.push(idx);
  36937. }
  36938. idx++;
  36939. }
  36940. }
  36941. var vertexData = new VertexData();
  36942. vertexData.indices = indices;
  36943. vertexData.positions = positions;
  36944. if (colors) {
  36945. vertexData.colors = vertexColors;
  36946. }
  36947. return vertexData;
  36948. };
  36949. /**
  36950. * Create the VertexData for a DashedLines
  36951. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  36952. * - points an array successive Vector3
  36953. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  36954. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  36955. * - dashNb the intended total number of dashes, optional, default 200
  36956. * @returns the VertexData for the DashedLines
  36957. */
  36958. VertexData.CreateDashedLines = function (options) {
  36959. var dashSize = options.dashSize || 3;
  36960. var gapSize = options.gapSize || 1;
  36961. var dashNb = options.dashNb || 200;
  36962. var points = options.points;
  36963. var positions = new Array();
  36964. var indices = new Array();
  36965. var curvect = BABYLON.Vector3.Zero();
  36966. var lg = 0;
  36967. var nb = 0;
  36968. var shft = 0;
  36969. var dashshft = 0;
  36970. var curshft = 0;
  36971. var idx = 0;
  36972. var i = 0;
  36973. for (i = 0; i < points.length - 1; i++) {
  36974. points[i + 1].subtractToRef(points[i], curvect);
  36975. lg += curvect.length();
  36976. }
  36977. shft = lg / dashNb;
  36978. dashshft = dashSize * shft / (dashSize + gapSize);
  36979. for (i = 0; i < points.length - 1; i++) {
  36980. points[i + 1].subtractToRef(points[i], curvect);
  36981. nb = Math.floor(curvect.length() / shft);
  36982. curvect.normalize();
  36983. for (var j = 0; j < nb; j++) {
  36984. curshft = shft * j;
  36985. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36986. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36987. indices.push(idx, idx + 1);
  36988. idx += 2;
  36989. }
  36990. }
  36991. // Result
  36992. var vertexData = new VertexData();
  36993. vertexData.positions = positions;
  36994. vertexData.indices = indices;
  36995. return vertexData;
  36996. };
  36997. /**
  36998. * Creates the VertexData for a Ground
  36999. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37000. * - width the width (x direction) of the ground, optional, default 1
  37001. * - height the height (z direction) of the ground, optional, default 1
  37002. * - subdivisions the number of subdivisions per side, optional, default 1
  37003. * @returns the VertexData of the Ground
  37004. */
  37005. VertexData.CreateGround = function (options) {
  37006. var indices = [];
  37007. var positions = [];
  37008. var normals = [];
  37009. var uvs = [];
  37010. var row, col;
  37011. var width = options.width || 1;
  37012. var height = options.height || 1;
  37013. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37014. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37015. for (row = 0; row <= subdivisionsY; row++) {
  37016. for (col = 0; col <= subdivisionsX; col++) {
  37017. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37018. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37019. positions.push(position.x, position.y, position.z);
  37020. normals.push(normal.x, normal.y, normal.z);
  37021. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37022. }
  37023. }
  37024. for (row = 0; row < subdivisionsY; row++) {
  37025. for (col = 0; col < subdivisionsX; col++) {
  37026. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37027. indices.push(col + 1 + row * (subdivisionsX + 1));
  37028. indices.push(col + row * (subdivisionsX + 1));
  37029. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37030. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37031. indices.push(col + row * (subdivisionsX + 1));
  37032. }
  37033. }
  37034. // Result
  37035. var vertexData = new VertexData();
  37036. vertexData.indices = indices;
  37037. vertexData.positions = positions;
  37038. vertexData.normals = normals;
  37039. vertexData.uvs = uvs;
  37040. return vertexData;
  37041. };
  37042. /**
  37043. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37044. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37045. * * xmin the ground minimum X coordinate, optional, default -1
  37046. * * zmin the ground minimum Z coordinate, optional, default -1
  37047. * * xmax the ground maximum X coordinate, optional, default 1
  37048. * * zmax the ground maximum Z coordinate, optional, default 1
  37049. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37050. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37051. * @returns the VertexData of the TiledGround
  37052. */
  37053. VertexData.CreateTiledGround = function (options) {
  37054. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37055. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37056. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37057. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37058. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37059. var precision = options.precision || { w: 1, h: 1 };
  37060. var indices = new Array();
  37061. var positions = new Array();
  37062. var normals = new Array();
  37063. var uvs = new Array();
  37064. var row, col, tileRow, tileCol;
  37065. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37066. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37067. precision.w = (precision.w < 1) ? 1 : precision.w;
  37068. precision.h = (precision.h < 1) ? 1 : precision.h;
  37069. var tileSize = {
  37070. 'w': (xmax - xmin) / subdivisions.w,
  37071. 'h': (zmax - zmin) / subdivisions.h
  37072. };
  37073. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37074. // Indices
  37075. var base = positions.length / 3;
  37076. var rowLength = precision.w + 1;
  37077. for (row = 0; row < precision.h; row++) {
  37078. for (col = 0; col < precision.w; col++) {
  37079. var square = [
  37080. base + col + row * rowLength,
  37081. base + (col + 1) + row * rowLength,
  37082. base + (col + 1) + (row + 1) * rowLength,
  37083. base + col + (row + 1) * rowLength
  37084. ];
  37085. indices.push(square[1]);
  37086. indices.push(square[2]);
  37087. indices.push(square[3]);
  37088. indices.push(square[0]);
  37089. indices.push(square[1]);
  37090. indices.push(square[3]);
  37091. }
  37092. }
  37093. // Position, normals and uvs
  37094. var position = BABYLON.Vector3.Zero();
  37095. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37096. for (row = 0; row <= precision.h; row++) {
  37097. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37098. for (col = 0; col <= precision.w; col++) {
  37099. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37100. position.y = 0;
  37101. positions.push(position.x, position.y, position.z);
  37102. normals.push(normal.x, normal.y, normal.z);
  37103. uvs.push(col / precision.w, row / precision.h);
  37104. }
  37105. }
  37106. }
  37107. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37108. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37109. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37110. }
  37111. }
  37112. // Result
  37113. var vertexData = new VertexData();
  37114. vertexData.indices = indices;
  37115. vertexData.positions = positions;
  37116. vertexData.normals = normals;
  37117. vertexData.uvs = uvs;
  37118. return vertexData;
  37119. };
  37120. /**
  37121. * Creates the VertexData of the Ground designed from a heightmap
  37122. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37123. * * width the width (x direction) of the ground
  37124. * * height the height (z direction) of the ground
  37125. * * subdivisions the number of subdivisions per side
  37126. * * minHeight the minimum altitude on the ground, optional, default 0
  37127. * * maxHeight the maximum altitude on the ground, optional default 1
  37128. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37129. * * buffer the array holding the image color data
  37130. * * bufferWidth the width of image
  37131. * * bufferHeight the height of image
  37132. * @returns the VertexData of the Ground designed from a heightmap
  37133. */
  37134. VertexData.CreateGroundFromHeightMap = function (options) {
  37135. var indices = [];
  37136. var positions = [];
  37137. var normals = [];
  37138. var uvs = [];
  37139. var row, col;
  37140. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37141. // Vertices
  37142. for (row = 0; row <= options.subdivisions; row++) {
  37143. for (col = 0; col <= options.subdivisions; col++) {
  37144. 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));
  37145. // Compute height
  37146. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37147. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37148. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37149. var r = options.buffer[pos] / 255.0;
  37150. var g = options.buffer[pos + 1] / 255.0;
  37151. var b = options.buffer[pos + 2] / 255.0;
  37152. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37153. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37154. // Add vertex
  37155. positions.push(position.x, position.y, position.z);
  37156. normals.push(0, 0, 0);
  37157. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37158. }
  37159. }
  37160. // Indices
  37161. for (row = 0; row < options.subdivisions; row++) {
  37162. for (col = 0; col < options.subdivisions; col++) {
  37163. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37164. indices.push(col + 1 + row * (options.subdivisions + 1));
  37165. indices.push(col + row * (options.subdivisions + 1));
  37166. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37167. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37168. indices.push(col + row * (options.subdivisions + 1));
  37169. }
  37170. }
  37171. // Normals
  37172. VertexData.ComputeNormals(positions, indices, normals);
  37173. // Result
  37174. var vertexData = new VertexData();
  37175. vertexData.indices = indices;
  37176. vertexData.positions = positions;
  37177. vertexData.normals = normals;
  37178. vertexData.uvs = uvs;
  37179. return vertexData;
  37180. };
  37181. /**
  37182. * Creates the VertexData for a Plane
  37183. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37184. * * size sets the width and height of the plane to the value of size, optional default 1
  37185. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37186. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37187. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37188. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37189. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37190. * @returns the VertexData of the box
  37191. */
  37192. VertexData.CreatePlane = function (options) {
  37193. var indices = [];
  37194. var positions = [];
  37195. var normals = [];
  37196. var uvs = [];
  37197. var width = options.width || options.size || 1;
  37198. var height = options.height || options.size || 1;
  37199. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37200. // Vertices
  37201. var halfWidth = width / 2.0;
  37202. var halfHeight = height / 2.0;
  37203. positions.push(-halfWidth, -halfHeight, 0);
  37204. normals.push(0, 0, -1.0);
  37205. uvs.push(0.0, 0.0);
  37206. positions.push(halfWidth, -halfHeight, 0);
  37207. normals.push(0, 0, -1.0);
  37208. uvs.push(1.0, 0.0);
  37209. positions.push(halfWidth, halfHeight, 0);
  37210. normals.push(0, 0, -1.0);
  37211. uvs.push(1.0, 1.0);
  37212. positions.push(-halfWidth, halfHeight, 0);
  37213. normals.push(0, 0, -1.0);
  37214. uvs.push(0.0, 1.0);
  37215. // Indices
  37216. indices.push(0);
  37217. indices.push(1);
  37218. indices.push(2);
  37219. indices.push(0);
  37220. indices.push(2);
  37221. indices.push(3);
  37222. // Sides
  37223. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37224. // Result
  37225. var vertexData = new VertexData();
  37226. vertexData.indices = indices;
  37227. vertexData.positions = positions;
  37228. vertexData.normals = normals;
  37229. vertexData.uvs = uvs;
  37230. return vertexData;
  37231. };
  37232. /**
  37233. * Creates the VertexData of the Disc or regular Polygon
  37234. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37235. * * radius the radius of the disc, optional default 0.5
  37236. * * tessellation the number of polygon sides, optional, default 64
  37237. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37238. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37239. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37240. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37241. * @returns the VertexData of the box
  37242. */
  37243. VertexData.CreateDisc = function (options) {
  37244. var positions = new Array();
  37245. var indices = new Array();
  37246. var normals = new Array();
  37247. var uvs = new Array();
  37248. var radius = options.radius || 0.5;
  37249. var tessellation = options.tessellation || 64;
  37250. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37251. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37252. // positions and uvs
  37253. positions.push(0, 0, 0); // disc center first
  37254. uvs.push(0.5, 0.5);
  37255. var theta = Math.PI * 2 * arc;
  37256. var step = theta / tessellation;
  37257. for (var a = 0; a < theta; a += step) {
  37258. var x = Math.cos(a);
  37259. var y = Math.sin(a);
  37260. var u = (x + 1) / 2;
  37261. var v = (1 - y) / 2;
  37262. positions.push(radius * x, radius * y, 0);
  37263. uvs.push(u, v);
  37264. }
  37265. if (arc === 1) {
  37266. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37267. uvs.push(uvs[2], uvs[3]);
  37268. }
  37269. //indices
  37270. var vertexNb = positions.length / 3;
  37271. for (var i = 1; i < vertexNb - 1; i++) {
  37272. indices.push(i + 1, 0, i);
  37273. }
  37274. // result
  37275. VertexData.ComputeNormals(positions, indices, normals);
  37276. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37277. var vertexData = new VertexData();
  37278. vertexData.indices = indices;
  37279. vertexData.positions = positions;
  37280. vertexData.normals = normals;
  37281. vertexData.uvs = uvs;
  37282. return vertexData;
  37283. };
  37284. /**
  37285. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37286. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37287. * @param polygon a mesh built from polygonTriangulation.build()
  37288. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37289. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37290. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37291. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37292. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37293. * @returns the VertexData of the Polygon
  37294. */
  37295. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37296. var faceUV = fUV || new Array(3);
  37297. var faceColors = fColors;
  37298. var colors = [];
  37299. // default face colors and UV if undefined
  37300. for (var f = 0; f < 3; f++) {
  37301. if (faceUV[f] === undefined) {
  37302. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37303. }
  37304. if (faceColors && faceColors[f] === undefined) {
  37305. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37306. }
  37307. }
  37308. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37309. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37310. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37311. var indices = polygon.getIndices();
  37312. // set face colours and textures
  37313. var idx = 0;
  37314. var face = 0;
  37315. for (var index = 0; index < normals.length; index += 3) {
  37316. //Edge Face no. 1
  37317. if (Math.abs(normals[index + 1]) < 0.001) {
  37318. face = 1;
  37319. }
  37320. //Top Face no. 0
  37321. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37322. face = 0;
  37323. }
  37324. //Bottom Face no. 2
  37325. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37326. face = 2;
  37327. }
  37328. idx = index / 3;
  37329. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37330. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37331. if (faceColors) {
  37332. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37333. }
  37334. }
  37335. // sides
  37336. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37337. // Result
  37338. var vertexData = new VertexData();
  37339. vertexData.indices = indices;
  37340. vertexData.positions = positions;
  37341. vertexData.normals = normals;
  37342. vertexData.uvs = uvs;
  37343. if (faceColors) {
  37344. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37345. vertexData.colors = totalColors;
  37346. }
  37347. return vertexData;
  37348. };
  37349. /**
  37350. * Creates the VertexData of the IcoSphere
  37351. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37352. * * radius the radius of the IcoSphere, optional default 1
  37353. * * radiusX allows stretching in the x direction, optional, default radius
  37354. * * radiusY allows stretching in the y direction, optional, default radius
  37355. * * radiusZ allows stretching in the z direction, optional, default radius
  37356. * * flat when true creates a flat shaded mesh, optional, default true
  37357. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37358. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37359. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37360. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37361. * @returns the VertexData of the IcoSphere
  37362. */
  37363. VertexData.CreateIcoSphere = function (options) {
  37364. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37365. var radius = options.radius || 1;
  37366. var flat = (options.flat === undefined) ? true : options.flat;
  37367. var subdivisions = options.subdivisions || 4;
  37368. var radiusX = options.radiusX || radius;
  37369. var radiusY = options.radiusY || radius;
  37370. var radiusZ = options.radiusZ || radius;
  37371. var t = (1 + Math.sqrt(5)) / 2;
  37372. // 12 vertex x,y,z
  37373. var ico_vertices = [
  37374. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37375. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37376. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37377. ];
  37378. // index of 3 vertex makes a face of icopshere
  37379. var ico_indices = [
  37380. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37381. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37382. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37383. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37384. ];
  37385. // vertex for uv have aliased position, not for UV
  37386. var vertices_unalias_id = [
  37387. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37388. // vertex alias
  37389. 0,
  37390. 2,
  37391. 3,
  37392. 3,
  37393. 3,
  37394. 4,
  37395. 7,
  37396. 8,
  37397. 9,
  37398. 9,
  37399. 10,
  37400. 11 // 23: B + 12
  37401. ];
  37402. // uv as integer step (not pixels !)
  37403. var ico_vertexuv = [
  37404. 5, 1, 3, 1, 6, 4, 0, 0,
  37405. 5, 3, 4, 2, 2, 2, 4, 0,
  37406. 2, 0, 1, 1, 6, 0, 6, 2,
  37407. // vertex alias (for same vertex on different faces)
  37408. 0, 4,
  37409. 3, 3,
  37410. 4, 4,
  37411. 3, 1,
  37412. 4, 2,
  37413. 4, 4,
  37414. 0, 2,
  37415. 1, 1,
  37416. 2, 2,
  37417. 3, 3,
  37418. 1, 3,
  37419. 2, 4 // 23: B + 12
  37420. ];
  37421. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37422. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37423. // First island of uv mapping
  37424. // v = 4h 3+ 2
  37425. // v = 3h 9+ 4
  37426. // v = 2h 9+ 5 B
  37427. // v = 1h 9 1 0
  37428. // v = 0h 3 8 7 A
  37429. // u = 0 1 2 3 4 5 6 *a
  37430. // Second island of uv mapping
  37431. // v = 4h 0+ B+ 4+
  37432. // v = 3h A+ 2+
  37433. // v = 2h 7+ 6 3+
  37434. // v = 1h 8+ 3+
  37435. // v = 0h
  37436. // u = 0 1 2 3 4 5 6 *a
  37437. // Face layout on texture UV mapping
  37438. // ============
  37439. // \ 4 /\ 16 / ======
  37440. // \ / \ / /\ 11 /
  37441. // \/ 7 \/ / \ /
  37442. // ======= / 10 \/
  37443. // /\ 17 /\ =======
  37444. // / \ / \ \ 15 /\
  37445. // / 8 \/ 12 \ \ / \
  37446. // ============ \/ 6 \
  37447. // \ 18 /\ ============
  37448. // \ / \ \ 5 /\ 0 /
  37449. // \/ 13 \ \ / \ /
  37450. // ======= \/ 1 \/
  37451. // =============
  37452. // /\ 19 /\ 2 /\
  37453. // / \ / \ / \
  37454. // / 14 \/ 9 \/ 3 \
  37455. // ===================
  37456. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37457. var ustep = 138 / 1024;
  37458. var vstep = 239 / 1024;
  37459. var uoffset = 60 / 1024;
  37460. var voffset = 26 / 1024;
  37461. // Second island should have margin, not to touch the first island
  37462. // avoid any borderline artefact in pixel rounding
  37463. var island_u_offset = -40 / 1024;
  37464. var island_v_offset = +20 / 1024;
  37465. // face is either island 0 or 1 :
  37466. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37467. var island = [
  37468. 0, 0, 0, 0, 1,
  37469. 0, 0, 1, 1, 0,
  37470. 0, 0, 1, 1, 0,
  37471. 0, 1, 1, 1, 0 // 15 - 19
  37472. ];
  37473. var indices = new Array();
  37474. var positions = new Array();
  37475. var normals = new Array();
  37476. var uvs = new Array();
  37477. var current_indice = 0;
  37478. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37479. var face_vertex_pos = new Array(3);
  37480. var face_vertex_uv = new Array(3);
  37481. var v012;
  37482. for (v012 = 0; v012 < 3; v012++) {
  37483. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37484. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37485. }
  37486. // create all with normals
  37487. for (var face = 0; face < 20; face++) {
  37488. // 3 vertex per face
  37489. for (v012 = 0; v012 < 3; v012++) {
  37490. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37491. var v_id = ico_indices[3 * face + v012];
  37492. // vertex have 3D position (x,y,z)
  37493. 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]);
  37494. // Normalize to get normal, then scale to radius
  37495. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37496. // uv Coordinates from vertex ID
  37497. 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);
  37498. }
  37499. // Subdivide the face (interpolate pos, norm, uv)
  37500. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37501. // - norm is linear interpolation of vertex corner normal
  37502. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37503. // - uv is linear interpolation
  37504. //
  37505. // Topology is as below for sub-divide by 2
  37506. // vertex shown as v0,v1,v2
  37507. // interp index is i1 to progress in range [v0,v1[
  37508. // interp index is i2 to progress in range [v0,v2[
  37509. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37510. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37511. //
  37512. //
  37513. // i2 v2
  37514. // ^ ^
  37515. // / / \
  37516. // / / \
  37517. // / / \
  37518. // / / (0,1) \
  37519. // / #---------\
  37520. // / / \ (0,0)'/ \
  37521. // / / \ / \
  37522. // / / \ / \
  37523. // / / (0,0) \ / (1,0) \
  37524. // / #---------#---------\
  37525. // v0 v1
  37526. //
  37527. // --------------------> i1
  37528. //
  37529. // interp of (i1,i2):
  37530. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37531. // along i1 : lerp(x0,x1, i1/(S-i2))
  37532. //
  37533. // centroid of triangle is needed to get help normal computation
  37534. // (c1,c2) are used for centroid location
  37535. var interp_vertex = function (i1, i2, c1, c2) {
  37536. // vertex is interpolated from
  37537. // - face_vertex_pos[0..2]
  37538. // - face_vertex_uv[0..2]
  37539. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37540. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37541. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37542. pos_interp.normalize();
  37543. var vertex_normal;
  37544. if (flat) {
  37545. // in flat mode, recalculate normal as face centroid normal
  37546. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37547. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37548. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37549. }
  37550. else {
  37551. // in smooth mode, recalculate normal from each single vertex position
  37552. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37553. }
  37554. // Vertex normal need correction due to X,Y,Z radius scaling
  37555. vertex_normal.x /= radiusX;
  37556. vertex_normal.y /= radiusY;
  37557. vertex_normal.z /= radiusZ;
  37558. vertex_normal.normalize();
  37559. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37560. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37561. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37562. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37563. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37564. uvs.push(uv_interp.x, uv_interp.y);
  37565. // push each vertex has member of a face
  37566. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37567. indices.push(current_indice);
  37568. current_indice++;
  37569. };
  37570. for (var i2 = 0; i2 < subdivisions; i2++) {
  37571. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37572. // face : (i1,i2) for /\ :
  37573. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37574. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37575. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37576. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37577. if (i1 + i2 + 1 < subdivisions) {
  37578. // face : (i1,i2)' for \/ :
  37579. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37580. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37581. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37582. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37583. }
  37584. }
  37585. }
  37586. }
  37587. // Sides
  37588. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37589. // Result
  37590. var vertexData = new VertexData();
  37591. vertexData.indices = indices;
  37592. vertexData.positions = positions;
  37593. vertexData.normals = normals;
  37594. vertexData.uvs = uvs;
  37595. return vertexData;
  37596. };
  37597. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37598. /**
  37599. * Creates the VertexData for a Polyhedron
  37600. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37601. * * type provided types are:
  37602. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37603. * * 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)
  37604. * * size the size of the IcoSphere, optional default 1
  37605. * * sizeX allows stretching in the x direction, optional, default size
  37606. * * sizeY allows stretching in the y direction, optional, default size
  37607. * * sizeZ allows stretching in the z direction, optional, default size
  37608. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  37609. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37610. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37611. * * flat when true creates a flat shaded mesh, optional, default true
  37612. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37613. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37614. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37615. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37616. * @returns the VertexData of the Polyhedron
  37617. */
  37618. VertexData.CreatePolyhedron = function (options) {
  37619. // provided polyhedron types :
  37620. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37621. // 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)
  37622. var polyhedra = [];
  37623. 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]] };
  37624. 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]] };
  37625. polyhedra[2] = {
  37626. 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]],
  37627. 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]]
  37628. };
  37629. polyhedra[3] = {
  37630. 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]],
  37631. 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]]
  37632. };
  37633. polyhedra[4] = {
  37634. 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]],
  37635. 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]]
  37636. };
  37637. 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]] };
  37638. 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]] };
  37639. 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]] };
  37640. 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]] };
  37641. 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]] };
  37642. 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]] };
  37643. 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]] };
  37644. 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]] };
  37645. 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]] };
  37646. polyhedra[14] = {
  37647. 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]],
  37648. 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]]
  37649. };
  37650. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37651. var size = options.size;
  37652. var sizeX = options.sizeX || size || 1;
  37653. var sizeY = options.sizeY || size || 1;
  37654. var sizeZ = options.sizeZ || size || 1;
  37655. var data = options.custom || polyhedra[type];
  37656. var nbfaces = data.face.length;
  37657. var faceUV = options.faceUV || new Array(nbfaces);
  37658. var faceColors = options.faceColors;
  37659. var flat = (options.flat === undefined) ? true : options.flat;
  37660. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37661. var positions = new Array();
  37662. var indices = new Array();
  37663. var normals = new Array();
  37664. var uvs = new Array();
  37665. var colors = new Array();
  37666. var index = 0;
  37667. var faceIdx = 0; // face cursor in the array "indexes"
  37668. var indexes = new Array();
  37669. var i = 0;
  37670. var f = 0;
  37671. var u, v, ang, x, y, tmp;
  37672. // default face colors and UV if undefined
  37673. if (flat) {
  37674. for (f = 0; f < nbfaces; f++) {
  37675. if (faceColors && faceColors[f] === undefined) {
  37676. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37677. }
  37678. if (faceUV && faceUV[f] === undefined) {
  37679. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37680. }
  37681. }
  37682. }
  37683. if (!flat) {
  37684. for (i = 0; i < data.vertex.length; i++) {
  37685. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37686. uvs.push(0, 0);
  37687. }
  37688. for (f = 0; f < nbfaces; f++) {
  37689. for (i = 0; i < data.face[f].length - 2; i++) {
  37690. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37691. }
  37692. }
  37693. }
  37694. else {
  37695. for (f = 0; f < nbfaces; f++) {
  37696. var fl = data.face[f].length; // number of vertices of the current face
  37697. ang = 2 * Math.PI / fl;
  37698. x = 0.5 * Math.tan(ang / 2);
  37699. y = 0.5;
  37700. // positions, uvs, colors
  37701. for (i = 0; i < fl; i++) {
  37702. // positions
  37703. 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);
  37704. indexes.push(index);
  37705. index++;
  37706. // uvs
  37707. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37708. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37709. uvs.push(u, v);
  37710. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37711. y = x * Math.sin(ang) + y * Math.cos(ang);
  37712. x = tmp;
  37713. // colors
  37714. if (faceColors) {
  37715. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37716. }
  37717. }
  37718. // indices from indexes
  37719. for (i = 0; i < fl - 2; i++) {
  37720. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37721. }
  37722. faceIdx += fl;
  37723. }
  37724. }
  37725. VertexData.ComputeNormals(positions, indices, normals);
  37726. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37727. var vertexData = new VertexData();
  37728. vertexData.positions = positions;
  37729. vertexData.indices = indices;
  37730. vertexData.normals = normals;
  37731. vertexData.uvs = uvs;
  37732. if (faceColors && flat) {
  37733. vertexData.colors = colors;
  37734. }
  37735. return vertexData;
  37736. };
  37737. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37738. /**
  37739. * Creates the VertexData for a TorusKnot
  37740. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37741. * * radius the radius of the torus knot, optional, default 2
  37742. * * tube the thickness of the tube, optional, default 0.5
  37743. * * radialSegments the number of sides on each tube segments, optional, default 32
  37744. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37745. * * p the number of windings around the z axis, optional, default 2
  37746. * * q the number of windings around the x axis, optional, default 3
  37747. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37748. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37749. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37750. * @returns the VertexData of the Torus Knot
  37751. */
  37752. VertexData.CreateTorusKnot = function (options) {
  37753. var indices = new Array();
  37754. var positions = new Array();
  37755. var normals = new Array();
  37756. var uvs = new Array();
  37757. var radius = options.radius || 2;
  37758. var tube = options.tube || 0.5;
  37759. var radialSegments = options.radialSegments || 32;
  37760. var tubularSegments = options.tubularSegments || 32;
  37761. var p = options.p || 2;
  37762. var q = options.q || 3;
  37763. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37764. // Helper
  37765. var getPos = function (angle) {
  37766. var cu = Math.cos(angle);
  37767. var su = Math.sin(angle);
  37768. var quOverP = q / p * angle;
  37769. var cs = Math.cos(quOverP);
  37770. var tx = radius * (2 + cs) * 0.5 * cu;
  37771. var ty = radius * (2 + cs) * su * 0.5;
  37772. var tz = radius * Math.sin(quOverP) * 0.5;
  37773. return new BABYLON.Vector3(tx, ty, tz);
  37774. };
  37775. // Vertices
  37776. var i;
  37777. var j;
  37778. for (i = 0; i <= radialSegments; i++) {
  37779. var modI = i % radialSegments;
  37780. var u = modI / radialSegments * 2 * p * Math.PI;
  37781. var p1 = getPos(u);
  37782. var p2 = getPos(u + 0.01);
  37783. var tang = p2.subtract(p1);
  37784. var n = p2.add(p1);
  37785. var bitan = BABYLON.Vector3.Cross(tang, n);
  37786. n = BABYLON.Vector3.Cross(bitan, tang);
  37787. bitan.normalize();
  37788. n.normalize();
  37789. for (j = 0; j < tubularSegments; j++) {
  37790. var modJ = j % tubularSegments;
  37791. var v = modJ / tubularSegments * 2 * Math.PI;
  37792. var cx = -tube * Math.cos(v);
  37793. var cy = tube * Math.sin(v);
  37794. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37795. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37796. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37797. uvs.push(i / radialSegments);
  37798. uvs.push(j / tubularSegments);
  37799. }
  37800. }
  37801. for (i = 0; i < radialSegments; i++) {
  37802. for (j = 0; j < tubularSegments; j++) {
  37803. var jNext = (j + 1) % tubularSegments;
  37804. var a = i * tubularSegments + j;
  37805. var b = (i + 1) * tubularSegments + j;
  37806. var c = (i + 1) * tubularSegments + jNext;
  37807. var d = i * tubularSegments + jNext;
  37808. indices.push(d);
  37809. indices.push(b);
  37810. indices.push(a);
  37811. indices.push(d);
  37812. indices.push(c);
  37813. indices.push(b);
  37814. }
  37815. }
  37816. // Normals
  37817. VertexData.ComputeNormals(positions, indices, normals);
  37818. // Sides
  37819. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37820. // Result
  37821. var vertexData = new VertexData();
  37822. vertexData.indices = indices;
  37823. vertexData.positions = positions;
  37824. vertexData.normals = normals;
  37825. vertexData.uvs = uvs;
  37826. return vertexData;
  37827. };
  37828. // Tools
  37829. /**
  37830. * Compute normals for given positions and indices
  37831. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37832. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37833. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37834. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37835. * * facetNormals : optional array of facet normals (vector3)
  37836. * * facetPositions : optional array of facet positions (vector3)
  37837. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37838. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37839. * * bInfo : optional bounding info, required for facetPartitioning computation
  37840. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37841. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37842. * * useRightHandedSystem: optional boolean to for right handed system computation
  37843. * * depthSort : optional boolean to enable the facet depth sort computation
  37844. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37845. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37846. */
  37847. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37848. // temporary scalar variables
  37849. var index = 0; // facet index
  37850. var p1p2x = 0.0; // p1p2 vector x coordinate
  37851. var p1p2y = 0.0; // p1p2 vector y coordinate
  37852. var p1p2z = 0.0; // p1p2 vector z coordinate
  37853. var p3p2x = 0.0; // p3p2 vector x coordinate
  37854. var p3p2y = 0.0; // p3p2 vector y coordinate
  37855. var p3p2z = 0.0; // p3p2 vector z coordinate
  37856. var faceNormalx = 0.0; // facet normal x coordinate
  37857. var faceNormaly = 0.0; // facet normal y coordinate
  37858. var faceNormalz = 0.0; // facet normal z coordinate
  37859. var length = 0.0; // facet normal length before normalization
  37860. var v1x = 0; // vector1 x index in the positions array
  37861. var v1y = 0; // vector1 y index in the positions array
  37862. var v1z = 0; // vector1 z index in the positions array
  37863. var v2x = 0; // vector2 x index in the positions array
  37864. var v2y = 0; // vector2 y index in the positions array
  37865. var v2z = 0; // vector2 z index in the positions array
  37866. var v3x = 0; // vector3 x index in the positions array
  37867. var v3y = 0; // vector3 y index in the positions array
  37868. var v3z = 0; // vector3 z index in the positions array
  37869. var computeFacetNormals = false;
  37870. var computeFacetPositions = false;
  37871. var computeFacetPartitioning = false;
  37872. var computeDepthSort = false;
  37873. var faceNormalSign = 1;
  37874. var ratio = 0;
  37875. var distanceTo = null;
  37876. if (options) {
  37877. computeFacetNormals = (options.facetNormals) ? true : false;
  37878. computeFacetPositions = (options.facetPositions) ? true : false;
  37879. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37880. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37881. ratio = options.ratio || 0;
  37882. computeDepthSort = (options.depthSort) ? true : false;
  37883. distanceTo = (options.distanceTo);
  37884. if (computeDepthSort) {
  37885. if (distanceTo === undefined) {
  37886. distanceTo = BABYLON.Vector3.Zero();
  37887. }
  37888. var depthSortedFacets = options.depthSortedFacets;
  37889. }
  37890. }
  37891. // facetPartitioning reinit if needed
  37892. var xSubRatio = 0;
  37893. var ySubRatio = 0;
  37894. var zSubRatio = 0;
  37895. var subSq = 0;
  37896. if (computeFacetPartitioning && options && options.bbSize) {
  37897. var ox = 0; // X partitioning index for facet position
  37898. var oy = 0; // Y partinioning index for facet position
  37899. var oz = 0; // Z partinioning index for facet position
  37900. var b1x = 0; // X partitioning index for facet v1 vertex
  37901. var b1y = 0; // Y partitioning index for facet v1 vertex
  37902. var b1z = 0; // z partitioning index for facet v1 vertex
  37903. var b2x = 0; // X partitioning index for facet v2 vertex
  37904. var b2y = 0; // Y partitioning index for facet v2 vertex
  37905. var b2z = 0; // Z partitioning index for facet v2 vertex
  37906. var b3x = 0; // X partitioning index for facet v3 vertex
  37907. var b3y = 0; // Y partitioning index for facet v3 vertex
  37908. var b3z = 0; // Z partitioning index for facet v3 vertex
  37909. var block_idx_o = 0; // facet barycenter block index
  37910. var block_idx_v1 = 0; // v1 vertex block index
  37911. var block_idx_v2 = 0; // v2 vertex block index
  37912. var block_idx_v3 = 0; // v3 vertex block index
  37913. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37914. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37915. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37916. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37917. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37918. subSq = options.subDiv.max * options.subDiv.max;
  37919. options.facetPartitioning.length = 0;
  37920. }
  37921. // reset the normals
  37922. for (index = 0; index < positions.length; index++) {
  37923. normals[index] = 0.0;
  37924. }
  37925. // Loop : 1 indice triplet = 1 facet
  37926. var nbFaces = (indices.length / 3) | 0;
  37927. for (index = 0; index < nbFaces; index++) {
  37928. // get the indexes of the coordinates of each vertex of the facet
  37929. v1x = indices[index * 3] * 3;
  37930. v1y = v1x + 1;
  37931. v1z = v1x + 2;
  37932. v2x = indices[index * 3 + 1] * 3;
  37933. v2y = v2x + 1;
  37934. v2z = v2x + 2;
  37935. v3x = indices[index * 3 + 2] * 3;
  37936. v3y = v3x + 1;
  37937. v3z = v3x + 2;
  37938. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37939. p1p2y = positions[v1y] - positions[v2y];
  37940. p1p2z = positions[v1z] - positions[v2z];
  37941. p3p2x = positions[v3x] - positions[v2x];
  37942. p3p2y = positions[v3y] - positions[v2y];
  37943. p3p2z = positions[v3z] - positions[v2z];
  37944. // compute the face normal with the cross product
  37945. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37946. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37947. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37948. // normalize this normal and store it in the array facetData
  37949. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37950. length = (length === 0) ? 1.0 : length;
  37951. faceNormalx /= length;
  37952. faceNormaly /= length;
  37953. faceNormalz /= length;
  37954. if (computeFacetNormals && options) {
  37955. options.facetNormals[index].x = faceNormalx;
  37956. options.facetNormals[index].y = faceNormaly;
  37957. options.facetNormals[index].z = faceNormalz;
  37958. }
  37959. if (computeFacetPositions && options) {
  37960. // compute and the facet barycenter coordinates in the array facetPositions
  37961. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37962. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37963. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37964. }
  37965. if (computeFacetPartitioning && options) {
  37966. // store the facet indexes in arrays in the main facetPartitioning array :
  37967. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37968. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37969. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37970. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37971. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37972. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37973. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37974. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37975. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37976. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37977. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37978. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37979. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37980. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37981. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37982. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37983. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37984. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37985. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37986. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37987. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37988. // push each facet index in each block containing the vertex
  37989. options.facetPartitioning[block_idx_v1].push(index);
  37990. if (block_idx_v2 != block_idx_v1) {
  37991. options.facetPartitioning[block_idx_v2].push(index);
  37992. }
  37993. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37994. options.facetPartitioning[block_idx_v3].push(index);
  37995. }
  37996. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37997. options.facetPartitioning[block_idx_o].push(index);
  37998. }
  37999. }
  38000. if (computeDepthSort && options && options.facetPositions) {
  38001. var dsf = depthSortedFacets[index];
  38002. dsf.ind = index * 3;
  38003. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38004. }
  38005. // compute the normals anyway
  38006. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38007. normals[v1y] += faceNormaly;
  38008. normals[v1z] += faceNormalz;
  38009. normals[v2x] += faceNormalx;
  38010. normals[v2y] += faceNormaly;
  38011. normals[v2z] += faceNormalz;
  38012. normals[v3x] += faceNormalx;
  38013. normals[v3y] += faceNormaly;
  38014. normals[v3z] += faceNormalz;
  38015. }
  38016. // last normalization of each normal
  38017. for (index = 0; index < normals.length / 3; index++) {
  38018. faceNormalx = normals[index * 3];
  38019. faceNormaly = normals[index * 3 + 1];
  38020. faceNormalz = normals[index * 3 + 2];
  38021. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38022. length = (length === 0) ? 1.0 : length;
  38023. faceNormalx /= length;
  38024. faceNormaly /= length;
  38025. faceNormalz /= length;
  38026. normals[index * 3] = faceNormalx;
  38027. normals[index * 3 + 1] = faceNormaly;
  38028. normals[index * 3 + 2] = faceNormalz;
  38029. }
  38030. };
  38031. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38032. var li = indices.length;
  38033. var ln = normals.length;
  38034. var i;
  38035. var n;
  38036. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38037. switch (sideOrientation) {
  38038. case BABYLON.Mesh.FRONTSIDE:
  38039. // nothing changed
  38040. break;
  38041. case BABYLON.Mesh.BACKSIDE:
  38042. var tmp;
  38043. // indices
  38044. for (i = 0; i < li; i += 3) {
  38045. tmp = indices[i];
  38046. indices[i] = indices[i + 2];
  38047. indices[i + 2] = tmp;
  38048. }
  38049. // normals
  38050. for (n = 0; n < ln; n++) {
  38051. normals[n] = -normals[n];
  38052. }
  38053. break;
  38054. case BABYLON.Mesh.DOUBLESIDE:
  38055. // positions
  38056. var lp = positions.length;
  38057. var l = lp / 3;
  38058. for (var p = 0; p < lp; p++) {
  38059. positions[lp + p] = positions[p];
  38060. }
  38061. // indices
  38062. for (i = 0; i < li; i += 3) {
  38063. indices[i + li] = indices[i + 2] + l;
  38064. indices[i + 1 + li] = indices[i + 1] + l;
  38065. indices[i + 2 + li] = indices[i] + l;
  38066. }
  38067. // normals
  38068. for (n = 0; n < ln; n++) {
  38069. normals[ln + n] = -normals[n];
  38070. }
  38071. // uvs
  38072. var lu = uvs.length;
  38073. var u = 0;
  38074. for (u = 0; u < lu; u++) {
  38075. uvs[u + lu] = uvs[u];
  38076. }
  38077. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38078. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38079. u = 0;
  38080. for (i = 0; i < lu / 2; i++) {
  38081. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38082. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38083. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38084. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38085. u += 2;
  38086. }
  38087. break;
  38088. }
  38089. };
  38090. /**
  38091. * Applies VertexData created from the imported parameters to the geometry
  38092. * @param parsedVertexData the parsed data from an imported file
  38093. * @param geometry the geometry to apply the VertexData to
  38094. */
  38095. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38096. var vertexData = new VertexData();
  38097. // positions
  38098. var positions = parsedVertexData.positions;
  38099. if (positions) {
  38100. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38101. }
  38102. // normals
  38103. var normals = parsedVertexData.normals;
  38104. if (normals) {
  38105. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38106. }
  38107. // tangents
  38108. var tangents = parsedVertexData.tangents;
  38109. if (tangents) {
  38110. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38111. }
  38112. // uvs
  38113. var uvs = parsedVertexData.uvs;
  38114. if (uvs) {
  38115. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38116. }
  38117. // uv2s
  38118. var uv2s = parsedVertexData.uv2s;
  38119. if (uv2s) {
  38120. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38121. }
  38122. // uv3s
  38123. var uv3s = parsedVertexData.uv3s;
  38124. if (uv3s) {
  38125. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38126. }
  38127. // uv4s
  38128. var uv4s = parsedVertexData.uv4s;
  38129. if (uv4s) {
  38130. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38131. }
  38132. // uv5s
  38133. var uv5s = parsedVertexData.uv5s;
  38134. if (uv5s) {
  38135. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38136. }
  38137. // uv6s
  38138. var uv6s = parsedVertexData.uv6s;
  38139. if (uv6s) {
  38140. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38141. }
  38142. // colors
  38143. var colors = parsedVertexData.colors;
  38144. if (colors) {
  38145. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38146. }
  38147. // matricesIndices
  38148. var matricesIndices = parsedVertexData.matricesIndices;
  38149. if (matricesIndices) {
  38150. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38151. }
  38152. // matricesWeights
  38153. var matricesWeights = parsedVertexData.matricesWeights;
  38154. if (matricesWeights) {
  38155. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38156. }
  38157. // indices
  38158. var indices = parsedVertexData.indices;
  38159. if (indices) {
  38160. vertexData.indices = indices;
  38161. }
  38162. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38163. };
  38164. return VertexData;
  38165. }());
  38166. BABYLON.VertexData = VertexData;
  38167. })(BABYLON || (BABYLON = {}));
  38168. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38169. var BABYLON;
  38170. (function (BABYLON) {
  38171. /**
  38172. * Class used to store geometry data (vertex buffers + index buffer)
  38173. */
  38174. var Geometry = /** @class */ (function () {
  38175. /**
  38176. * Creates a new geometry
  38177. * @param id defines the unique ID
  38178. * @param scene defines the hosting scene
  38179. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38180. * @param updatable defines if geometry must be updatable (false by default)
  38181. * @param mesh defines the mesh that will be associated with the geometry
  38182. */
  38183. function Geometry(id, scene, vertexData, updatable, mesh) {
  38184. if (updatable === void 0) { updatable = false; }
  38185. if (mesh === void 0) { mesh = null; }
  38186. /**
  38187. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38188. */
  38189. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38190. this._totalVertices = 0;
  38191. this._isDisposed = false;
  38192. this._indexBufferIsUpdatable = false;
  38193. this.id = id;
  38194. this._engine = scene.getEngine();
  38195. this._meshes = [];
  38196. this._scene = scene;
  38197. //Init vertex buffer cache
  38198. this._vertexBuffers = {};
  38199. this._indices = [];
  38200. this._updatable = updatable;
  38201. // vertexData
  38202. if (vertexData) {
  38203. this.setAllVerticesData(vertexData, updatable);
  38204. }
  38205. else {
  38206. this._totalVertices = 0;
  38207. this._indices = [];
  38208. }
  38209. if (this._engine.getCaps().vertexArrayObject) {
  38210. this._vertexArrayObjects = {};
  38211. }
  38212. // applyToMesh
  38213. if (mesh) {
  38214. if (mesh.getClassName() === "LinesMesh") {
  38215. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38216. this._updateExtend();
  38217. }
  38218. this.applyToMesh(mesh);
  38219. mesh.computeWorldMatrix(true);
  38220. }
  38221. }
  38222. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38223. /**
  38224. * 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
  38225. */
  38226. get: function () {
  38227. return this._boundingBias;
  38228. },
  38229. /**
  38230. * 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
  38231. */
  38232. set: function (value) {
  38233. if (this._boundingBias && this._boundingBias.equals(value)) {
  38234. return;
  38235. }
  38236. this._boundingBias = value.clone();
  38237. this._updateBoundingInfo(true, null);
  38238. },
  38239. enumerable: true,
  38240. configurable: true
  38241. });
  38242. /**
  38243. * Static function used to attach a new empty geometry to a mesh
  38244. * @param mesh defines the mesh to attach the geometry to
  38245. * @returns the new {BABYLON.Geometry}
  38246. */
  38247. Geometry.CreateGeometryForMesh = function (mesh) {
  38248. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38249. geometry.applyToMesh(mesh);
  38250. return geometry;
  38251. };
  38252. Object.defineProperty(Geometry.prototype, "extend", {
  38253. /**
  38254. * Gets the current extend of the geometry
  38255. */
  38256. get: function () {
  38257. return this._extend;
  38258. },
  38259. enumerable: true,
  38260. configurable: true
  38261. });
  38262. /**
  38263. * Gets the hosting scene
  38264. * @returns the hosting {BABYLON.Scene}
  38265. */
  38266. Geometry.prototype.getScene = function () {
  38267. return this._scene;
  38268. };
  38269. /**
  38270. * Gets the hosting engine
  38271. * @returns the hosting {BABYLON.Engine}
  38272. */
  38273. Geometry.prototype.getEngine = function () {
  38274. return this._engine;
  38275. };
  38276. /**
  38277. * Defines if the geometry is ready to use
  38278. * @returns true if the geometry is ready to be used
  38279. */
  38280. Geometry.prototype.isReady = function () {
  38281. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38282. };
  38283. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38284. /**
  38285. * Gets a value indicating that the geometry should not be serialized
  38286. */
  38287. get: function () {
  38288. for (var index = 0; index < this._meshes.length; index++) {
  38289. if (!this._meshes[index].doNotSerialize) {
  38290. return false;
  38291. }
  38292. }
  38293. return true;
  38294. },
  38295. enumerable: true,
  38296. configurable: true
  38297. });
  38298. /** @ignore */
  38299. Geometry.prototype._rebuild = function () {
  38300. if (this._vertexArrayObjects) {
  38301. this._vertexArrayObjects = {};
  38302. }
  38303. // Index buffer
  38304. if (this._meshes.length !== 0 && this._indices) {
  38305. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38306. }
  38307. // Vertex buffers
  38308. for (var key in this._vertexBuffers) {
  38309. var vertexBuffer = this._vertexBuffers[key];
  38310. vertexBuffer._rebuild();
  38311. }
  38312. };
  38313. /**
  38314. * Affects all gemetry data in one call
  38315. * @param vertexData defines the geometry data
  38316. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38317. */
  38318. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38319. vertexData.applyToGeometry(this, updatable);
  38320. this.notifyUpdate();
  38321. };
  38322. /**
  38323. * Set specific vertex data
  38324. * @param kind defines the data kind (Position, normal, etc...)
  38325. * @param data defines the vertex data to use
  38326. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38327. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38328. */
  38329. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38330. if (updatable === void 0) { updatable = false; }
  38331. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38332. this.setVerticesBuffer(buffer);
  38333. };
  38334. /**
  38335. * Removes a specific vertex data
  38336. * @param kind defines the data kind (Position, normal, etc...)
  38337. */
  38338. Geometry.prototype.removeVerticesData = function (kind) {
  38339. if (this._vertexBuffers[kind]) {
  38340. this._vertexBuffers[kind].dispose();
  38341. delete this._vertexBuffers[kind];
  38342. }
  38343. };
  38344. /**
  38345. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38346. * @param buffer defines the vertex buffer to use
  38347. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38348. */
  38349. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38350. if (totalVertices === void 0) { totalVertices = null; }
  38351. var kind = buffer.getKind();
  38352. if (this._vertexBuffers[kind]) {
  38353. this._vertexBuffers[kind].dispose();
  38354. }
  38355. this._vertexBuffers[kind] = buffer;
  38356. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38357. var data = buffer.getData();
  38358. if (totalVertices != null) {
  38359. this._totalVertices = totalVertices;
  38360. }
  38361. else {
  38362. if (data != null) {
  38363. this._totalVertices = data.length / (buffer.byteStride / 4);
  38364. }
  38365. }
  38366. this._updateExtend(data);
  38367. this._resetPointsArrayCache();
  38368. var meshes = this._meshes;
  38369. var numOfMeshes = meshes.length;
  38370. for (var index = 0; index < numOfMeshes; index++) {
  38371. var mesh = meshes[index];
  38372. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38373. mesh._createGlobalSubMesh(false);
  38374. mesh.computeWorldMatrix(true);
  38375. }
  38376. }
  38377. this.notifyUpdate(kind);
  38378. if (this._vertexArrayObjects) {
  38379. this._disposeVertexArrayObjects();
  38380. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38381. }
  38382. };
  38383. /**
  38384. * Update a specific vertex buffer
  38385. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38386. * It will do nothing if the buffer is not updatable
  38387. * @param kind defines the data kind (Position, normal, etc...)
  38388. * @param data defines the data to use
  38389. * @param offset defines the offset in the target buffer where to store the data
  38390. * @param useBytes set to true if the offset is in bytes
  38391. */
  38392. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38393. if (useBytes === void 0) { useBytes = false; }
  38394. var vertexBuffer = this.getVertexBuffer(kind);
  38395. if (!vertexBuffer) {
  38396. return;
  38397. }
  38398. vertexBuffer.updateDirectly(data, offset, useBytes);
  38399. this.notifyUpdate(kind);
  38400. };
  38401. /**
  38402. * Update a specific vertex buffer
  38403. * This function will create a new buffer if the current one is not updatable
  38404. * @param kind defines the data kind (Position, normal, etc...)
  38405. * @param data defines the data to use
  38406. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38407. */
  38408. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38409. if (updateExtends === void 0) { updateExtends = false; }
  38410. var vertexBuffer = this.getVertexBuffer(kind);
  38411. if (!vertexBuffer) {
  38412. return;
  38413. }
  38414. vertexBuffer.update(data);
  38415. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38416. this._updateBoundingInfo(updateExtends, data);
  38417. }
  38418. this.notifyUpdate(kind);
  38419. };
  38420. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38421. if (updateExtends) {
  38422. this._updateExtend(data);
  38423. }
  38424. var meshes = this._meshes;
  38425. var numOfMeshes = meshes.length;
  38426. this._resetPointsArrayCache();
  38427. for (var index = 0; index < numOfMeshes; index++) {
  38428. var mesh = meshes[index];
  38429. if (updateExtends) {
  38430. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38431. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38432. var subMesh = mesh.subMeshes[subIndex];
  38433. subMesh.refreshBoundingInfo();
  38434. }
  38435. }
  38436. }
  38437. };
  38438. /** @ignore */
  38439. Geometry.prototype._bind = function (effect, indexToBind) {
  38440. if (!effect) {
  38441. return;
  38442. }
  38443. if (indexToBind === undefined) {
  38444. indexToBind = this._indexBuffer;
  38445. }
  38446. var vbs = this.getVertexBuffers();
  38447. if (!vbs) {
  38448. return;
  38449. }
  38450. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38451. this._engine.bindBuffers(vbs, indexToBind, effect);
  38452. return;
  38453. }
  38454. // Using VAO
  38455. if (!this._vertexArrayObjects[effect.key]) {
  38456. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38457. }
  38458. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38459. };
  38460. /**
  38461. * Gets total number of vertices
  38462. * @returns the total number of vertices
  38463. */
  38464. Geometry.prototype.getTotalVertices = function () {
  38465. if (!this.isReady()) {
  38466. return 0;
  38467. }
  38468. return this._totalVertices;
  38469. };
  38470. /**
  38471. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38472. * @param kind defines the data kind (Position, normal, etc...)
  38473. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38474. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38475. * @returns a float array containing vertex data
  38476. */
  38477. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38478. var vertexBuffer = this.getVertexBuffer(kind);
  38479. if (!vertexBuffer) {
  38480. return null;
  38481. }
  38482. var data = vertexBuffer.getData();
  38483. if (!data) {
  38484. return null;
  38485. }
  38486. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38487. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38488. var count = this._totalVertices * defaultStride;
  38489. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38490. var copy_1 = new Array(count);
  38491. vertexBuffer.forEach(count, function (value, index) {
  38492. copy_1[index] = value;
  38493. });
  38494. return copy_1;
  38495. }
  38496. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38497. if (data instanceof Array) {
  38498. var offset = vertexBuffer.byteOffset / 4;
  38499. return BABYLON.Tools.Slice(data, offset, offset + count);
  38500. }
  38501. else if (data instanceof ArrayBuffer) {
  38502. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38503. }
  38504. else {
  38505. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38506. }
  38507. }
  38508. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38509. return BABYLON.Tools.Slice(data);
  38510. }
  38511. return data;
  38512. };
  38513. /**
  38514. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38515. * @param kind defines the data kind (Position, normal, etc...)
  38516. * @returns true if the vertex buffer with the specified kind is updatable
  38517. */
  38518. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38519. var vb = this._vertexBuffers[kind];
  38520. if (!vb) {
  38521. return false;
  38522. }
  38523. return vb.isUpdatable();
  38524. };
  38525. /**
  38526. * Gets a specific vertex buffer
  38527. * @param kind defines the data kind (Position, normal, etc...)
  38528. * @returns a {BABYLON.VertexBuffer}
  38529. */
  38530. Geometry.prototype.getVertexBuffer = function (kind) {
  38531. if (!this.isReady()) {
  38532. return null;
  38533. }
  38534. return this._vertexBuffers[kind];
  38535. };
  38536. /**
  38537. * Returns all vertex buffers
  38538. * @return an object holding all vertex buffers indexed by kind
  38539. */
  38540. Geometry.prototype.getVertexBuffers = function () {
  38541. if (!this.isReady()) {
  38542. return null;
  38543. }
  38544. return this._vertexBuffers;
  38545. };
  38546. /**
  38547. * Gets a boolean indicating if specific vertex buffer is present
  38548. * @param kind defines the data kind (Position, normal, etc...)
  38549. * @returns true if data is present
  38550. */
  38551. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38552. if (!this._vertexBuffers) {
  38553. if (this._delayInfo) {
  38554. return this._delayInfo.indexOf(kind) !== -1;
  38555. }
  38556. return false;
  38557. }
  38558. return this._vertexBuffers[kind] !== undefined;
  38559. };
  38560. /**
  38561. * Gets a list of all attached data kinds (Position, normal, etc...)
  38562. * @returns a list of string containing all kinds
  38563. */
  38564. Geometry.prototype.getVerticesDataKinds = function () {
  38565. var result = [];
  38566. var kind;
  38567. if (!this._vertexBuffers && this._delayInfo) {
  38568. for (kind in this._delayInfo) {
  38569. result.push(kind);
  38570. }
  38571. }
  38572. else {
  38573. for (kind in this._vertexBuffers) {
  38574. result.push(kind);
  38575. }
  38576. }
  38577. return result;
  38578. };
  38579. /**
  38580. * Update index buffer
  38581. * @param indices defines the indices to store in the index buffer
  38582. * @param offset defines the offset in the target buffer where to store the data
  38583. */
  38584. Geometry.prototype.updateIndices = function (indices, offset) {
  38585. if (!this._indexBuffer) {
  38586. return;
  38587. }
  38588. if (!this._indexBufferIsUpdatable) {
  38589. this.setIndices(indices, null, true);
  38590. }
  38591. else {
  38592. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38593. }
  38594. };
  38595. /**
  38596. * Creates a new index buffer
  38597. * @param indices defines the indices to store in the index buffer
  38598. * @param totalVertices defines the total number of vertices (could be null)
  38599. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38600. */
  38601. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38602. if (totalVertices === void 0) { totalVertices = null; }
  38603. if (updatable === void 0) { updatable = false; }
  38604. if (this._indexBuffer) {
  38605. this._engine._releaseBuffer(this._indexBuffer);
  38606. }
  38607. this._disposeVertexArrayObjects();
  38608. this._indices = indices;
  38609. this._indexBufferIsUpdatable = updatable;
  38610. if (this._meshes.length !== 0 && this._indices) {
  38611. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38612. }
  38613. if (totalVertices != undefined) { // including null and undefined
  38614. this._totalVertices = totalVertices;
  38615. }
  38616. var meshes = this._meshes;
  38617. var numOfMeshes = meshes.length;
  38618. for (var index = 0; index < numOfMeshes; index++) {
  38619. meshes[index]._createGlobalSubMesh(true);
  38620. }
  38621. this.notifyUpdate();
  38622. };
  38623. /**
  38624. * Return the total number of indices
  38625. * @returns the total number of indices
  38626. */
  38627. Geometry.prototype.getTotalIndices = function () {
  38628. if (!this.isReady()) {
  38629. return 0;
  38630. }
  38631. return this._indices.length;
  38632. };
  38633. /**
  38634. * Gets the index buffer array
  38635. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38636. * @returns the index buffer array
  38637. */
  38638. Geometry.prototype.getIndices = function (copyWhenShared) {
  38639. if (!this.isReady()) {
  38640. return null;
  38641. }
  38642. var orig = this._indices;
  38643. if (!copyWhenShared || this._meshes.length === 1) {
  38644. return orig;
  38645. }
  38646. else {
  38647. var len = orig.length;
  38648. var copy = [];
  38649. for (var i = 0; i < len; i++) {
  38650. copy.push(orig[i]);
  38651. }
  38652. return copy;
  38653. }
  38654. };
  38655. /**
  38656. * Gets the index buffer
  38657. * @return the index buffer
  38658. */
  38659. Geometry.prototype.getIndexBuffer = function () {
  38660. if (!this.isReady()) {
  38661. return null;
  38662. }
  38663. return this._indexBuffer;
  38664. };
  38665. /** @ignore */
  38666. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38667. if (effect === void 0) { effect = null; }
  38668. if (!effect || !this._vertexArrayObjects) {
  38669. return;
  38670. }
  38671. if (this._vertexArrayObjects[effect.key]) {
  38672. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38673. delete this._vertexArrayObjects[effect.key];
  38674. }
  38675. };
  38676. /**
  38677. * Release the associated resources for a specific mesh
  38678. * @param mesh defines the source mesh
  38679. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38680. */
  38681. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38682. var meshes = this._meshes;
  38683. var index = meshes.indexOf(mesh);
  38684. if (index === -1) {
  38685. return;
  38686. }
  38687. meshes.splice(index, 1);
  38688. mesh._geometry = null;
  38689. if (meshes.length === 0 && shouldDispose) {
  38690. this.dispose();
  38691. }
  38692. };
  38693. /**
  38694. * Apply current geometry to a given mesh
  38695. * @param mesh defines the mesh to apply geometry to
  38696. */
  38697. Geometry.prototype.applyToMesh = function (mesh) {
  38698. if (mesh._geometry === this) {
  38699. return;
  38700. }
  38701. var previousGeometry = mesh._geometry;
  38702. if (previousGeometry) {
  38703. previousGeometry.releaseForMesh(mesh);
  38704. }
  38705. var meshes = this._meshes;
  38706. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38707. mesh._geometry = this;
  38708. this._scene.pushGeometry(this);
  38709. meshes.push(mesh);
  38710. if (this.isReady()) {
  38711. this._applyToMesh(mesh);
  38712. }
  38713. else {
  38714. mesh._boundingInfo = this._boundingInfo;
  38715. }
  38716. };
  38717. Geometry.prototype._updateExtend = function (data) {
  38718. if (data === void 0) { data = null; }
  38719. if (!data) {
  38720. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38721. }
  38722. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38723. };
  38724. Geometry.prototype._applyToMesh = function (mesh) {
  38725. var numOfMeshes = this._meshes.length;
  38726. // vertexBuffers
  38727. for (var kind in this._vertexBuffers) {
  38728. if (numOfMeshes === 1) {
  38729. this._vertexBuffers[kind].create();
  38730. }
  38731. var buffer = this._vertexBuffers[kind].getBuffer();
  38732. if (buffer)
  38733. buffer.references = numOfMeshes;
  38734. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38735. if (!this._extend) {
  38736. this._updateExtend();
  38737. }
  38738. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38739. mesh._createGlobalSubMesh(false);
  38740. //bounding info was just created again, world matrix should be applied again.
  38741. mesh._updateBoundingInfo();
  38742. }
  38743. }
  38744. // indexBuffer
  38745. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38746. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38747. }
  38748. if (this._indexBuffer) {
  38749. this._indexBuffer.references = numOfMeshes;
  38750. }
  38751. };
  38752. Geometry.prototype.notifyUpdate = function (kind) {
  38753. if (this.onGeometryUpdated) {
  38754. this.onGeometryUpdated(this, kind);
  38755. }
  38756. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38757. var mesh = _a[_i];
  38758. mesh._markSubMeshesAsAttributesDirty();
  38759. }
  38760. };
  38761. /**
  38762. * Load the geometry if it was flagged as delay loaded
  38763. * @param scene defines the hosting scene
  38764. * @param onLoaded defines a callback called when the geometry is loaded
  38765. */
  38766. Geometry.prototype.load = function (scene, onLoaded) {
  38767. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38768. return;
  38769. }
  38770. if (this.isReady()) {
  38771. if (onLoaded) {
  38772. onLoaded();
  38773. }
  38774. return;
  38775. }
  38776. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38777. this._queueLoad(scene, onLoaded);
  38778. };
  38779. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38780. var _this = this;
  38781. if (!this.delayLoadingFile) {
  38782. return;
  38783. }
  38784. scene._addPendingData(this);
  38785. scene._loadFile(this.delayLoadingFile, function (data) {
  38786. if (!_this._delayLoadingFunction) {
  38787. return;
  38788. }
  38789. _this._delayLoadingFunction(JSON.parse(data), _this);
  38790. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38791. _this._delayInfo = [];
  38792. scene._removePendingData(_this);
  38793. var meshes = _this._meshes;
  38794. var numOfMeshes = meshes.length;
  38795. for (var index = 0; index < numOfMeshes; index++) {
  38796. _this._applyToMesh(meshes[index]);
  38797. }
  38798. if (onLoaded) {
  38799. onLoaded();
  38800. }
  38801. }, undefined, true);
  38802. };
  38803. /**
  38804. * Invert the geometry to move from a right handed system to a left handed one.
  38805. */
  38806. Geometry.prototype.toLeftHanded = function () {
  38807. // Flip faces
  38808. var tIndices = this.getIndices(false);
  38809. if (tIndices != null && tIndices.length > 0) {
  38810. for (var i = 0; i < tIndices.length; i += 3) {
  38811. var tTemp = tIndices[i + 0];
  38812. tIndices[i + 0] = tIndices[i + 2];
  38813. tIndices[i + 2] = tTemp;
  38814. }
  38815. this.setIndices(tIndices);
  38816. }
  38817. // Negate position.z
  38818. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38819. if (tPositions != null && tPositions.length > 0) {
  38820. for (var i = 0; i < tPositions.length; i += 3) {
  38821. tPositions[i + 2] = -tPositions[i + 2];
  38822. }
  38823. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38824. }
  38825. // Negate normal.z
  38826. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38827. if (tNormals != null && tNormals.length > 0) {
  38828. for (var i = 0; i < tNormals.length; i += 3) {
  38829. tNormals[i + 2] = -tNormals[i + 2];
  38830. }
  38831. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38832. }
  38833. };
  38834. // Cache
  38835. /** @ignore */
  38836. Geometry.prototype._resetPointsArrayCache = function () {
  38837. this._positions = null;
  38838. };
  38839. /** @ignore */
  38840. Geometry.prototype._generatePointsArray = function () {
  38841. if (this._positions)
  38842. return true;
  38843. this._positions = [];
  38844. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38845. if (!data) {
  38846. return false;
  38847. }
  38848. for (var index = 0; index < data.length; index += 3) {
  38849. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38850. }
  38851. return true;
  38852. };
  38853. /**
  38854. * Gets a value indicating if the geometry is disposed
  38855. * @returns true if the geometry was disposed
  38856. */
  38857. Geometry.prototype.isDisposed = function () {
  38858. return this._isDisposed;
  38859. };
  38860. Geometry.prototype._disposeVertexArrayObjects = function () {
  38861. if (this._vertexArrayObjects) {
  38862. for (var kind in this._vertexArrayObjects) {
  38863. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38864. }
  38865. this._vertexArrayObjects = {};
  38866. }
  38867. };
  38868. /**
  38869. * Free all associated resources
  38870. */
  38871. Geometry.prototype.dispose = function () {
  38872. var meshes = this._meshes;
  38873. var numOfMeshes = meshes.length;
  38874. var index;
  38875. for (index = 0; index < numOfMeshes; index++) {
  38876. this.releaseForMesh(meshes[index]);
  38877. }
  38878. this._meshes = [];
  38879. this._disposeVertexArrayObjects();
  38880. for (var kind in this._vertexBuffers) {
  38881. this._vertexBuffers[kind].dispose();
  38882. }
  38883. this._vertexBuffers = {};
  38884. this._totalVertices = 0;
  38885. if (this._indexBuffer) {
  38886. this._engine._releaseBuffer(this._indexBuffer);
  38887. }
  38888. this._indexBuffer = null;
  38889. this._indices = [];
  38890. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38891. this.delayLoadingFile = null;
  38892. this._delayLoadingFunction = null;
  38893. this._delayInfo = [];
  38894. this._boundingInfo = null;
  38895. this._scene.removeGeometry(this);
  38896. this._isDisposed = true;
  38897. };
  38898. /**
  38899. * Clone the current geometry into a new geometry
  38900. * @param id defines the unique ID of the new geometry
  38901. * @returns a new geometry object
  38902. */
  38903. Geometry.prototype.copy = function (id) {
  38904. var vertexData = new BABYLON.VertexData();
  38905. vertexData.indices = [];
  38906. var indices = this.getIndices();
  38907. if (indices) {
  38908. for (var index = 0; index < indices.length; index++) {
  38909. vertexData.indices.push(indices[index]);
  38910. }
  38911. }
  38912. var updatable = false;
  38913. var stopChecking = false;
  38914. var kind;
  38915. for (kind in this._vertexBuffers) {
  38916. // using slice() to make a copy of the array and not just reference it
  38917. var data = this.getVerticesData(kind);
  38918. if (data instanceof Float32Array) {
  38919. vertexData.set(new Float32Array(data), kind);
  38920. }
  38921. else {
  38922. vertexData.set(data.slice(0), kind);
  38923. }
  38924. if (!stopChecking) {
  38925. var vb = this.getVertexBuffer(kind);
  38926. if (vb) {
  38927. updatable = vb.isUpdatable();
  38928. stopChecking = !updatable;
  38929. }
  38930. }
  38931. }
  38932. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38933. geometry.delayLoadState = this.delayLoadState;
  38934. geometry.delayLoadingFile = this.delayLoadingFile;
  38935. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38936. for (kind in this._delayInfo) {
  38937. geometry._delayInfo = geometry._delayInfo || [];
  38938. geometry._delayInfo.push(kind);
  38939. }
  38940. // Bounding info
  38941. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38942. return geometry;
  38943. };
  38944. /**
  38945. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38946. * @return a JSON representation of the current geometry data (without the vertices data)
  38947. */
  38948. Geometry.prototype.serialize = function () {
  38949. var serializationObject = {};
  38950. serializationObject.id = this.id;
  38951. serializationObject.updatable = this._updatable;
  38952. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38953. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38954. }
  38955. return serializationObject;
  38956. };
  38957. Geometry.prototype.toNumberArray = function (origin) {
  38958. if (Array.isArray(origin)) {
  38959. return origin;
  38960. }
  38961. else {
  38962. return Array.prototype.slice.call(origin);
  38963. }
  38964. };
  38965. /**
  38966. * Serialize all vertices data into a JSON oject
  38967. * @returns a JSON representation of the current geometry data
  38968. */
  38969. Geometry.prototype.serializeVerticeData = function () {
  38970. var serializationObject = this.serialize();
  38971. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38972. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38973. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38974. serializationObject.positions._updatable = true;
  38975. }
  38976. }
  38977. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38978. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38979. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38980. serializationObject.normals._updatable = true;
  38981. }
  38982. }
  38983. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38984. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38985. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38986. serializationObject.tangets._updatable = true;
  38987. }
  38988. }
  38989. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38990. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38991. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38992. serializationObject.uvs._updatable = true;
  38993. }
  38994. }
  38995. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38996. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38997. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38998. serializationObject.uv2s._updatable = true;
  38999. }
  39000. }
  39001. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39002. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39003. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39004. serializationObject.uv3s._updatable = true;
  39005. }
  39006. }
  39007. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39008. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39009. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39010. serializationObject.uv4s._updatable = true;
  39011. }
  39012. }
  39013. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39014. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39015. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39016. serializationObject.uv5s._updatable = true;
  39017. }
  39018. }
  39019. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39020. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39021. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39022. serializationObject.uv6s._updatable = true;
  39023. }
  39024. }
  39025. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39026. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39027. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39028. serializationObject.colors._updatable = true;
  39029. }
  39030. }
  39031. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39032. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39033. serializationObject.matricesIndices._isExpanded = true;
  39034. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39035. serializationObject.matricesIndices._updatable = true;
  39036. }
  39037. }
  39038. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39039. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39040. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39041. serializationObject.matricesWeights._updatable = true;
  39042. }
  39043. }
  39044. serializationObject.indices = this.toNumberArray(this.getIndices());
  39045. return serializationObject;
  39046. };
  39047. // Statics
  39048. /**
  39049. * Extracts a clone of a mesh geometry
  39050. * @param mesh defines the source mesh
  39051. * @param id defines the unique ID of the new geometry object
  39052. * @returns the new geometry object
  39053. */
  39054. Geometry.ExtractFromMesh = function (mesh, id) {
  39055. var geometry = mesh._geometry;
  39056. if (!geometry) {
  39057. return null;
  39058. }
  39059. return geometry.copy(id);
  39060. };
  39061. /**
  39062. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39063. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39064. * Be aware Math.random() could cause collisions, but:
  39065. * "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"
  39066. * @returns a string containing a new GUID
  39067. */
  39068. Geometry.RandomId = function () {
  39069. return BABYLON.Tools.RandomId();
  39070. };
  39071. /** @ignore */
  39072. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39073. var scene = mesh.getScene();
  39074. // Geometry
  39075. var geometryId = parsedGeometry.geometryId;
  39076. if (geometryId) {
  39077. var geometry = scene.getGeometryByID(geometryId);
  39078. if (geometry) {
  39079. geometry.applyToMesh(mesh);
  39080. }
  39081. }
  39082. else if (parsedGeometry instanceof ArrayBuffer) {
  39083. var binaryInfo = mesh._binaryInfo;
  39084. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39085. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39086. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39087. }
  39088. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39089. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39090. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39091. }
  39092. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39093. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39094. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39095. }
  39096. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39097. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39098. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39099. }
  39100. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39101. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39102. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39103. }
  39104. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39105. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39106. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39107. }
  39108. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39109. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39110. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39111. }
  39112. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39113. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39114. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39115. }
  39116. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39117. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39118. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39119. }
  39120. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39121. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39122. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39123. }
  39124. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39125. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39126. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39127. }
  39128. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39129. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39130. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39131. }
  39132. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39133. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39134. mesh.setIndices(indicesData, null);
  39135. }
  39136. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39137. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39138. mesh.subMeshes = [];
  39139. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39140. var materialIndex = subMeshesData[(i * 5) + 0];
  39141. var verticesStart = subMeshesData[(i * 5) + 1];
  39142. var verticesCount = subMeshesData[(i * 5) + 2];
  39143. var indexStart = subMeshesData[(i * 5) + 3];
  39144. var indexCount = subMeshesData[(i * 5) + 4];
  39145. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39146. }
  39147. }
  39148. }
  39149. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39150. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39151. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39152. if (parsedGeometry.tangents) {
  39153. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39154. }
  39155. if (parsedGeometry.uvs) {
  39156. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39157. }
  39158. if (parsedGeometry.uvs2) {
  39159. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39160. }
  39161. if (parsedGeometry.uvs3) {
  39162. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39163. }
  39164. if (parsedGeometry.uvs4) {
  39165. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39166. }
  39167. if (parsedGeometry.uvs5) {
  39168. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39169. }
  39170. if (parsedGeometry.uvs6) {
  39171. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39172. }
  39173. if (parsedGeometry.colors) {
  39174. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39175. }
  39176. if (parsedGeometry.matricesIndices) {
  39177. if (!parsedGeometry.matricesIndices._isExpanded) {
  39178. var floatIndices = [];
  39179. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39180. var matricesIndex = parsedGeometry.matricesIndices[i];
  39181. floatIndices.push(matricesIndex & 0x000000FF);
  39182. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39183. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39184. floatIndices.push(matricesIndex >> 24);
  39185. }
  39186. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39187. }
  39188. else {
  39189. delete parsedGeometry.matricesIndices._isExpanded;
  39190. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39191. }
  39192. }
  39193. if (parsedGeometry.matricesIndicesExtra) {
  39194. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39195. var floatIndices = [];
  39196. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39197. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39198. floatIndices.push(matricesIndex & 0x000000FF);
  39199. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39200. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39201. floatIndices.push(matricesIndex >> 24);
  39202. }
  39203. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39204. }
  39205. else {
  39206. delete parsedGeometry.matricesIndices._isExpanded;
  39207. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39208. }
  39209. }
  39210. if (parsedGeometry.matricesWeights) {
  39211. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39212. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39213. }
  39214. if (parsedGeometry.matricesWeightsExtra) {
  39215. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39216. }
  39217. mesh.setIndices(parsedGeometry.indices, null);
  39218. }
  39219. // SubMeshes
  39220. if (parsedGeometry.subMeshes) {
  39221. mesh.subMeshes = [];
  39222. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39223. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39224. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39225. }
  39226. }
  39227. // Flat shading
  39228. if (mesh._shouldGenerateFlatShading) {
  39229. mesh.convertToFlatShadedMesh();
  39230. delete mesh._shouldGenerateFlatShading;
  39231. }
  39232. // Update
  39233. mesh.computeWorldMatrix(true);
  39234. // Octree
  39235. var sceneOctree = scene.selectionOctree;
  39236. if (sceneOctree !== undefined && sceneOctree !== null) {
  39237. sceneOctree.addMesh(mesh);
  39238. }
  39239. };
  39240. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39241. var epsilon = 1e-3;
  39242. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39243. return;
  39244. }
  39245. var noInfluenceBoneIndex = 0.0;
  39246. if (parsedGeometry.skeletonId > -1) {
  39247. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39248. if (!skeleton) {
  39249. return;
  39250. }
  39251. noInfluenceBoneIndex = skeleton.bones.length;
  39252. }
  39253. else {
  39254. return;
  39255. }
  39256. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39257. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39258. var matricesWeights = parsedGeometry.matricesWeights;
  39259. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39260. var influencers = parsedGeometry.numBoneInfluencer;
  39261. var size = matricesWeights.length;
  39262. for (var i = 0; i < size; i += 4) {
  39263. var weight = 0.0;
  39264. var firstZeroWeight = -1;
  39265. for (var j = 0; j < 4; j++) {
  39266. var w = matricesWeights[i + j];
  39267. weight += w;
  39268. if (w < epsilon && firstZeroWeight < 0) {
  39269. firstZeroWeight = j;
  39270. }
  39271. }
  39272. if (matricesWeightsExtra) {
  39273. for (var j = 0; j < 4; j++) {
  39274. var w = matricesWeightsExtra[i + j];
  39275. weight += w;
  39276. if (w < epsilon && firstZeroWeight < 0) {
  39277. firstZeroWeight = j + 4;
  39278. }
  39279. }
  39280. }
  39281. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39282. firstZeroWeight = influencers - 1;
  39283. }
  39284. if (weight > epsilon) {
  39285. var mweight = 1.0 / weight;
  39286. for (var j = 0; j < 4; j++) {
  39287. matricesWeights[i + j] *= mweight;
  39288. }
  39289. if (matricesWeightsExtra) {
  39290. for (var j = 0; j < 4; j++) {
  39291. matricesWeightsExtra[i + j] *= mweight;
  39292. }
  39293. }
  39294. }
  39295. else {
  39296. if (firstZeroWeight >= 4) {
  39297. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39298. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39299. }
  39300. else {
  39301. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39302. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39303. }
  39304. }
  39305. }
  39306. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39307. if (parsedGeometry.matricesWeightsExtra) {
  39308. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39309. }
  39310. };
  39311. /**
  39312. * Create a new geometry from persisted data (Using .babylon file format)
  39313. * @param parsedVertexData defines the persisted data
  39314. * @param scene defines the hosting scene
  39315. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39316. * @returns the new geometry object
  39317. */
  39318. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39319. if (scene.getGeometryByID(parsedVertexData.id)) {
  39320. return null; // null since geometry could be something else than a box...
  39321. }
  39322. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39323. if (BABYLON.Tags) {
  39324. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39325. }
  39326. if (parsedVertexData.delayLoadingFile) {
  39327. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39328. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39329. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39330. geometry._delayInfo = [];
  39331. if (parsedVertexData.hasUVs) {
  39332. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39333. }
  39334. if (parsedVertexData.hasUVs2) {
  39335. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39336. }
  39337. if (parsedVertexData.hasUVs3) {
  39338. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39339. }
  39340. if (parsedVertexData.hasUVs4) {
  39341. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39342. }
  39343. if (parsedVertexData.hasUVs5) {
  39344. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39345. }
  39346. if (parsedVertexData.hasUVs6) {
  39347. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39348. }
  39349. if (parsedVertexData.hasColors) {
  39350. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39351. }
  39352. if (parsedVertexData.hasMatricesIndices) {
  39353. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39354. }
  39355. if (parsedVertexData.hasMatricesWeights) {
  39356. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39357. }
  39358. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39359. }
  39360. else {
  39361. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39362. }
  39363. scene.pushGeometry(geometry, true);
  39364. return geometry;
  39365. };
  39366. return Geometry;
  39367. }());
  39368. BABYLON.Geometry = Geometry;
  39369. // Primitives
  39370. /// Abstract class
  39371. /**
  39372. * Abstract class used to provide common services for all typed geometries
  39373. */
  39374. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39375. __extends(_PrimitiveGeometry, _super);
  39376. /**
  39377. * Creates a new typed geometry
  39378. * @param id defines the unique ID of the geometry
  39379. * @param scene defines the hosting scene
  39380. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39381. * @param mesh defines the hosting mesh (can be null)
  39382. */
  39383. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39384. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39385. if (mesh === void 0) { mesh = null; }
  39386. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39387. _this._canBeRegenerated = _canBeRegenerated;
  39388. _this._beingRegenerated = true;
  39389. _this.regenerate();
  39390. _this._beingRegenerated = false;
  39391. return _this;
  39392. }
  39393. /**
  39394. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39395. * @returns true if the geometry can be regenerated
  39396. */
  39397. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39398. return this._canBeRegenerated;
  39399. };
  39400. /**
  39401. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39402. */
  39403. _PrimitiveGeometry.prototype.regenerate = function () {
  39404. if (!this._canBeRegenerated) {
  39405. return;
  39406. }
  39407. this._beingRegenerated = true;
  39408. this.setAllVerticesData(this._regenerateVertexData(), false);
  39409. this._beingRegenerated = false;
  39410. };
  39411. /**
  39412. * Clone the geometry
  39413. * @param id defines the unique ID of the new geometry
  39414. * @returns the new geometry
  39415. */
  39416. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39417. return _super.prototype.copy.call(this, id);
  39418. };
  39419. // overrides
  39420. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39421. if (!this._beingRegenerated) {
  39422. return;
  39423. }
  39424. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39425. };
  39426. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39427. if (!this._beingRegenerated) {
  39428. return;
  39429. }
  39430. _super.prototype.setVerticesData.call(this, kind, data, false);
  39431. };
  39432. // to override
  39433. /** @ignore */
  39434. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39435. throw new Error("Abstract method");
  39436. };
  39437. _PrimitiveGeometry.prototype.copy = function (id) {
  39438. throw new Error("Must be overriden in sub-classes.");
  39439. };
  39440. _PrimitiveGeometry.prototype.serialize = function () {
  39441. var serializationObject = _super.prototype.serialize.call(this);
  39442. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39443. return serializationObject;
  39444. };
  39445. return _PrimitiveGeometry;
  39446. }(Geometry));
  39447. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39448. /**
  39449. * Creates a ribbon geometry
  39450. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39451. */
  39452. var RibbonGeometry = /** @class */ (function (_super) {
  39453. __extends(RibbonGeometry, _super);
  39454. /**
  39455. * Creates a ribbon geometry
  39456. * @param id defines the unique ID of the geometry
  39457. * @param scene defines the hosting scene
  39458. * @param pathArray defines the array of paths to use
  39459. * @param closeArray defines if the last path and the first path must be joined
  39460. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39461. * @param offset defines the offset between points
  39462. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39463. * @param mesh defines the hosting mesh (can be null)
  39464. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39465. */
  39466. function RibbonGeometry(id, scene,
  39467. /**
  39468. * Defines the array of paths to use
  39469. */
  39470. pathArray,
  39471. /**
  39472. * Defines if the last and first points of each path in your pathArray must be joined
  39473. */
  39474. closeArray,
  39475. /**
  39476. * Defines if the last and first points of each path in your pathArray must be joined
  39477. */
  39478. closePath,
  39479. /**
  39480. * Defines the offset between points
  39481. */
  39482. offset, canBeRegenerated, mesh,
  39483. /**
  39484. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39485. */
  39486. side) {
  39487. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39488. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39489. _this.pathArray = pathArray;
  39490. _this.closeArray = closeArray;
  39491. _this.closePath = closePath;
  39492. _this.offset = offset;
  39493. _this.side = side;
  39494. return _this;
  39495. }
  39496. /** @ignore */
  39497. RibbonGeometry.prototype._regenerateVertexData = function () {
  39498. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39499. };
  39500. RibbonGeometry.prototype.copy = function (id) {
  39501. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39502. };
  39503. return RibbonGeometry;
  39504. }(_PrimitiveGeometry));
  39505. BABYLON.RibbonGeometry = RibbonGeometry;
  39506. /**
  39507. * Creates a box geometry
  39508. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39509. */
  39510. var BoxGeometry = /** @class */ (function (_super) {
  39511. __extends(BoxGeometry, _super);
  39512. /**
  39513. * Creates a box geometry
  39514. * @param id defines the unique ID of the geometry
  39515. * @param scene defines the hosting scene
  39516. * @param size defines the zise of the box (width, height and depth are the same)
  39517. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39518. * @param mesh defines the hosting mesh (can be null)
  39519. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39520. */
  39521. function BoxGeometry(id, scene,
  39522. /**
  39523. * Defines the zise of the box (width, height and depth are the same)
  39524. */
  39525. size, canBeRegenerated, mesh,
  39526. /**
  39527. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39528. */
  39529. side) {
  39530. if (mesh === void 0) { mesh = null; }
  39531. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39532. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39533. _this.size = size;
  39534. _this.side = side;
  39535. return _this;
  39536. }
  39537. BoxGeometry.prototype._regenerateVertexData = function () {
  39538. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39539. };
  39540. BoxGeometry.prototype.copy = function (id) {
  39541. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39542. };
  39543. BoxGeometry.prototype.serialize = function () {
  39544. var serializationObject = _super.prototype.serialize.call(this);
  39545. serializationObject.size = this.size;
  39546. return serializationObject;
  39547. };
  39548. BoxGeometry.Parse = function (parsedBox, scene) {
  39549. if (scene.getGeometryByID(parsedBox.id)) {
  39550. return null; // null since geometry could be something else than a box...
  39551. }
  39552. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39553. if (BABYLON.Tags) {
  39554. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39555. }
  39556. scene.pushGeometry(box, true);
  39557. return box;
  39558. };
  39559. return BoxGeometry;
  39560. }(_PrimitiveGeometry));
  39561. BABYLON.BoxGeometry = BoxGeometry;
  39562. /**
  39563. * Creates a sphere geometry
  39564. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39565. */
  39566. var SphereGeometry = /** @class */ (function (_super) {
  39567. __extends(SphereGeometry, _super);
  39568. /**
  39569. * Create a new sphere geometry
  39570. * @param id defines the unique ID of the geometry
  39571. * @param scene defines the hosting scene
  39572. * @param segments defines the number of segments to use to create the sphere
  39573. * @param diameter defines the diameter of the sphere
  39574. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39575. * @param mesh defines the hosting mesh (can be null)
  39576. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39577. */
  39578. function SphereGeometry(id, scene,
  39579. /**
  39580. * Defines the number of segments to use to create the sphere
  39581. */
  39582. segments,
  39583. /**
  39584. * Defines the diameter of the sphere
  39585. */
  39586. diameter, canBeRegenerated, mesh,
  39587. /**
  39588. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39589. */
  39590. side) {
  39591. if (mesh === void 0) { mesh = null; }
  39592. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39593. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39594. _this.segments = segments;
  39595. _this.diameter = diameter;
  39596. _this.side = side;
  39597. return _this;
  39598. }
  39599. SphereGeometry.prototype._regenerateVertexData = function () {
  39600. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39601. };
  39602. SphereGeometry.prototype.copy = function (id) {
  39603. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39604. };
  39605. SphereGeometry.prototype.serialize = function () {
  39606. var serializationObject = _super.prototype.serialize.call(this);
  39607. serializationObject.segments = this.segments;
  39608. serializationObject.diameter = this.diameter;
  39609. return serializationObject;
  39610. };
  39611. SphereGeometry.Parse = function (parsedSphere, scene) {
  39612. if (scene.getGeometryByID(parsedSphere.id)) {
  39613. return null; // null since geometry could be something else than a sphere...
  39614. }
  39615. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39616. if (BABYLON.Tags) {
  39617. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39618. }
  39619. scene.pushGeometry(sphere, true);
  39620. return sphere;
  39621. };
  39622. return SphereGeometry;
  39623. }(_PrimitiveGeometry));
  39624. BABYLON.SphereGeometry = SphereGeometry;
  39625. /**
  39626. * Creates a disc geometry
  39627. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39628. */
  39629. var DiscGeometry = /** @class */ (function (_super) {
  39630. __extends(DiscGeometry, _super);
  39631. /**
  39632. * Creates a new disc geometry
  39633. * @param id defines the unique ID of the geometry
  39634. * @param scene defines the hosting scene
  39635. * @param radius defines the radius of the disc
  39636. * @param tessellation defines the tesselation factor to apply to the disc
  39637. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39638. * @param mesh defines the hosting mesh (can be null)
  39639. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39640. */
  39641. function DiscGeometry(id, scene,
  39642. /**
  39643. * Defines the radius of the disc
  39644. */
  39645. radius,
  39646. /**
  39647. * Defines the tesselation factor to apply to the disc
  39648. */
  39649. tessellation, canBeRegenerated, mesh,
  39650. /**
  39651. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39652. */
  39653. side) {
  39654. if (mesh === void 0) { mesh = null; }
  39655. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39656. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39657. _this.radius = radius;
  39658. _this.tessellation = tessellation;
  39659. _this.side = side;
  39660. return _this;
  39661. }
  39662. DiscGeometry.prototype._regenerateVertexData = function () {
  39663. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39664. };
  39665. DiscGeometry.prototype.copy = function (id) {
  39666. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39667. };
  39668. return DiscGeometry;
  39669. }(_PrimitiveGeometry));
  39670. BABYLON.DiscGeometry = DiscGeometry;
  39671. /**
  39672. * Creates a new cylinder geometry
  39673. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39674. */
  39675. var CylinderGeometry = /** @class */ (function (_super) {
  39676. __extends(CylinderGeometry, _super);
  39677. /**
  39678. * Creates a new cylinder geometry
  39679. * @param id defines the unique ID of the geometry
  39680. * @param scene defines the hosting scene
  39681. * @param height defines the height of the cylinder
  39682. * @param diameterTop defines the diameter of the cylinder's top cap
  39683. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39684. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39685. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39686. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39687. * @param mesh defines the hosting mesh (can be null)
  39688. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39689. */
  39690. function CylinderGeometry(id, scene,
  39691. /**
  39692. * Defines the height of the cylinder
  39693. */
  39694. height,
  39695. /**
  39696. * Defines the diameter of the cylinder's top cap
  39697. */
  39698. diameterTop,
  39699. /**
  39700. * Defines the diameter of the cylinder's bottom cap
  39701. */
  39702. diameterBottom,
  39703. /**
  39704. * Defines the tessellation factor to apply to the cylinder
  39705. */
  39706. tessellation,
  39707. /**
  39708. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39709. */
  39710. subdivisions, canBeRegenerated, mesh,
  39711. /**
  39712. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39713. */
  39714. side) {
  39715. if (subdivisions === void 0) { subdivisions = 1; }
  39716. if (mesh === void 0) { mesh = null; }
  39717. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39718. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39719. _this.height = height;
  39720. _this.diameterTop = diameterTop;
  39721. _this.diameterBottom = diameterBottom;
  39722. _this.tessellation = tessellation;
  39723. _this.subdivisions = subdivisions;
  39724. _this.side = side;
  39725. return _this;
  39726. }
  39727. CylinderGeometry.prototype._regenerateVertexData = function () {
  39728. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39729. };
  39730. CylinderGeometry.prototype.copy = function (id) {
  39731. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39732. };
  39733. CylinderGeometry.prototype.serialize = function () {
  39734. var serializationObject = _super.prototype.serialize.call(this);
  39735. serializationObject.height = this.height;
  39736. serializationObject.diameterTop = this.diameterTop;
  39737. serializationObject.diameterBottom = this.diameterBottom;
  39738. serializationObject.tessellation = this.tessellation;
  39739. return serializationObject;
  39740. };
  39741. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39742. if (scene.getGeometryByID(parsedCylinder.id)) {
  39743. return null; // null since geometry could be something else than a cylinder...
  39744. }
  39745. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39746. if (BABYLON.Tags) {
  39747. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39748. }
  39749. scene.pushGeometry(cylinder, true);
  39750. return cylinder;
  39751. };
  39752. return CylinderGeometry;
  39753. }(_PrimitiveGeometry));
  39754. BABYLON.CylinderGeometry = CylinderGeometry;
  39755. /**
  39756. * Creates a new torus geometry
  39757. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39758. */
  39759. var TorusGeometry = /** @class */ (function (_super) {
  39760. __extends(TorusGeometry, _super);
  39761. /**
  39762. * Creates a new torus geometry
  39763. * @param id defines the unique ID of the geometry
  39764. * @param scene defines the hosting scene
  39765. * @param diameter defines the diameter of the torus
  39766. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39767. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39768. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39769. * @param mesh defines the hosting mesh (can be null)
  39770. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39771. */
  39772. function TorusGeometry(id, scene,
  39773. /**
  39774. * Defines the diameter of the torus
  39775. */
  39776. diameter,
  39777. /**
  39778. * Defines the thickness of the torus (ie. internal diameter)
  39779. */
  39780. thickness,
  39781. /**
  39782. * Defines the tesselation factor to apply to the torus
  39783. */
  39784. tessellation, canBeRegenerated, mesh,
  39785. /**
  39786. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39787. */
  39788. side) {
  39789. if (mesh === void 0) { mesh = null; }
  39790. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39791. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39792. _this.diameter = diameter;
  39793. _this.thickness = thickness;
  39794. _this.tessellation = tessellation;
  39795. _this.side = side;
  39796. return _this;
  39797. }
  39798. TorusGeometry.prototype._regenerateVertexData = function () {
  39799. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39800. };
  39801. TorusGeometry.prototype.copy = function (id) {
  39802. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39803. };
  39804. TorusGeometry.prototype.serialize = function () {
  39805. var serializationObject = _super.prototype.serialize.call(this);
  39806. serializationObject.diameter = this.diameter;
  39807. serializationObject.thickness = this.thickness;
  39808. serializationObject.tessellation = this.tessellation;
  39809. return serializationObject;
  39810. };
  39811. TorusGeometry.Parse = function (parsedTorus, scene) {
  39812. if (scene.getGeometryByID(parsedTorus.id)) {
  39813. return null; // null since geometry could be something else than a torus...
  39814. }
  39815. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39816. if (BABYLON.Tags) {
  39817. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39818. }
  39819. scene.pushGeometry(torus, true);
  39820. return torus;
  39821. };
  39822. return TorusGeometry;
  39823. }(_PrimitiveGeometry));
  39824. BABYLON.TorusGeometry = TorusGeometry;
  39825. /**
  39826. * Creates a new ground geometry
  39827. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39828. */
  39829. var GroundGeometry = /** @class */ (function (_super) {
  39830. __extends(GroundGeometry, _super);
  39831. /**
  39832. * Creates a new ground geometry
  39833. * @param id defines the unique ID of the geometry
  39834. * @param scene defines the hosting scene
  39835. * @param width defines the width of the ground
  39836. * @param height defines the height of the ground
  39837. * @param subdivisions defines the subdivisions to apply to the ground
  39838. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39839. * @param mesh defines the hosting mesh (can be null)
  39840. */
  39841. function GroundGeometry(id, scene,
  39842. /**
  39843. * Defines the width of the ground
  39844. */
  39845. width,
  39846. /**
  39847. * Defines the height of the ground
  39848. */
  39849. height,
  39850. /**
  39851. * Defines the subdivisions to apply to the ground
  39852. */
  39853. subdivisions, canBeRegenerated, mesh) {
  39854. if (mesh === void 0) { mesh = null; }
  39855. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39856. _this.width = width;
  39857. _this.height = height;
  39858. _this.subdivisions = subdivisions;
  39859. return _this;
  39860. }
  39861. GroundGeometry.prototype._regenerateVertexData = function () {
  39862. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39863. };
  39864. GroundGeometry.prototype.copy = function (id) {
  39865. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39866. };
  39867. GroundGeometry.prototype.serialize = function () {
  39868. var serializationObject = _super.prototype.serialize.call(this);
  39869. serializationObject.width = this.width;
  39870. serializationObject.height = this.height;
  39871. serializationObject.subdivisions = this.subdivisions;
  39872. return serializationObject;
  39873. };
  39874. GroundGeometry.Parse = function (parsedGround, scene) {
  39875. if (scene.getGeometryByID(parsedGround.id)) {
  39876. return null; // null since geometry could be something else than a ground...
  39877. }
  39878. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39879. if (BABYLON.Tags) {
  39880. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39881. }
  39882. scene.pushGeometry(ground, true);
  39883. return ground;
  39884. };
  39885. return GroundGeometry;
  39886. }(_PrimitiveGeometry));
  39887. BABYLON.GroundGeometry = GroundGeometry;
  39888. /**
  39889. * Creates a tiled ground geometry
  39890. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39891. */
  39892. var TiledGroundGeometry = /** @class */ (function (_super) {
  39893. __extends(TiledGroundGeometry, _super);
  39894. /**
  39895. * Creates a tiled ground geometry
  39896. * @param id defines the unique ID of the geometry
  39897. * @param scene defines the hosting scene
  39898. * @param xmin defines the minimum value on X axis
  39899. * @param zmin defines the minimum value on Z axis
  39900. * @param xmax defines the maximum value on X axis
  39901. * @param zmax defines the maximum value on Z axis
  39902. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39903. * @param precision defines the precision to use when computing the tiles
  39904. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39905. * @param mesh defines the hosting mesh (can be null)
  39906. */
  39907. function TiledGroundGeometry(id, scene,
  39908. /**
  39909. * Defines the minimum value on X axis
  39910. */
  39911. xmin,
  39912. /**
  39913. * Defines the minimum value on Z axis
  39914. */
  39915. zmin,
  39916. /**
  39917. * Defines the maximum value on X axis
  39918. */
  39919. xmax,
  39920. /**
  39921. * Defines the maximum value on Z axis
  39922. */
  39923. zmax,
  39924. /**
  39925. * Defines the subdivisions to apply to the ground
  39926. */
  39927. subdivisions,
  39928. /**
  39929. * Defines the precision to use when computing the tiles
  39930. */
  39931. precision, canBeRegenerated, mesh) {
  39932. if (mesh === void 0) { mesh = null; }
  39933. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39934. _this.xmin = xmin;
  39935. _this.zmin = zmin;
  39936. _this.xmax = xmax;
  39937. _this.zmax = zmax;
  39938. _this.subdivisions = subdivisions;
  39939. _this.precision = precision;
  39940. return _this;
  39941. }
  39942. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39943. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39944. };
  39945. TiledGroundGeometry.prototype.copy = function (id) {
  39946. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39947. };
  39948. return TiledGroundGeometry;
  39949. }(_PrimitiveGeometry));
  39950. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39951. /**
  39952. * Creates a plane geometry
  39953. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39954. */
  39955. var PlaneGeometry = /** @class */ (function (_super) {
  39956. __extends(PlaneGeometry, _super);
  39957. /**
  39958. * Creates a plane geometry
  39959. * @param id defines the unique ID of the geometry
  39960. * @param scene defines the hosting scene
  39961. * @param size defines the size of the plane (width === height)
  39962. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39963. * @param mesh defines the hosting mesh (can be null)
  39964. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39965. */
  39966. function PlaneGeometry(id, scene,
  39967. /**
  39968. * Defines the size of the plane (width === height)
  39969. */
  39970. size, canBeRegenerated, mesh,
  39971. /**
  39972. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39973. */
  39974. side) {
  39975. if (mesh === void 0) { mesh = null; }
  39976. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39977. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39978. _this.size = size;
  39979. _this.side = side;
  39980. return _this;
  39981. }
  39982. PlaneGeometry.prototype._regenerateVertexData = function () {
  39983. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39984. };
  39985. PlaneGeometry.prototype.copy = function (id) {
  39986. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39987. };
  39988. PlaneGeometry.prototype.serialize = function () {
  39989. var serializationObject = _super.prototype.serialize.call(this);
  39990. serializationObject.size = this.size;
  39991. return serializationObject;
  39992. };
  39993. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39994. if (scene.getGeometryByID(parsedPlane.id)) {
  39995. return null; // null since geometry could be something else than a ground...
  39996. }
  39997. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39998. if (BABYLON.Tags) {
  39999. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40000. }
  40001. scene.pushGeometry(plane, true);
  40002. return plane;
  40003. };
  40004. return PlaneGeometry;
  40005. }(_PrimitiveGeometry));
  40006. BABYLON.PlaneGeometry = PlaneGeometry;
  40007. /**
  40008. * Creates a torus knot geometry
  40009. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40010. */
  40011. var TorusKnotGeometry = /** @class */ (function (_super) {
  40012. __extends(TorusKnotGeometry, _super);
  40013. /**
  40014. * Creates a torus knot geometry
  40015. * @param id defines the unique ID of the geometry
  40016. * @param scene defines the hosting scene
  40017. * @param radius defines the radius of the torus knot
  40018. * @param tube defines the thickness of the torus knot tube
  40019. * @param radialSegments defines the number of radial segments
  40020. * @param tubularSegments defines the number of tubular segments
  40021. * @param p defines the first number of windings
  40022. * @param q defines the second number of windings
  40023. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40024. * @param mesh defines the hosting mesh (can be null)
  40025. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40026. */
  40027. function TorusKnotGeometry(id, scene,
  40028. /**
  40029. * Defines the radius of the torus knot
  40030. */
  40031. radius,
  40032. /**
  40033. * Defines the thickness of the torus knot tube
  40034. */
  40035. tube,
  40036. /**
  40037. * Defines the number of radial segments
  40038. */
  40039. radialSegments,
  40040. /**
  40041. * Defines the number of tubular segments
  40042. */
  40043. tubularSegments,
  40044. /**
  40045. * Defines the first number of windings
  40046. */
  40047. p,
  40048. /**
  40049. * Defines the second number of windings
  40050. */
  40051. q, canBeRegenerated, mesh,
  40052. /**
  40053. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40054. */
  40055. side) {
  40056. if (mesh === void 0) { mesh = null; }
  40057. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40058. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40059. _this.radius = radius;
  40060. _this.tube = tube;
  40061. _this.radialSegments = radialSegments;
  40062. _this.tubularSegments = tubularSegments;
  40063. _this.p = p;
  40064. _this.q = q;
  40065. _this.side = side;
  40066. return _this;
  40067. }
  40068. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40069. 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 });
  40070. };
  40071. TorusKnotGeometry.prototype.copy = function (id) {
  40072. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40073. };
  40074. TorusKnotGeometry.prototype.serialize = function () {
  40075. var serializationObject = _super.prototype.serialize.call(this);
  40076. serializationObject.radius = this.radius;
  40077. serializationObject.tube = this.tube;
  40078. serializationObject.radialSegments = this.radialSegments;
  40079. serializationObject.tubularSegments = this.tubularSegments;
  40080. serializationObject.p = this.p;
  40081. serializationObject.q = this.q;
  40082. return serializationObject;
  40083. };
  40084. ;
  40085. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40086. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40087. return null; // null since geometry could be something else than a ground...
  40088. }
  40089. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40090. if (BABYLON.Tags) {
  40091. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40092. }
  40093. scene.pushGeometry(torusKnot, true);
  40094. return torusKnot;
  40095. };
  40096. return TorusKnotGeometry;
  40097. }(_PrimitiveGeometry));
  40098. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40099. //}
  40100. })(BABYLON || (BABYLON = {}));
  40101. //# sourceMappingURL=babylon.geometry.js.map
  40102. var BABYLON;
  40103. (function (BABYLON) {
  40104. /**
  40105. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40106. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40107. */
  40108. var PostProcessManager = /** @class */ (function () {
  40109. /**
  40110. * Creates a new instance PostProcess
  40111. * @param scene The scene that the post process is associated with.
  40112. */
  40113. function PostProcessManager(scene) {
  40114. this._vertexBuffers = {};
  40115. this._scene = scene;
  40116. }
  40117. PostProcessManager.prototype._prepareBuffers = function () {
  40118. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40119. return;
  40120. }
  40121. // VBO
  40122. var vertices = [];
  40123. vertices.push(1, 1);
  40124. vertices.push(-1, 1);
  40125. vertices.push(-1, -1);
  40126. vertices.push(1, -1);
  40127. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40128. this._buildIndexBuffer();
  40129. };
  40130. PostProcessManager.prototype._buildIndexBuffer = function () {
  40131. // Indices
  40132. var indices = [];
  40133. indices.push(0);
  40134. indices.push(1);
  40135. indices.push(2);
  40136. indices.push(0);
  40137. indices.push(2);
  40138. indices.push(3);
  40139. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40140. };
  40141. /**
  40142. * Rebuilds the vertex buffers of the manager.
  40143. */
  40144. PostProcessManager.prototype._rebuild = function () {
  40145. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40146. if (!vb) {
  40147. return;
  40148. }
  40149. vb._rebuild();
  40150. this._buildIndexBuffer();
  40151. };
  40152. // Methods
  40153. /**
  40154. * Prepares a frame to be run through a post process.
  40155. * @param sourceTexture The input texture to the post procesess. (default: null)
  40156. * @param postProcesses An array of post processes to be run. (default: null)
  40157. * @returns True if the post processes were able to be run.
  40158. */
  40159. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40160. if (sourceTexture === void 0) { sourceTexture = null; }
  40161. if (postProcesses === void 0) { postProcesses = null; }
  40162. var camera = this._scene.activeCamera;
  40163. if (!camera) {
  40164. return false;
  40165. }
  40166. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40167. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40168. return false;
  40169. }
  40170. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40171. return true;
  40172. };
  40173. /**
  40174. * Manually render a set of post processes to a texture.
  40175. * @param postProcesses An array of post processes to be run.
  40176. * @param targetTexture The target texture to render to.
  40177. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40178. */
  40179. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40180. if (targetTexture === void 0) { targetTexture = null; }
  40181. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40182. var engine = this._scene.getEngine();
  40183. for (var index = 0; index < postProcesses.length; index++) {
  40184. if (index < postProcesses.length - 1) {
  40185. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40186. }
  40187. else {
  40188. if (targetTexture) {
  40189. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40190. }
  40191. else {
  40192. engine.restoreDefaultFramebuffer();
  40193. }
  40194. }
  40195. var pp = postProcesses[index];
  40196. var effect = pp.apply();
  40197. if (effect) {
  40198. pp.onBeforeRenderObservable.notifyObservers(effect);
  40199. // VBOs
  40200. this._prepareBuffers();
  40201. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40202. // Draw order
  40203. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40204. pp.onAfterRenderObservable.notifyObservers(effect);
  40205. }
  40206. }
  40207. // Restore depth buffer
  40208. engine.setDepthBuffer(true);
  40209. engine.setDepthWrite(true);
  40210. };
  40211. /**
  40212. * Finalize the result of the output of the postprocesses.
  40213. * @param doNotPresent If true the result will not be displayed to the screen.
  40214. * @param targetTexture The target texture to render to.
  40215. * @param faceIndex The index of the face to bind the target texture to.
  40216. * @param postProcesses The array of post processes to render.
  40217. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40218. */
  40219. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40220. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40221. var camera = this._scene.activeCamera;
  40222. if (!camera) {
  40223. return;
  40224. }
  40225. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40226. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40227. return;
  40228. }
  40229. var engine = this._scene.getEngine();
  40230. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40231. var pp = postProcesses[index];
  40232. if (index < len - 1) {
  40233. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40234. }
  40235. else {
  40236. if (targetTexture) {
  40237. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40238. pp._outputTexture = targetTexture;
  40239. }
  40240. else {
  40241. engine.restoreDefaultFramebuffer();
  40242. pp._outputTexture = null;
  40243. }
  40244. }
  40245. if (doNotPresent) {
  40246. break;
  40247. }
  40248. var effect = pp.apply();
  40249. if (effect) {
  40250. pp.onBeforeRenderObservable.notifyObservers(effect);
  40251. // VBOs
  40252. this._prepareBuffers();
  40253. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40254. // Draw order
  40255. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40256. pp.onAfterRenderObservable.notifyObservers(effect);
  40257. }
  40258. }
  40259. // Restore states
  40260. engine.setDepthBuffer(true);
  40261. engine.setDepthWrite(true);
  40262. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40263. };
  40264. /**
  40265. * Disposes of the post process manager.
  40266. */
  40267. PostProcessManager.prototype.dispose = function () {
  40268. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40269. if (buffer) {
  40270. buffer.dispose();
  40271. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40272. }
  40273. if (this._indexBuffer) {
  40274. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40275. this._indexBuffer = null;
  40276. }
  40277. };
  40278. return PostProcessManager;
  40279. }());
  40280. BABYLON.PostProcessManager = PostProcessManager;
  40281. })(BABYLON || (BABYLON = {}));
  40282. //# sourceMappingURL=babylon.postProcessManager.js.map
  40283. var BABYLON;
  40284. (function (BABYLON) {
  40285. /**
  40286. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40287. */
  40288. var PerformanceMonitor = /** @class */ (function () {
  40289. /**
  40290. * constructor
  40291. * @param frameSampleSize The number of samples required to saturate the sliding window
  40292. */
  40293. function PerformanceMonitor(frameSampleSize) {
  40294. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40295. this._enabled = true;
  40296. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40297. }
  40298. /**
  40299. * Samples current frame
  40300. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40301. */
  40302. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40303. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40304. if (!this._enabled)
  40305. return;
  40306. if (this._lastFrameTimeMs != null) {
  40307. var dt = timeMs - this._lastFrameTimeMs;
  40308. this._rollingFrameTime.add(dt);
  40309. }
  40310. this._lastFrameTimeMs = timeMs;
  40311. };
  40312. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40313. /**
  40314. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40315. * @return Average frame time in milliseconds
  40316. */
  40317. get: function () {
  40318. return this._rollingFrameTime.average;
  40319. },
  40320. enumerable: true,
  40321. configurable: true
  40322. });
  40323. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40324. /**
  40325. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40326. * @return Frame time variance in milliseconds squared
  40327. */
  40328. get: function () {
  40329. return this._rollingFrameTime.variance;
  40330. },
  40331. enumerable: true,
  40332. configurable: true
  40333. });
  40334. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40335. /**
  40336. * Returns the frame time of the most recent frame
  40337. * @return Frame time in milliseconds
  40338. */
  40339. get: function () {
  40340. return this._rollingFrameTime.history(0);
  40341. },
  40342. enumerable: true,
  40343. configurable: true
  40344. });
  40345. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40346. /**
  40347. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40348. * @return Framerate in frames per second
  40349. */
  40350. get: function () {
  40351. return 1000.0 / this._rollingFrameTime.average;
  40352. },
  40353. enumerable: true,
  40354. configurable: true
  40355. });
  40356. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40357. /**
  40358. * Returns the average framerate in frames per second using the most recent frame time
  40359. * @return Framerate in frames per second
  40360. */
  40361. get: function () {
  40362. var history = this._rollingFrameTime.history(0);
  40363. if (history === 0) {
  40364. return 0;
  40365. }
  40366. return 1000.0 / history;
  40367. },
  40368. enumerable: true,
  40369. configurable: true
  40370. });
  40371. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40372. /**
  40373. * Returns true if enough samples have been taken to completely fill the sliding window
  40374. * @return true if saturated
  40375. */
  40376. get: function () {
  40377. return this._rollingFrameTime.isSaturated();
  40378. },
  40379. enumerable: true,
  40380. configurable: true
  40381. });
  40382. /**
  40383. * Enables contributions to the sliding window sample set
  40384. */
  40385. PerformanceMonitor.prototype.enable = function () {
  40386. this._enabled = true;
  40387. };
  40388. /**
  40389. * Disables contributions to the sliding window sample set
  40390. * Samples will not be interpolated over the disabled period
  40391. */
  40392. PerformanceMonitor.prototype.disable = function () {
  40393. this._enabled = false;
  40394. //clear last sample to avoid interpolating over the disabled period when next enabled
  40395. this._lastFrameTimeMs = null;
  40396. };
  40397. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40398. /**
  40399. * Returns true if sampling is enabled
  40400. * @return true if enabled
  40401. */
  40402. get: function () {
  40403. return this._enabled;
  40404. },
  40405. enumerable: true,
  40406. configurable: true
  40407. });
  40408. /**
  40409. * Resets performance monitor
  40410. */
  40411. PerformanceMonitor.prototype.reset = function () {
  40412. //clear last sample to avoid interpolating over the disabled period when next enabled
  40413. this._lastFrameTimeMs = null;
  40414. //wipe record
  40415. this._rollingFrameTime.reset();
  40416. };
  40417. return PerformanceMonitor;
  40418. }());
  40419. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40420. /**
  40421. * RollingAverage
  40422. *
  40423. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40424. */
  40425. var RollingAverage = /** @class */ (function () {
  40426. /**
  40427. * constructor
  40428. * @param length The number of samples required to saturate the sliding window
  40429. */
  40430. function RollingAverage(length) {
  40431. this._samples = new Array(length);
  40432. this.reset();
  40433. }
  40434. /**
  40435. * Adds a sample to the sample set
  40436. * @param v The sample value
  40437. */
  40438. RollingAverage.prototype.add = function (v) {
  40439. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40440. var delta;
  40441. //we need to check if we've already wrapped round
  40442. if (this.isSaturated()) {
  40443. //remove bottom of stack from mean
  40444. var bottomValue = this._samples[this._pos];
  40445. delta = bottomValue - this.average;
  40446. this.average -= delta / (this._sampleCount - 1);
  40447. this._m2 -= delta * (bottomValue - this.average);
  40448. }
  40449. else {
  40450. this._sampleCount++;
  40451. }
  40452. //add new value to mean
  40453. delta = v - this.average;
  40454. this.average += delta / (this._sampleCount);
  40455. this._m2 += delta * (v - this.average);
  40456. //set the new variance
  40457. this.variance = this._m2 / (this._sampleCount - 1);
  40458. this._samples[this._pos] = v;
  40459. this._pos++;
  40460. this._pos %= this._samples.length; //positive wrap around
  40461. };
  40462. /**
  40463. * Returns previously added values or null if outside of history or outside the sliding window domain
  40464. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40465. * @return Value previously recorded with add() or null if outside of range
  40466. */
  40467. RollingAverage.prototype.history = function (i) {
  40468. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40469. return 0;
  40470. }
  40471. var i0 = this._wrapPosition(this._pos - 1.0);
  40472. return this._samples[this._wrapPosition(i0 - i)];
  40473. };
  40474. /**
  40475. * Returns true if enough samples have been taken to completely fill the sliding window
  40476. * @return true if sample-set saturated
  40477. */
  40478. RollingAverage.prototype.isSaturated = function () {
  40479. return this._sampleCount >= this._samples.length;
  40480. };
  40481. /**
  40482. * Resets the rolling average (equivalent to 0 samples taken so far)
  40483. */
  40484. RollingAverage.prototype.reset = function () {
  40485. this.average = 0;
  40486. this.variance = 0;
  40487. this._sampleCount = 0;
  40488. this._pos = 0;
  40489. this._m2 = 0;
  40490. };
  40491. /**
  40492. * Wraps a value around the sample range boundaries
  40493. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40494. * @return Wrapped position in sample range
  40495. */
  40496. RollingAverage.prototype._wrapPosition = function (i) {
  40497. var max = this._samples.length;
  40498. return ((i % max) + max) % max;
  40499. };
  40500. return RollingAverage;
  40501. }());
  40502. BABYLON.RollingAverage = RollingAverage;
  40503. })(BABYLON || (BABYLON = {}));
  40504. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40505. var BABYLON;
  40506. (function (BABYLON) {
  40507. /**
  40508. * This groups together the common properties used for image processing either in direct forward pass
  40509. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40510. * or not.
  40511. */
  40512. var ImageProcessingConfiguration = /** @class */ (function () {
  40513. function ImageProcessingConfiguration() {
  40514. /**
  40515. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40516. */
  40517. this.colorCurves = new BABYLON.ColorCurves();
  40518. this._colorCurvesEnabled = false;
  40519. this._colorGradingEnabled = false;
  40520. this._colorGradingWithGreenDepth = true;
  40521. this._colorGradingBGR = true;
  40522. this._exposure = 1.0;
  40523. this._toneMappingEnabled = false;
  40524. this._contrast = 1.0;
  40525. /**
  40526. * Vignette stretch size.
  40527. */
  40528. this.vignetteStretch = 0;
  40529. /**
  40530. * Vignette centre X Offset.
  40531. */
  40532. this.vignetteCentreX = 0;
  40533. /**
  40534. * Vignette centre Y Offset.
  40535. */
  40536. this.vignetteCentreY = 0;
  40537. /**
  40538. * Vignette weight or intensity of the vignette effect.
  40539. */
  40540. this.vignetteWeight = 1.5;
  40541. /**
  40542. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40543. * if vignetteEnabled is set to true.
  40544. */
  40545. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40546. /**
  40547. * Camera field of view used by the Vignette effect.
  40548. */
  40549. this.vignetteCameraFov = 0.5;
  40550. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40551. this._vignetteEnabled = false;
  40552. this._applyByPostProcess = false;
  40553. this._isEnabled = true;
  40554. /**
  40555. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40556. */
  40557. this.onUpdateParameters = new BABYLON.Observable();
  40558. }
  40559. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40560. /**
  40561. * Gets wether the color curves effect is enabled.
  40562. */
  40563. get: function () {
  40564. return this._colorCurvesEnabled;
  40565. },
  40566. /**
  40567. * Sets wether the color curves effect is enabled.
  40568. */
  40569. set: function (value) {
  40570. if (this._colorCurvesEnabled === value) {
  40571. return;
  40572. }
  40573. this._colorCurvesEnabled = value;
  40574. this._updateParameters();
  40575. },
  40576. enumerable: true,
  40577. configurable: true
  40578. });
  40579. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40580. /**
  40581. * Gets wether the color grading effect is enabled.
  40582. */
  40583. get: function () {
  40584. return this._colorGradingEnabled;
  40585. },
  40586. /**
  40587. * Sets wether the color grading effect is enabled.
  40588. */
  40589. set: function (value) {
  40590. if (this._colorGradingEnabled === value) {
  40591. return;
  40592. }
  40593. this._colorGradingEnabled = value;
  40594. this._updateParameters();
  40595. },
  40596. enumerable: true,
  40597. configurable: true
  40598. });
  40599. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40600. /**
  40601. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40602. */
  40603. get: function () {
  40604. return this._colorGradingWithGreenDepth;
  40605. },
  40606. /**
  40607. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40608. */
  40609. set: function (value) {
  40610. if (this._colorGradingWithGreenDepth === value) {
  40611. return;
  40612. }
  40613. this._colorGradingWithGreenDepth = value;
  40614. this._updateParameters();
  40615. },
  40616. enumerable: true,
  40617. configurable: true
  40618. });
  40619. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40620. /**
  40621. * Gets wether the color grading texture contains BGR values.
  40622. */
  40623. get: function () {
  40624. return this._colorGradingBGR;
  40625. },
  40626. /**
  40627. * Sets wether the color grading texture contains BGR values.
  40628. */
  40629. set: function (value) {
  40630. if (this._colorGradingBGR === value) {
  40631. return;
  40632. }
  40633. this._colorGradingBGR = value;
  40634. this._updateParameters();
  40635. },
  40636. enumerable: true,
  40637. configurable: true
  40638. });
  40639. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40640. /**
  40641. * Gets the Exposure used in the effect.
  40642. */
  40643. get: function () {
  40644. return this._exposure;
  40645. },
  40646. /**
  40647. * Sets the Exposure used in the effect.
  40648. */
  40649. set: function (value) {
  40650. if (this._exposure === value) {
  40651. return;
  40652. }
  40653. this._exposure = value;
  40654. this._updateParameters();
  40655. },
  40656. enumerable: true,
  40657. configurable: true
  40658. });
  40659. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40660. /**
  40661. * Gets wether the tone mapping effect is enabled.
  40662. */
  40663. get: function () {
  40664. return this._toneMappingEnabled;
  40665. },
  40666. /**
  40667. * Sets wether the tone mapping effect is enabled.
  40668. */
  40669. set: function (value) {
  40670. if (this._toneMappingEnabled === value) {
  40671. return;
  40672. }
  40673. this._toneMappingEnabled = value;
  40674. this._updateParameters();
  40675. },
  40676. enumerable: true,
  40677. configurable: true
  40678. });
  40679. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40680. /**
  40681. * Gets the contrast used in the effect.
  40682. */
  40683. get: function () {
  40684. return this._contrast;
  40685. },
  40686. /**
  40687. * Sets the contrast used in the effect.
  40688. */
  40689. set: function (value) {
  40690. if (this._contrast === value) {
  40691. return;
  40692. }
  40693. this._contrast = value;
  40694. this._updateParameters();
  40695. },
  40696. enumerable: true,
  40697. configurable: true
  40698. });
  40699. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40700. /**
  40701. * Gets the vignette blend mode allowing different kind of effect.
  40702. */
  40703. get: function () {
  40704. return this._vignetteBlendMode;
  40705. },
  40706. /**
  40707. * Sets the vignette blend mode allowing different kind of effect.
  40708. */
  40709. set: function (value) {
  40710. if (this._vignetteBlendMode === value) {
  40711. return;
  40712. }
  40713. this._vignetteBlendMode = value;
  40714. this._updateParameters();
  40715. },
  40716. enumerable: true,
  40717. configurable: true
  40718. });
  40719. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40720. /**
  40721. * Gets wether the vignette effect is enabled.
  40722. */
  40723. get: function () {
  40724. return this._vignetteEnabled;
  40725. },
  40726. /**
  40727. * Sets wether the vignette effect is enabled.
  40728. */
  40729. set: function (value) {
  40730. if (this._vignetteEnabled === value) {
  40731. return;
  40732. }
  40733. this._vignetteEnabled = value;
  40734. this._updateParameters();
  40735. },
  40736. enumerable: true,
  40737. configurable: true
  40738. });
  40739. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40740. /**
  40741. * Gets wether the image processing is applied through a post process or not.
  40742. */
  40743. get: function () {
  40744. return this._applyByPostProcess;
  40745. },
  40746. /**
  40747. * Sets wether the image processing is applied through a post process or not.
  40748. */
  40749. set: function (value) {
  40750. if (this._applyByPostProcess === value) {
  40751. return;
  40752. }
  40753. this._applyByPostProcess = value;
  40754. this._updateParameters();
  40755. },
  40756. enumerable: true,
  40757. configurable: true
  40758. });
  40759. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40760. /**
  40761. * Gets wether the image processing is enabled or not.
  40762. */
  40763. get: function () {
  40764. return this._isEnabled;
  40765. },
  40766. /**
  40767. * Sets wether the image processing is enabled or not.
  40768. */
  40769. set: function (value) {
  40770. if (this._isEnabled === value) {
  40771. return;
  40772. }
  40773. this._isEnabled = value;
  40774. this._updateParameters();
  40775. },
  40776. enumerable: true,
  40777. configurable: true
  40778. });
  40779. /**
  40780. * Method called each time the image processing information changes requires to recompile the effect.
  40781. */
  40782. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40783. this.onUpdateParameters.notifyObservers(this);
  40784. };
  40785. ImageProcessingConfiguration.prototype.getClassName = function () {
  40786. return "ImageProcessingConfiguration";
  40787. };
  40788. /**
  40789. * Prepare the list of uniforms associated with the Image Processing effects.
  40790. * @param uniformsList The list of uniforms used in the effect
  40791. * @param defines the list of defines currently in use
  40792. */
  40793. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40794. if (defines.EXPOSURE) {
  40795. uniforms.push("exposureLinear");
  40796. }
  40797. if (defines.CONTRAST) {
  40798. uniforms.push("contrast");
  40799. }
  40800. if (defines.COLORGRADING) {
  40801. uniforms.push("colorTransformSettings");
  40802. }
  40803. if (defines.VIGNETTE) {
  40804. uniforms.push("vInverseScreenSize");
  40805. uniforms.push("vignetteSettings1");
  40806. uniforms.push("vignetteSettings2");
  40807. }
  40808. if (defines.COLORCURVES) {
  40809. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40810. }
  40811. };
  40812. /**
  40813. * Prepare the list of samplers associated with the Image Processing effects.
  40814. * @param uniformsList The list of uniforms used in the effect
  40815. * @param defines the list of defines currently in use
  40816. */
  40817. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40818. if (defines.COLORGRADING) {
  40819. samplersList.push("txColorTransform");
  40820. }
  40821. };
  40822. /**
  40823. * Prepare the list of defines associated to the shader.
  40824. * @param defines the list of defines to complete
  40825. */
  40826. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40827. if (forPostProcess === void 0) { forPostProcess = false; }
  40828. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40829. defines.VIGNETTE = false;
  40830. defines.TONEMAPPING = false;
  40831. defines.CONTRAST = false;
  40832. defines.EXPOSURE = false;
  40833. defines.COLORCURVES = false;
  40834. defines.COLORGRADING = false;
  40835. defines.COLORGRADING3D = false;
  40836. defines.IMAGEPROCESSING = false;
  40837. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40838. return;
  40839. }
  40840. defines.VIGNETTE = this.vignetteEnabled;
  40841. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40842. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40843. defines.TONEMAPPING = this.toneMappingEnabled;
  40844. defines.CONTRAST = (this.contrast !== 1.0);
  40845. defines.EXPOSURE = (this.exposure !== 1.0);
  40846. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40847. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40848. if (defines.COLORGRADING) {
  40849. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40850. }
  40851. else {
  40852. defines.COLORGRADING3D = false;
  40853. }
  40854. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40855. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40856. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40857. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40858. };
  40859. /**
  40860. * Returns true if all the image processing information are ready.
  40861. */
  40862. ImageProcessingConfiguration.prototype.isReady = function () {
  40863. // Color Grading texure can not be none blocking.
  40864. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40865. };
  40866. /**
  40867. * Binds the image processing to the shader.
  40868. * @param effect The effect to bind to
  40869. */
  40870. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40871. if (aspectRatio === void 0) { aspectRatio = 1; }
  40872. // Color Curves
  40873. if (this._colorCurvesEnabled && this.colorCurves) {
  40874. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40875. }
  40876. // Vignette
  40877. if (this._vignetteEnabled) {
  40878. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40879. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40880. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40881. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40882. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40883. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40884. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40885. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40886. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40887. var vignettePower = -2.0 * this.vignetteWeight;
  40888. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40889. }
  40890. // Exposure
  40891. effect.setFloat("exposureLinear", this.exposure);
  40892. // Contrast
  40893. effect.setFloat("contrast", this.contrast);
  40894. // Color transform settings
  40895. if (this.colorGradingTexture) {
  40896. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40897. var textureSize = this.colorGradingTexture.getSize().height;
  40898. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40899. 0.5 / textureSize, // textureOffset
  40900. textureSize, // textureSize
  40901. this.colorGradingTexture.level // weight
  40902. );
  40903. }
  40904. };
  40905. /**
  40906. * Clones the current image processing instance.
  40907. * @return The cloned image processing
  40908. */
  40909. ImageProcessingConfiguration.prototype.clone = function () {
  40910. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40911. };
  40912. /**
  40913. * Serializes the current image processing instance to a json representation.
  40914. * @return a JSON representation
  40915. */
  40916. ImageProcessingConfiguration.prototype.serialize = function () {
  40917. return BABYLON.SerializationHelper.Serialize(this);
  40918. };
  40919. /**
  40920. * Parses the image processing from a json representation.
  40921. * @param source the JSON source to parse
  40922. * @return The parsed image processing
  40923. */
  40924. ImageProcessingConfiguration.Parse = function (source) {
  40925. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40926. };
  40927. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40928. /**
  40929. * Used to apply the vignette as a mix with the pixel color.
  40930. */
  40931. get: function () {
  40932. return this._VIGNETTEMODE_MULTIPLY;
  40933. },
  40934. enumerable: true,
  40935. configurable: true
  40936. });
  40937. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40938. /**
  40939. * Used to apply the vignette as a replacement of the pixel color.
  40940. */
  40941. get: function () {
  40942. return this._VIGNETTEMODE_OPAQUE;
  40943. },
  40944. enumerable: true,
  40945. configurable: true
  40946. });
  40947. // Static constants associated to the image processing.
  40948. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40949. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40950. __decorate([
  40951. BABYLON.serializeAsColorCurves()
  40952. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40953. __decorate([
  40954. BABYLON.serialize()
  40955. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40956. __decorate([
  40957. BABYLON.serializeAsTexture()
  40958. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40959. __decorate([
  40960. BABYLON.serialize()
  40961. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40962. __decorate([
  40963. BABYLON.serialize()
  40964. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40965. __decorate([
  40966. BABYLON.serialize()
  40967. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40968. __decorate([
  40969. BABYLON.serialize()
  40970. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40971. __decorate([
  40972. BABYLON.serialize()
  40973. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40974. __decorate([
  40975. BABYLON.serialize()
  40976. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40977. __decorate([
  40978. BABYLON.serialize()
  40979. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40980. __decorate([
  40981. BABYLON.serialize()
  40982. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40983. __decorate([
  40984. BABYLON.serialize()
  40985. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40986. __decorate([
  40987. BABYLON.serialize()
  40988. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40989. __decorate([
  40990. BABYLON.serializeAsColor4()
  40991. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40992. __decorate([
  40993. BABYLON.serialize()
  40994. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40995. __decorate([
  40996. BABYLON.serialize()
  40997. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40998. __decorate([
  40999. BABYLON.serialize()
  41000. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41001. __decorate([
  41002. BABYLON.serialize()
  41003. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41004. __decorate([
  41005. BABYLON.serialize()
  41006. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41007. return ImageProcessingConfiguration;
  41008. }());
  41009. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41010. })(BABYLON || (BABYLON = {}));
  41011. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41012. var BABYLON;
  41013. (function (BABYLON) {
  41014. /**
  41015. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41016. * It can help converting any input color in a desired output one. This can then be used to create effects
  41017. * from sepia, black and white to sixties or futuristic rendering...
  41018. *
  41019. * The only supported format is currently 3dl.
  41020. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41021. */
  41022. var ColorGradingTexture = /** @class */ (function (_super) {
  41023. __extends(ColorGradingTexture, _super);
  41024. /**
  41025. * Instantiates a ColorGradingTexture from the following parameters.
  41026. *
  41027. * @param url The location of the color gradind data (currently only supporting 3dl)
  41028. * @param scene The scene the texture will be used in
  41029. */
  41030. function ColorGradingTexture(url, scene) {
  41031. var _this = _super.call(this, scene) || this;
  41032. if (!url) {
  41033. return _this;
  41034. }
  41035. _this._engine = scene.getEngine();
  41036. _this._textureMatrix = BABYLON.Matrix.Identity();
  41037. _this.name = url;
  41038. _this.url = url;
  41039. _this.hasAlpha = false;
  41040. _this.isCube = false;
  41041. _this.is3D = _this._engine.webGLVersion > 1;
  41042. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41043. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41044. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41045. _this.anisotropicFilteringLevel = 1;
  41046. _this._texture = _this._getFromCache(url, true);
  41047. if (!_this._texture) {
  41048. if (!scene.useDelayedTextureLoading) {
  41049. _this.loadTexture();
  41050. }
  41051. else {
  41052. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41053. }
  41054. }
  41055. return _this;
  41056. }
  41057. /**
  41058. * Returns the texture matrix used in most of the material.
  41059. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41060. */
  41061. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41062. return this._textureMatrix;
  41063. };
  41064. /**
  41065. * Occurs when the file being loaded is a .3dl LUT file.
  41066. */
  41067. ColorGradingTexture.prototype.load3dlTexture = function () {
  41068. var engine = this._engine;
  41069. var texture;
  41070. if (engine.webGLVersion === 1) {
  41071. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41072. }
  41073. else {
  41074. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41075. }
  41076. this._texture = texture;
  41077. var callback = function (text) {
  41078. if (typeof text !== "string") {
  41079. return;
  41080. }
  41081. var data = null;
  41082. var tempData = null;
  41083. var line;
  41084. var lines = text.split('\n');
  41085. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41086. var maxColor = 0;
  41087. for (var i = 0; i < lines.length; i++) {
  41088. line = lines[i];
  41089. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41090. continue;
  41091. if (line.indexOf('#') === 0)
  41092. continue;
  41093. var words = line.split(" ");
  41094. if (size === 0) {
  41095. // Number of space + one
  41096. size = words.length;
  41097. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41098. tempData = new Float32Array(size * size * size * 4);
  41099. continue;
  41100. }
  41101. if (size != 0) {
  41102. var r = Math.max(parseInt(words[0]), 0);
  41103. var g = Math.max(parseInt(words[1]), 0);
  41104. var b = Math.max(parseInt(words[2]), 0);
  41105. maxColor = Math.max(r, maxColor);
  41106. maxColor = Math.max(g, maxColor);
  41107. maxColor = Math.max(b, maxColor);
  41108. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41109. if (tempData) {
  41110. tempData[pixelStorageIndex + 0] = r;
  41111. tempData[pixelStorageIndex + 1] = g;
  41112. tempData[pixelStorageIndex + 2] = b;
  41113. }
  41114. pixelIndexSlice++;
  41115. if (pixelIndexSlice % size == 0) {
  41116. pixelIndexH++;
  41117. pixelIndexSlice = 0;
  41118. if (pixelIndexH % size == 0) {
  41119. pixelIndexW++;
  41120. pixelIndexH = 0;
  41121. }
  41122. }
  41123. }
  41124. }
  41125. if (tempData && data) {
  41126. for (var i = 0; i < tempData.length; i++) {
  41127. if (i > 0 && (i + 1) % 4 === 0) {
  41128. data[i] = 255;
  41129. }
  41130. else {
  41131. var value = tempData[i];
  41132. data[i] = (value / maxColor * 255);
  41133. }
  41134. }
  41135. }
  41136. if (texture.is3D) {
  41137. texture.updateSize(size, size, size);
  41138. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41139. }
  41140. else {
  41141. texture.updateSize(size * size, size);
  41142. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41143. }
  41144. };
  41145. var scene = this.getScene();
  41146. if (scene) {
  41147. scene._loadFile(this.url, callback);
  41148. }
  41149. else {
  41150. this._engine._loadFile(this.url, callback);
  41151. }
  41152. return this._texture;
  41153. };
  41154. /**
  41155. * Starts the loading process of the texture.
  41156. */
  41157. ColorGradingTexture.prototype.loadTexture = function () {
  41158. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41159. this.load3dlTexture();
  41160. }
  41161. };
  41162. /**
  41163. * Clones the color gradind texture.
  41164. */
  41165. ColorGradingTexture.prototype.clone = function () {
  41166. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41167. // Base texture
  41168. newTexture.level = this.level;
  41169. return newTexture;
  41170. };
  41171. /**
  41172. * Called during delayed load for textures.
  41173. */
  41174. ColorGradingTexture.prototype.delayLoad = function () {
  41175. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41176. return;
  41177. }
  41178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41179. this._texture = this._getFromCache(this.url, true);
  41180. if (!this._texture) {
  41181. this.loadTexture();
  41182. }
  41183. };
  41184. /**
  41185. * Parses a color grading texture serialized by Babylon.
  41186. * @param parsedTexture The texture information being parsedTexture
  41187. * @param scene The scene to load the texture in
  41188. * @param rootUrl The root url of the data assets to load
  41189. * @return A color gradind texture
  41190. */
  41191. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41192. var texture = null;
  41193. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41194. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41195. texture.name = parsedTexture.name;
  41196. texture.level = parsedTexture.level;
  41197. }
  41198. return texture;
  41199. };
  41200. /**
  41201. * Serializes the LUT texture to json format.
  41202. */
  41203. ColorGradingTexture.prototype.serialize = function () {
  41204. if (!this.name) {
  41205. return null;
  41206. }
  41207. var serializationObject = {};
  41208. serializationObject.name = this.name;
  41209. serializationObject.level = this.level;
  41210. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41211. return serializationObject;
  41212. };
  41213. /**
  41214. * Empty line regex stored for GC.
  41215. */
  41216. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41217. return ColorGradingTexture;
  41218. }(BABYLON.BaseTexture));
  41219. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41220. })(BABYLON || (BABYLON = {}));
  41221. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41222. var BABYLON;
  41223. (function (BABYLON) {
  41224. /**
  41225. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41226. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41227. * 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;
  41228. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41229. */
  41230. var ColorCurves = /** @class */ (function () {
  41231. function ColorCurves() {
  41232. this._dirty = true;
  41233. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41234. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41235. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41236. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41237. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41238. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41239. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41240. this._globalHue = 30;
  41241. this._globalDensity = 0;
  41242. this._globalSaturation = 0;
  41243. this._globalExposure = 0;
  41244. this._highlightsHue = 30;
  41245. this._highlightsDensity = 0;
  41246. this._highlightsSaturation = 0;
  41247. this._highlightsExposure = 0;
  41248. this._midtonesHue = 30;
  41249. this._midtonesDensity = 0;
  41250. this._midtonesSaturation = 0;
  41251. this._midtonesExposure = 0;
  41252. this._shadowsHue = 30;
  41253. this._shadowsDensity = 0;
  41254. this._shadowsSaturation = 0;
  41255. this._shadowsExposure = 0;
  41256. }
  41257. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41258. /**
  41259. * Gets the global Hue value.
  41260. * 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).
  41261. */
  41262. get: function () {
  41263. return this._globalHue;
  41264. },
  41265. /**
  41266. * Sets the global Hue value.
  41267. * 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).
  41268. */
  41269. set: function (value) {
  41270. this._globalHue = value;
  41271. this._dirty = true;
  41272. },
  41273. enumerable: true,
  41274. configurable: true
  41275. });
  41276. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41277. /**
  41278. * Gets the global Density value.
  41279. * 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.
  41280. * Values less than zero provide a filter of opposite hue.
  41281. */
  41282. get: function () {
  41283. return this._globalDensity;
  41284. },
  41285. /**
  41286. * Sets the global Density value.
  41287. * 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.
  41288. * Values less than zero provide a filter of opposite hue.
  41289. */
  41290. set: function (value) {
  41291. this._globalDensity = value;
  41292. this._dirty = true;
  41293. },
  41294. enumerable: true,
  41295. configurable: true
  41296. });
  41297. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41298. /**
  41299. * Gets the global Saturation value.
  41300. * 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.
  41301. */
  41302. get: function () {
  41303. return this._globalSaturation;
  41304. },
  41305. /**
  41306. * Sets the global Saturation value.
  41307. * 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.
  41308. */
  41309. set: function (value) {
  41310. this._globalSaturation = value;
  41311. this._dirty = true;
  41312. },
  41313. enumerable: true,
  41314. configurable: true
  41315. });
  41316. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41317. /**
  41318. * Gets the highlights Hue value.
  41319. * 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).
  41320. */
  41321. get: function () {
  41322. return this._highlightsHue;
  41323. },
  41324. /**
  41325. * Sets the highlights Hue value.
  41326. * 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).
  41327. */
  41328. set: function (value) {
  41329. this._highlightsHue = value;
  41330. this._dirty = true;
  41331. },
  41332. enumerable: true,
  41333. configurable: true
  41334. });
  41335. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41336. /**
  41337. * Gets the highlights Density value.
  41338. * 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.
  41339. * Values less than zero provide a filter of opposite hue.
  41340. */
  41341. get: function () {
  41342. return this._highlightsDensity;
  41343. },
  41344. /**
  41345. * Sets the highlights Density value.
  41346. * 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.
  41347. * Values less than zero provide a filter of opposite hue.
  41348. */
  41349. set: function (value) {
  41350. this._highlightsDensity = value;
  41351. this._dirty = true;
  41352. },
  41353. enumerable: true,
  41354. configurable: true
  41355. });
  41356. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41357. /**
  41358. * Gets the highlights Saturation value.
  41359. * 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.
  41360. */
  41361. get: function () {
  41362. return this._highlightsSaturation;
  41363. },
  41364. /**
  41365. * Sets the highlights Saturation value.
  41366. * 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.
  41367. */
  41368. set: function (value) {
  41369. this._highlightsSaturation = value;
  41370. this._dirty = true;
  41371. },
  41372. enumerable: true,
  41373. configurable: true
  41374. });
  41375. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41376. /**
  41377. * Gets the highlights Exposure value.
  41378. * 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.
  41379. */
  41380. get: function () {
  41381. return this._highlightsExposure;
  41382. },
  41383. /**
  41384. * Sets the highlights Exposure value.
  41385. * 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.
  41386. */
  41387. set: function (value) {
  41388. this._highlightsExposure = value;
  41389. this._dirty = true;
  41390. },
  41391. enumerable: true,
  41392. configurable: true
  41393. });
  41394. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41395. /**
  41396. * Gets the midtones Hue value.
  41397. * 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).
  41398. */
  41399. get: function () {
  41400. return this._midtonesHue;
  41401. },
  41402. /**
  41403. * Sets the midtones Hue value.
  41404. * 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).
  41405. */
  41406. set: function (value) {
  41407. this._midtonesHue = value;
  41408. this._dirty = true;
  41409. },
  41410. enumerable: true,
  41411. configurable: true
  41412. });
  41413. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41414. /**
  41415. * Gets the midtones Density value.
  41416. * 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.
  41417. * Values less than zero provide a filter of opposite hue.
  41418. */
  41419. get: function () {
  41420. return this._midtonesDensity;
  41421. },
  41422. /**
  41423. * Sets the midtones Density value.
  41424. * 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.
  41425. * Values less than zero provide a filter of opposite hue.
  41426. */
  41427. set: function (value) {
  41428. this._midtonesDensity = value;
  41429. this._dirty = true;
  41430. },
  41431. enumerable: true,
  41432. configurable: true
  41433. });
  41434. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41435. /**
  41436. * Gets the midtones Saturation value.
  41437. * 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.
  41438. */
  41439. get: function () {
  41440. return this._midtonesSaturation;
  41441. },
  41442. /**
  41443. * Sets the midtones Saturation value.
  41444. * 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.
  41445. */
  41446. set: function (value) {
  41447. this._midtonesSaturation = value;
  41448. this._dirty = true;
  41449. },
  41450. enumerable: true,
  41451. configurable: true
  41452. });
  41453. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41454. /**
  41455. * Gets the midtones Exposure value.
  41456. * 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.
  41457. */
  41458. get: function () {
  41459. return this._midtonesExposure;
  41460. },
  41461. /**
  41462. * Sets the midtones Exposure value.
  41463. * 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.
  41464. */
  41465. set: function (value) {
  41466. this._midtonesExposure = value;
  41467. this._dirty = true;
  41468. },
  41469. enumerable: true,
  41470. configurable: true
  41471. });
  41472. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41473. /**
  41474. * Gets the shadows Hue value.
  41475. * 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).
  41476. */
  41477. get: function () {
  41478. return this._shadowsHue;
  41479. },
  41480. /**
  41481. * Sets the shadows Hue value.
  41482. * 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).
  41483. */
  41484. set: function (value) {
  41485. this._shadowsHue = value;
  41486. this._dirty = true;
  41487. },
  41488. enumerable: true,
  41489. configurable: true
  41490. });
  41491. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41492. /**
  41493. * Gets the shadows Density value.
  41494. * 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.
  41495. * Values less than zero provide a filter of opposite hue.
  41496. */
  41497. get: function () {
  41498. return this._shadowsDensity;
  41499. },
  41500. /**
  41501. * Sets the shadows Density value.
  41502. * 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.
  41503. * Values less than zero provide a filter of opposite hue.
  41504. */
  41505. set: function (value) {
  41506. this._shadowsDensity = value;
  41507. this._dirty = true;
  41508. },
  41509. enumerable: true,
  41510. configurable: true
  41511. });
  41512. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41513. /**
  41514. * Gets the shadows Saturation value.
  41515. * 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.
  41516. */
  41517. get: function () {
  41518. return this._shadowsSaturation;
  41519. },
  41520. /**
  41521. * Sets the shadows Saturation value.
  41522. * 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.
  41523. */
  41524. set: function (value) {
  41525. this._shadowsSaturation = value;
  41526. this._dirty = true;
  41527. },
  41528. enumerable: true,
  41529. configurable: true
  41530. });
  41531. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41532. /**
  41533. * Gets the shadows Exposure value.
  41534. * 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.
  41535. */
  41536. get: function () {
  41537. return this._shadowsExposure;
  41538. },
  41539. /**
  41540. * Sets the shadows Exposure value.
  41541. * 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.
  41542. */
  41543. set: function (value) {
  41544. this._shadowsExposure = value;
  41545. this._dirty = true;
  41546. },
  41547. enumerable: true,
  41548. configurable: true
  41549. });
  41550. ColorCurves.prototype.getClassName = function () {
  41551. return "ColorCurves";
  41552. };
  41553. /**
  41554. * Binds the color curves to the shader.
  41555. * @param colorCurves The color curve to bind
  41556. * @param effect The effect to bind to
  41557. */
  41558. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41559. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41560. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41561. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41562. if (colorCurves._dirty) {
  41563. colorCurves._dirty = false;
  41564. // Fill in global info.
  41565. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41566. // Compute highlights info.
  41567. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41568. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41569. // Compute midtones info.
  41570. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41571. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41572. // Compute shadows info.
  41573. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41574. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41575. // Compute deltas (neutral is midtones).
  41576. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41577. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41578. }
  41579. if (effect) {
  41580. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41581. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41582. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41583. }
  41584. };
  41585. /**
  41586. * Prepare the list of uniforms associated with the ColorCurves effects.
  41587. * @param uniformsList The list of uniforms used in the effect
  41588. */
  41589. ColorCurves.PrepareUniforms = function (uniformsList) {
  41590. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41591. };
  41592. /**
  41593. * Returns color grading data based on a hue, density, saturation and exposure value.
  41594. * @param filterHue The hue of the color filter.
  41595. * @param filterDensity The density of the color filter.
  41596. * @param saturation The saturation.
  41597. * @param exposure The exposure.
  41598. * @param result The result data container.
  41599. */
  41600. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41601. if (hue == null) {
  41602. return;
  41603. }
  41604. hue = ColorCurves.clamp(hue, 0, 360);
  41605. density = ColorCurves.clamp(density, -100, 100);
  41606. saturation = ColorCurves.clamp(saturation, -100, 100);
  41607. exposure = ColorCurves.clamp(exposure, -100, 100);
  41608. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41609. // so that the maximum filter density is only 50% control. This provides fine control
  41610. // for small values and reasonable range.
  41611. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41612. density *= 0.5;
  41613. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41614. if (density < 0) {
  41615. density *= -1;
  41616. hue = (hue + 180) % 360;
  41617. }
  41618. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41619. result.scaleToRef(2, result);
  41620. result.a = 1 + 0.01 * saturation;
  41621. };
  41622. /**
  41623. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41624. * @param value The input slider value in range [-100,100].
  41625. * @returns Adjusted value.
  41626. */
  41627. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41628. value /= 100;
  41629. var x = Math.abs(value);
  41630. x = Math.pow(x, 2);
  41631. if (value < 0) {
  41632. x *= -1;
  41633. }
  41634. x *= 100;
  41635. return x;
  41636. };
  41637. /**
  41638. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41639. * @param hue The hue (H) input.
  41640. * @param saturation The saturation (S) input.
  41641. * @param brightness The brightness (B) input.
  41642. * @result An RGBA color represented as Vector4.
  41643. */
  41644. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41645. var h = ColorCurves.clamp(hue, 0, 360);
  41646. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41647. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41648. if (s === 0) {
  41649. result.r = v;
  41650. result.g = v;
  41651. result.b = v;
  41652. }
  41653. else {
  41654. // sector 0 to 5
  41655. h /= 60;
  41656. var i = Math.floor(h);
  41657. // fractional part of h
  41658. var f = h - i;
  41659. var p = v * (1 - s);
  41660. var q = v * (1 - s * f);
  41661. var t = v * (1 - s * (1 - f));
  41662. switch (i) {
  41663. case 0:
  41664. result.r = v;
  41665. result.g = t;
  41666. result.b = p;
  41667. break;
  41668. case 1:
  41669. result.r = q;
  41670. result.g = v;
  41671. result.b = p;
  41672. break;
  41673. case 2:
  41674. result.r = p;
  41675. result.g = v;
  41676. result.b = t;
  41677. break;
  41678. case 3:
  41679. result.r = p;
  41680. result.g = q;
  41681. result.b = v;
  41682. break;
  41683. case 4:
  41684. result.r = t;
  41685. result.g = p;
  41686. result.b = v;
  41687. break;
  41688. default: // case 5:
  41689. result.r = v;
  41690. result.g = p;
  41691. result.b = q;
  41692. break;
  41693. }
  41694. }
  41695. result.a = 1;
  41696. };
  41697. /**
  41698. * Returns a value clamped between min and max
  41699. * @param value The value to clamp
  41700. * @param min The minimum of value
  41701. * @param max The maximum of value
  41702. * @returns The clamped value.
  41703. */
  41704. ColorCurves.clamp = function (value, min, max) {
  41705. return Math.min(Math.max(value, min), max);
  41706. };
  41707. /**
  41708. * Clones the current color curve instance.
  41709. * @return The cloned curves
  41710. */
  41711. ColorCurves.prototype.clone = function () {
  41712. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41713. };
  41714. /**
  41715. * Serializes the current color curve instance to a json representation.
  41716. * @return a JSON representation
  41717. */
  41718. ColorCurves.prototype.serialize = function () {
  41719. return BABYLON.SerializationHelper.Serialize(this);
  41720. };
  41721. /**
  41722. * Parses the color curve from a json representation.
  41723. * @param source the JSON source to parse
  41724. * @return The parsed curves
  41725. */
  41726. ColorCurves.Parse = function (source) {
  41727. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41728. };
  41729. __decorate([
  41730. BABYLON.serialize()
  41731. ], ColorCurves.prototype, "_globalHue", void 0);
  41732. __decorate([
  41733. BABYLON.serialize()
  41734. ], ColorCurves.prototype, "_globalDensity", void 0);
  41735. __decorate([
  41736. BABYLON.serialize()
  41737. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41738. __decorate([
  41739. BABYLON.serialize()
  41740. ], ColorCurves.prototype, "_globalExposure", void 0);
  41741. __decorate([
  41742. BABYLON.serialize()
  41743. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41744. __decorate([
  41745. BABYLON.serialize()
  41746. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41747. __decorate([
  41748. BABYLON.serialize()
  41749. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41750. __decorate([
  41751. BABYLON.serialize()
  41752. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41753. __decorate([
  41754. BABYLON.serialize()
  41755. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41756. __decorate([
  41757. BABYLON.serialize()
  41758. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41759. __decorate([
  41760. BABYLON.serialize()
  41761. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41762. __decorate([
  41763. BABYLON.serialize()
  41764. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41765. return ColorCurves;
  41766. }());
  41767. BABYLON.ColorCurves = ColorCurves;
  41768. })(BABYLON || (BABYLON = {}));
  41769. //# sourceMappingURL=babylon.colorCurves.js.map
  41770. //# sourceMappingURL=babylon.behavior.js.map
  41771. var BABYLON;
  41772. (function (BABYLON) {
  41773. /**
  41774. * "Static Class" containing the most commonly used helper while dealing with material for
  41775. * rendering purpose.
  41776. *
  41777. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41778. *
  41779. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41780. */
  41781. var MaterialHelper = /** @class */ (function () {
  41782. function MaterialHelper() {
  41783. }
  41784. /**
  41785. * Bind the current view position to an effect.
  41786. * @param effect The effect to be bound
  41787. * @param scene The scene the eyes position is used from
  41788. */
  41789. MaterialHelper.BindEyePosition = function (effect, scene) {
  41790. if (scene._forcedViewPosition) {
  41791. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41792. return;
  41793. }
  41794. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41795. };
  41796. /**
  41797. * Helps preparing the defines values about the UVs in used in the effect.
  41798. * UVs are shared as much as we can accross chanels in the shaders.
  41799. * @param texture The texture we are preparing the UVs for
  41800. * @param defines The defines to update
  41801. * @param key The chanel key "diffuse", "specular"... used in the shader
  41802. */
  41803. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41804. defines._needUVs = true;
  41805. defines[key] = true;
  41806. if (texture.getTextureMatrix().isIdentity(true)) {
  41807. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41808. if (texture.coordinatesIndex === 0) {
  41809. defines["MAINUV1"] = true;
  41810. }
  41811. else {
  41812. defines["MAINUV2"] = true;
  41813. }
  41814. }
  41815. else {
  41816. defines[key + "DIRECTUV"] = 0;
  41817. }
  41818. };
  41819. /**
  41820. * Binds a texture matrix value to its corrsponding uniform
  41821. * @param texture The texture to bind the matrix for
  41822. * @param uniformBuffer The uniform buffer receivin the data
  41823. * @param key The chanel key "diffuse", "specular"... used in the shader
  41824. */
  41825. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41826. var matrix = texture.getTextureMatrix();
  41827. if (!matrix.isIdentity(true)) {
  41828. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41829. }
  41830. };
  41831. /**
  41832. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41833. * @param mesh defines the current mesh
  41834. * @param scene defines the current scene
  41835. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41836. * @param pointsCloud defines if point cloud rendering has to be turned on
  41837. * @param fogEnabled defines if fog has to be turned on
  41838. * @param alphaTest defines if alpha testing has to be turned on
  41839. * @param defines defines the current list of defines
  41840. */
  41841. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41842. if (defines._areMiscDirty) {
  41843. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41844. defines["POINTSIZE"] = pointsCloud;
  41845. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41846. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41847. defines["ALPHATEST"] = alphaTest;
  41848. }
  41849. };
  41850. /**
  41851. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41852. * @param scene defines the current scene
  41853. * @param engine defines the current engine
  41854. * @param defines specifies the list of active defines
  41855. * @param useInstances defines if instances have to be turned on
  41856. * @param useClipPlane defines if clip plane have to be turned on
  41857. */
  41858. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41859. if (useClipPlane === void 0) { useClipPlane = null; }
  41860. var changed = false;
  41861. if (useClipPlane == null) {
  41862. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41863. }
  41864. if (defines["CLIPPLANE"] !== useClipPlane) {
  41865. defines["CLIPPLANE"] = useClipPlane;
  41866. changed = true;
  41867. }
  41868. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41869. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41870. changed = true;
  41871. }
  41872. if (defines["INSTANCES"] !== useInstances) {
  41873. defines["INSTANCES"] = useInstances;
  41874. changed = true;
  41875. }
  41876. if (changed) {
  41877. defines.markAsUnprocessed();
  41878. }
  41879. };
  41880. /**
  41881. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41882. * @param mesh The mesh containing the geometry data we will draw
  41883. * @param defines The defines to update
  41884. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41885. * @param useBones Precise whether bones should be used or not (override mesh info)
  41886. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41887. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41888. * @returns false if defines are considered not dirty and have not been checked
  41889. */
  41890. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41891. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41892. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41893. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41894. return false;
  41895. }
  41896. defines._normals = defines._needNormals;
  41897. defines._uvs = defines._needUVs;
  41898. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41899. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41900. defines["TANGENT"] = true;
  41901. }
  41902. if (defines._needUVs) {
  41903. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41904. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41905. }
  41906. else {
  41907. defines["UV1"] = false;
  41908. defines["UV2"] = false;
  41909. }
  41910. if (useVertexColor) {
  41911. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41912. defines["VERTEXCOLOR"] = hasVertexColors;
  41913. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41914. }
  41915. if (useBones) {
  41916. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41917. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41918. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41919. }
  41920. else {
  41921. defines["NUM_BONE_INFLUENCERS"] = 0;
  41922. defines["BonesPerMesh"] = 0;
  41923. }
  41924. }
  41925. if (useMorphTargets) {
  41926. var manager = mesh.morphTargetManager;
  41927. if (manager) {
  41928. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41929. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41930. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41931. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41932. }
  41933. else {
  41934. defines["MORPHTARGETS_TANGENT"] = false;
  41935. defines["MORPHTARGETS_NORMAL"] = false;
  41936. defines["MORPHTARGETS"] = false;
  41937. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41938. }
  41939. }
  41940. return true;
  41941. };
  41942. /**
  41943. * Prepares the defines related to the light information passed in parameter
  41944. * @param scene The scene we are intending to draw
  41945. * @param mesh The mesh the effect is compiling for
  41946. * @param defines The defines to update
  41947. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41948. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41949. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41950. * @returns true if normals will be required for the rest of the effect
  41951. */
  41952. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41953. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41954. if (disableLighting === void 0) { disableLighting = false; }
  41955. if (!defines._areLightsDirty) {
  41956. return defines._needNormals;
  41957. }
  41958. var lightIndex = 0;
  41959. var needNormals = false;
  41960. var needRebuild = false;
  41961. var lightmapMode = false;
  41962. var shadowEnabled = false;
  41963. var specularEnabled = false;
  41964. if (scene.lightsEnabled && !disableLighting) {
  41965. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41966. var light = _a[_i];
  41967. needNormals = true;
  41968. if (defines["LIGHT" + lightIndex] === undefined) {
  41969. needRebuild = true;
  41970. }
  41971. defines["LIGHT" + lightIndex] = true;
  41972. defines["SPOTLIGHT" + lightIndex] = false;
  41973. defines["HEMILIGHT" + lightIndex] = false;
  41974. defines["POINTLIGHT" + lightIndex] = false;
  41975. defines["DIRLIGHT" + lightIndex] = false;
  41976. var type;
  41977. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41978. type = "SPOTLIGHT" + lightIndex;
  41979. var spotLight = light;
  41980. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41981. }
  41982. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41983. type = "HEMILIGHT" + lightIndex;
  41984. }
  41985. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41986. type = "POINTLIGHT" + lightIndex;
  41987. }
  41988. else {
  41989. type = "DIRLIGHT" + lightIndex;
  41990. }
  41991. defines[type] = true;
  41992. // Specular
  41993. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41994. specularEnabled = true;
  41995. }
  41996. // Shadows
  41997. defines["SHADOW" + lightIndex] = false;
  41998. defines["SHADOWPCF" + lightIndex] = false;
  41999. defines["SHADOWPCSS" + lightIndex] = false;
  42000. defines["SHADOWPOISSON" + lightIndex] = false;
  42001. defines["SHADOWESM" + lightIndex] = false;
  42002. defines["SHADOWCUBE" + lightIndex] = false;
  42003. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42004. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42005. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42006. var shadowGenerator = light.getShadowGenerator();
  42007. if (shadowGenerator) {
  42008. shadowEnabled = true;
  42009. shadowGenerator.prepareDefines(defines, lightIndex);
  42010. }
  42011. }
  42012. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42013. lightmapMode = true;
  42014. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42015. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42016. }
  42017. else {
  42018. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42019. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42020. }
  42021. lightIndex++;
  42022. if (lightIndex === maxSimultaneousLights)
  42023. break;
  42024. }
  42025. }
  42026. defines["SPECULARTERM"] = specularEnabled;
  42027. defines["SHADOWS"] = shadowEnabled;
  42028. // Resetting all other lights if any
  42029. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42030. if (defines["LIGHT" + index] !== undefined) {
  42031. defines["LIGHT" + index] = false;
  42032. defines["HEMILIGHT" + lightIndex] = false;
  42033. defines["POINTLIGHT" + lightIndex] = false;
  42034. defines["DIRLIGHT" + lightIndex] = false;
  42035. defines["SPOTLIGHT" + lightIndex] = false;
  42036. defines["SHADOW" + lightIndex] = false;
  42037. }
  42038. }
  42039. var caps = scene.getEngine().getCaps();
  42040. if (defines["SHADOWFLOAT"] === undefined) {
  42041. needRebuild = true;
  42042. }
  42043. defines["SHADOWFLOAT"] = shadowEnabled &&
  42044. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42045. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42046. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42047. if (needRebuild) {
  42048. defines.rebuild();
  42049. }
  42050. return needNormals;
  42051. };
  42052. /**
  42053. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42054. * that won t be acctive due to defines being turned off.
  42055. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42056. * @param samplersList The samplers list
  42057. * @param defines The defines helping in the list generation
  42058. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42059. */
  42060. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42061. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42062. var uniformsList;
  42063. var uniformBuffersList = null;
  42064. if (uniformsListOrOptions.uniformsNames) {
  42065. var options = uniformsListOrOptions;
  42066. uniformsList = options.uniformsNames;
  42067. uniformBuffersList = options.uniformBuffersNames;
  42068. samplersList = options.samplers;
  42069. defines = options.defines;
  42070. maxSimultaneousLights = options.maxSimultaneousLights;
  42071. }
  42072. else {
  42073. uniformsList = uniformsListOrOptions;
  42074. if (!samplersList) {
  42075. samplersList = [];
  42076. }
  42077. }
  42078. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42079. if (!defines["LIGHT" + lightIndex]) {
  42080. break;
  42081. }
  42082. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42083. if (uniformBuffersList) {
  42084. uniformBuffersList.push("Light" + lightIndex);
  42085. }
  42086. samplersList.push("shadowSampler" + lightIndex);
  42087. samplersList.push("depthSampler" + lightIndex);
  42088. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42089. samplersList.push("projectionLightSampler" + lightIndex);
  42090. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42091. }
  42092. }
  42093. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42094. uniformsList.push("morphTargetInfluences");
  42095. }
  42096. };
  42097. /**
  42098. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42099. * @param defines The defines to update while falling back
  42100. * @param fallbacks The authorized effect fallbacks
  42101. * @param maxSimultaneousLights The maximum number of lights allowed
  42102. * @param rank the current rank of the Effect
  42103. * @returns The newly affected rank
  42104. */
  42105. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42106. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42107. if (rank === void 0) { rank = 0; }
  42108. var lightFallbackRank = 0;
  42109. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42110. if (!defines["LIGHT" + lightIndex]) {
  42111. break;
  42112. }
  42113. if (lightIndex > 0) {
  42114. lightFallbackRank = rank + lightIndex;
  42115. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42116. }
  42117. if (!defines["SHADOWS"]) {
  42118. if (defines["SHADOW" + lightIndex]) {
  42119. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42120. }
  42121. if (defines["SHADOWPCF" + lightIndex]) {
  42122. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42123. }
  42124. if (defines["SHADOWPCSS" + lightIndex]) {
  42125. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42126. }
  42127. if (defines["SHADOWPOISSON" + lightIndex]) {
  42128. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42129. }
  42130. if (defines["SHADOWESM" + lightIndex]) {
  42131. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42132. }
  42133. }
  42134. }
  42135. return lightFallbackRank++;
  42136. };
  42137. /**
  42138. * Prepares the list of attributes required for morph targets according to the effect defines.
  42139. * @param attribs The current list of supported attribs
  42140. * @param mesh The mesh to prepare the morph targets attributes for
  42141. * @param defines The current Defines of the effect
  42142. */
  42143. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42144. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42145. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42146. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42147. var manager = mesh.morphTargetManager;
  42148. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42149. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42150. for (var index = 0; index < influencers; index++) {
  42151. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42152. if (normal) {
  42153. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42154. }
  42155. if (tangent) {
  42156. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42157. }
  42158. if (attribs.length > maxAttributesCount) {
  42159. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42160. }
  42161. }
  42162. }
  42163. };
  42164. /**
  42165. * Prepares the list of attributes required for bones according to the effect defines.
  42166. * @param attribs The current list of supported attribs
  42167. * @param mesh The mesh to prepare the bones attributes for
  42168. * @param defines The current Defines of the effect
  42169. * @param fallbacks The current efffect fallback strategy
  42170. */
  42171. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42172. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42173. fallbacks.addCPUSkinningFallback(0, mesh);
  42174. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42175. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42176. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42177. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42178. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42179. }
  42180. }
  42181. };
  42182. /**
  42183. * Prepares the list of attributes required for instances according to the effect defines.
  42184. * @param attribs The current list of supported attribs
  42185. * @param defines The current Defines of the effect
  42186. */
  42187. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42188. if (defines["INSTANCES"]) {
  42189. attribs.push("world0");
  42190. attribs.push("world1");
  42191. attribs.push("world2");
  42192. attribs.push("world3");
  42193. }
  42194. };
  42195. /**
  42196. * Binds the light shadow information to the effect for the given mesh.
  42197. * @param light The light containing the generator
  42198. * @param scene The scene the lights belongs to
  42199. * @param mesh The mesh we are binding the information to render
  42200. * @param lightIndex The light index in the effect used to render the mesh
  42201. * @param effect The effect we are binding the data to
  42202. */
  42203. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42204. if (light.shadowEnabled && mesh.receiveShadows) {
  42205. var shadowGenerator = light.getShadowGenerator();
  42206. if (shadowGenerator) {
  42207. shadowGenerator.bindShadowLight(lightIndex, effect);
  42208. }
  42209. }
  42210. };
  42211. /**
  42212. * Binds the light information to the effect.
  42213. * @param light The light containing the generator
  42214. * @param effect The effect we are binding the data to
  42215. * @param lightIndex The light index in the effect used to render
  42216. */
  42217. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42218. light.transferToEffect(effect, lightIndex + "");
  42219. };
  42220. /**
  42221. * Binds the lights information from the scene to the effect for the given mesh.
  42222. * @param scene The scene the lights belongs to
  42223. * @param mesh The mesh we are binding the information to render
  42224. * @param effect The effect we are binding the data to
  42225. * @param defines The generated defines for the effect
  42226. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42227. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42228. */
  42229. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42230. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42231. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42232. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42233. for (var i = 0; i < len; i++) {
  42234. var light = mesh._lightSources[i];
  42235. var iAsString = i.toString();
  42236. var scaledIntensity = light.getScaledIntensity();
  42237. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42238. MaterialHelper.BindLightProperties(light, effect, i);
  42239. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42240. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42241. if (defines["SPECULARTERM"]) {
  42242. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42243. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42244. }
  42245. // Shadows
  42246. if (scene.shadowsEnabled) {
  42247. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42248. }
  42249. light._uniformBuffer.update();
  42250. }
  42251. };
  42252. /**
  42253. * Binds the fog information from the scene to the effect for the given mesh.
  42254. * @param scene The scene the lights belongs to
  42255. * @param mesh The mesh we are binding the information to render
  42256. * @param effect The effect we are binding the data to
  42257. */
  42258. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42259. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42260. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42261. effect.setColor3("vFogColor", scene.fogColor);
  42262. }
  42263. };
  42264. /**
  42265. * Binds the bones information from the mesh to the effect.
  42266. * @param mesh The mesh we are binding the information to render
  42267. * @param effect The effect we are binding the data to
  42268. */
  42269. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42270. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42271. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42272. if (matrices && effect) {
  42273. effect.setMatrices("mBones", matrices);
  42274. }
  42275. }
  42276. };
  42277. /**
  42278. * Binds the morph targets information from the mesh to the effect.
  42279. * @param abstractMesh The mesh we are binding the information to render
  42280. * @param effect The effect we are binding the data to
  42281. */
  42282. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42283. var manager = abstractMesh.morphTargetManager;
  42284. if (!abstractMesh || !manager) {
  42285. return;
  42286. }
  42287. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42288. };
  42289. /**
  42290. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42291. * @param defines The generated defines used in the effect
  42292. * @param effect The effect we are binding the data to
  42293. * @param scene The scene we are willing to render with logarithmic scale for
  42294. */
  42295. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42296. if (defines["LOGARITHMICDEPTH"]) {
  42297. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42298. }
  42299. };
  42300. /**
  42301. * Binds the clip plane information from the scene to the effect.
  42302. * @param scene The scene the clip plane information are extracted from
  42303. * @param effect The effect we are binding the data to
  42304. */
  42305. MaterialHelper.BindClipPlane = function (effect, scene) {
  42306. if (scene.clipPlane) {
  42307. var clipPlane = scene.clipPlane;
  42308. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42309. }
  42310. };
  42311. return MaterialHelper;
  42312. }());
  42313. BABYLON.MaterialHelper = MaterialHelper;
  42314. })(BABYLON || (BABYLON = {}));
  42315. //# sourceMappingURL=babylon.materialHelper.js.map
  42316. var BABYLON;
  42317. (function (BABYLON) {
  42318. var PushMaterial = /** @class */ (function (_super) {
  42319. __extends(PushMaterial, _super);
  42320. function PushMaterial(name, scene) {
  42321. var _this = _super.call(this, name, scene) || this;
  42322. _this._normalMatrix = new BABYLON.Matrix();
  42323. _this.storeEffectOnSubMeshes = true;
  42324. return _this;
  42325. }
  42326. PushMaterial.prototype.getEffect = function () {
  42327. return this._activeEffect;
  42328. };
  42329. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42330. if (!mesh) {
  42331. return false;
  42332. }
  42333. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42334. return true;
  42335. }
  42336. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42337. };
  42338. /**
  42339. * Binds the given world matrix to the active effect
  42340. *
  42341. * @param world the matrix to bind
  42342. */
  42343. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42344. this._activeEffect.setMatrix("world", world);
  42345. };
  42346. /**
  42347. * Binds the given normal matrix to the active effect
  42348. *
  42349. * @param normalMatrix the matrix to bind
  42350. */
  42351. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42352. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42353. };
  42354. PushMaterial.prototype.bind = function (world, mesh) {
  42355. if (!mesh) {
  42356. return;
  42357. }
  42358. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42359. };
  42360. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42361. if (effect === void 0) { effect = null; }
  42362. _super.prototype._afterBind.call(this, mesh);
  42363. this.getScene()._cachedEffect = effect;
  42364. };
  42365. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42366. if (visibility === void 0) { visibility = 1; }
  42367. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42368. };
  42369. return PushMaterial;
  42370. }(BABYLON.Material));
  42371. BABYLON.PushMaterial = PushMaterial;
  42372. })(BABYLON || (BABYLON = {}));
  42373. //# sourceMappingURL=babylon.pushMaterial.js.map
  42374. var BABYLON;
  42375. (function (BABYLON) {
  42376. /** @ignore */
  42377. var StandardMaterialDefines = /** @class */ (function (_super) {
  42378. __extends(StandardMaterialDefines, _super);
  42379. function StandardMaterialDefines() {
  42380. var _this = _super.call(this) || this;
  42381. _this.MAINUV1 = false;
  42382. _this.MAINUV2 = false;
  42383. _this.DIFFUSE = false;
  42384. _this.DIFFUSEDIRECTUV = 0;
  42385. _this.AMBIENT = false;
  42386. _this.AMBIENTDIRECTUV = 0;
  42387. _this.OPACITY = false;
  42388. _this.OPACITYDIRECTUV = 0;
  42389. _this.OPACITYRGB = false;
  42390. _this.REFLECTION = false;
  42391. _this.EMISSIVE = false;
  42392. _this.EMISSIVEDIRECTUV = 0;
  42393. _this.SPECULAR = false;
  42394. _this.SPECULARDIRECTUV = 0;
  42395. _this.BUMP = false;
  42396. _this.BUMPDIRECTUV = 0;
  42397. _this.PARALLAX = false;
  42398. _this.PARALLAXOCCLUSION = false;
  42399. _this.SPECULAROVERALPHA = false;
  42400. _this.CLIPPLANE = false;
  42401. _this.ALPHATEST = false;
  42402. _this.DEPTHPREPASS = false;
  42403. _this.ALPHAFROMDIFFUSE = false;
  42404. _this.POINTSIZE = false;
  42405. _this.FOG = false;
  42406. _this.SPECULARTERM = false;
  42407. _this.DIFFUSEFRESNEL = false;
  42408. _this.OPACITYFRESNEL = false;
  42409. _this.REFLECTIONFRESNEL = false;
  42410. _this.REFRACTIONFRESNEL = false;
  42411. _this.EMISSIVEFRESNEL = false;
  42412. _this.FRESNEL = false;
  42413. _this.NORMAL = false;
  42414. _this.UV1 = false;
  42415. _this.UV2 = false;
  42416. _this.VERTEXCOLOR = false;
  42417. _this.VERTEXALPHA = false;
  42418. _this.NUM_BONE_INFLUENCERS = 0;
  42419. _this.BonesPerMesh = 0;
  42420. _this.INSTANCES = false;
  42421. _this.GLOSSINESS = false;
  42422. _this.ROUGHNESS = false;
  42423. _this.EMISSIVEASILLUMINATION = false;
  42424. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42425. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42426. _this.LIGHTMAP = false;
  42427. _this.LIGHTMAPDIRECTUV = 0;
  42428. _this.OBJECTSPACE_NORMALMAP = false;
  42429. _this.USELIGHTMAPASSHADOWMAP = false;
  42430. _this.REFLECTIONMAP_3D = false;
  42431. _this.REFLECTIONMAP_SPHERICAL = false;
  42432. _this.REFLECTIONMAP_PLANAR = false;
  42433. _this.REFLECTIONMAP_CUBIC = false;
  42434. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42435. _this.REFLECTIONMAP_PROJECTION = false;
  42436. _this.REFLECTIONMAP_SKYBOX = false;
  42437. _this.REFLECTIONMAP_EXPLICIT = false;
  42438. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42439. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42440. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42441. _this.INVERTCUBICMAP = false;
  42442. _this.LOGARITHMICDEPTH = false;
  42443. _this.REFRACTION = false;
  42444. _this.REFRACTIONMAP_3D = false;
  42445. _this.REFLECTIONOVERALPHA = false;
  42446. _this.TWOSIDEDLIGHTING = false;
  42447. _this.SHADOWFLOAT = false;
  42448. _this.MORPHTARGETS = false;
  42449. _this.MORPHTARGETS_NORMAL = false;
  42450. _this.MORPHTARGETS_TANGENT = false;
  42451. _this.NUM_MORPH_INFLUENCERS = 0;
  42452. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42453. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42454. _this.IMAGEPROCESSING = false;
  42455. _this.VIGNETTE = false;
  42456. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42457. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42458. _this.TONEMAPPING = false;
  42459. _this.CONTRAST = false;
  42460. _this.COLORCURVES = false;
  42461. _this.COLORGRADING = false;
  42462. _this.COLORGRADING3D = false;
  42463. _this.SAMPLER3DGREENDEPTH = false;
  42464. _this.SAMPLER3DBGRMAP = false;
  42465. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42466. /**
  42467. * If the reflection texture on this material is in linear color space
  42468. * @ignore
  42469. */
  42470. _this.IS_REFLECTION_LINEAR = false;
  42471. /**
  42472. * If the refraction texture on this material is in linear color space
  42473. * @ignore
  42474. */
  42475. _this.IS_REFRACTION_LINEAR = false;
  42476. _this.EXPOSURE = false;
  42477. _this.rebuild();
  42478. return _this;
  42479. }
  42480. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42481. var modes = [
  42482. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42483. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42484. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42485. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42486. ];
  42487. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42488. var mode = modes_1[_i];
  42489. this[mode] = (mode === modeToEnable);
  42490. }
  42491. };
  42492. return StandardMaterialDefines;
  42493. }(BABYLON.MaterialDefines));
  42494. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42495. var StandardMaterial = /** @class */ (function (_super) {
  42496. __extends(StandardMaterial, _super);
  42497. function StandardMaterial(name, scene) {
  42498. var _this = _super.call(this, name, scene) || this;
  42499. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42500. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42501. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42502. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42503. _this.specularPower = 64;
  42504. _this._useAlphaFromDiffuseTexture = false;
  42505. _this._useEmissiveAsIllumination = false;
  42506. _this._linkEmissiveWithDiffuse = false;
  42507. _this._useSpecularOverAlpha = false;
  42508. _this._useReflectionOverAlpha = false;
  42509. _this._disableLighting = false;
  42510. _this._useObjectSpaceNormalMap = false;
  42511. _this._useParallax = false;
  42512. _this._useParallaxOcclusion = false;
  42513. _this.parallaxScaleBias = 0.05;
  42514. _this._roughness = 0;
  42515. _this.indexOfRefraction = 0.98;
  42516. _this.invertRefractionY = true;
  42517. /**
  42518. * Defines the alpha limits in alpha test mode
  42519. */
  42520. _this.alphaCutOff = 0.4;
  42521. _this._useLightmapAsShadowmap = false;
  42522. _this._useReflectionFresnelFromSpecular = false;
  42523. _this._useGlossinessFromSpecularMapAlpha = false;
  42524. _this._maxSimultaneousLights = 4;
  42525. /**
  42526. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42527. */
  42528. _this._invertNormalMapX = false;
  42529. /**
  42530. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42531. */
  42532. _this._invertNormalMapY = false;
  42533. /**
  42534. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42535. */
  42536. _this._twoSidedLighting = false;
  42537. _this._renderTargets = new BABYLON.SmartArray(16);
  42538. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42539. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42540. // Setup the default processing configuration to the scene.
  42541. _this._attachImageProcessingConfiguration(null);
  42542. _this.getRenderTargetTextures = function () {
  42543. _this._renderTargets.reset();
  42544. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42545. _this._renderTargets.push(_this._reflectionTexture);
  42546. }
  42547. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42548. _this._renderTargets.push(_this._refractionTexture);
  42549. }
  42550. return _this._renderTargets;
  42551. };
  42552. return _this;
  42553. }
  42554. ;
  42555. ;
  42556. ;
  42557. ;
  42558. ;
  42559. ;
  42560. ;
  42561. ;
  42562. ;
  42563. ;
  42564. ;
  42565. ;
  42566. ;
  42567. ;
  42568. ;
  42569. ;
  42570. ;
  42571. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42572. /**
  42573. * Gets the image processing configuration used either in this material.
  42574. */
  42575. get: function () {
  42576. return this._imageProcessingConfiguration;
  42577. },
  42578. /**
  42579. * Sets the Default image processing configuration used either in the this material.
  42580. *
  42581. * If sets to null, the scene one is in use.
  42582. */
  42583. set: function (value) {
  42584. this._attachImageProcessingConfiguration(value);
  42585. // Ensure the effect will be rebuilt.
  42586. this._markAllSubMeshesAsTexturesDirty();
  42587. },
  42588. enumerable: true,
  42589. configurable: true
  42590. });
  42591. /**
  42592. * Attaches a new image processing configuration to the Standard Material.
  42593. * @param configuration
  42594. */
  42595. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42596. var _this = this;
  42597. if (configuration === this._imageProcessingConfiguration) {
  42598. return;
  42599. }
  42600. // Detaches observer.
  42601. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42602. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42603. }
  42604. // Pick the scene configuration if needed.
  42605. if (!configuration) {
  42606. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42607. }
  42608. else {
  42609. this._imageProcessingConfiguration = configuration;
  42610. }
  42611. // Attaches observer.
  42612. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42613. _this._markAllSubMeshesAsImageProcessingDirty();
  42614. });
  42615. };
  42616. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42617. /**
  42618. * Gets wether the color curves effect is enabled.
  42619. */
  42620. get: function () {
  42621. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42622. },
  42623. /**
  42624. * Sets wether the color curves effect is enabled.
  42625. */
  42626. set: function (value) {
  42627. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42628. },
  42629. enumerable: true,
  42630. configurable: true
  42631. });
  42632. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42633. /**
  42634. * Gets wether the color grading effect is enabled.
  42635. */
  42636. get: function () {
  42637. return this.imageProcessingConfiguration.colorGradingEnabled;
  42638. },
  42639. /**
  42640. * Gets wether the color grading effect is enabled.
  42641. */
  42642. set: function (value) {
  42643. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42644. },
  42645. enumerable: true,
  42646. configurable: true
  42647. });
  42648. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42649. /**
  42650. * Gets wether tonemapping is enabled or not.
  42651. */
  42652. get: function () {
  42653. return this._imageProcessingConfiguration.toneMappingEnabled;
  42654. },
  42655. /**
  42656. * Sets wether tonemapping is enabled or not
  42657. */
  42658. set: function (value) {
  42659. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42660. },
  42661. enumerable: true,
  42662. configurable: true
  42663. });
  42664. ;
  42665. ;
  42666. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42667. /**
  42668. * The camera exposure used on this material.
  42669. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42670. * This corresponds to a photographic exposure.
  42671. */
  42672. get: function () {
  42673. return this._imageProcessingConfiguration.exposure;
  42674. },
  42675. /**
  42676. * The camera exposure used on this material.
  42677. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42678. * This corresponds to a photographic exposure.
  42679. */
  42680. set: function (value) {
  42681. this._imageProcessingConfiguration.exposure = value;
  42682. },
  42683. enumerable: true,
  42684. configurable: true
  42685. });
  42686. ;
  42687. ;
  42688. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42689. /**
  42690. * Gets The camera contrast used on this material.
  42691. */
  42692. get: function () {
  42693. return this._imageProcessingConfiguration.contrast;
  42694. },
  42695. /**
  42696. * Sets The camera contrast used on this material.
  42697. */
  42698. set: function (value) {
  42699. this._imageProcessingConfiguration.contrast = value;
  42700. },
  42701. enumerable: true,
  42702. configurable: true
  42703. });
  42704. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42705. /**
  42706. * Gets the Color Grading 2D Lookup Texture.
  42707. */
  42708. get: function () {
  42709. return this._imageProcessingConfiguration.colorGradingTexture;
  42710. },
  42711. /**
  42712. * Sets the Color Grading 2D Lookup Texture.
  42713. */
  42714. set: function (value) {
  42715. this._imageProcessingConfiguration.colorGradingTexture = value;
  42716. },
  42717. enumerable: true,
  42718. configurable: true
  42719. });
  42720. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42721. /**
  42722. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42723. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42724. * 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;
  42725. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42726. */
  42727. get: function () {
  42728. return this._imageProcessingConfiguration.colorCurves;
  42729. },
  42730. /**
  42731. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42732. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42733. * 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;
  42734. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42735. */
  42736. set: function (value) {
  42737. this._imageProcessingConfiguration.colorCurves = value;
  42738. },
  42739. enumerable: true,
  42740. configurable: true
  42741. });
  42742. StandardMaterial.prototype.getClassName = function () {
  42743. return "StandardMaterial";
  42744. };
  42745. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42746. get: function () {
  42747. return this._useLogarithmicDepth;
  42748. },
  42749. set: function (value) {
  42750. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42751. this._markAllSubMeshesAsMiscDirty();
  42752. },
  42753. enumerable: true,
  42754. configurable: true
  42755. });
  42756. StandardMaterial.prototype.needAlphaBlending = function () {
  42757. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42758. };
  42759. StandardMaterial.prototype.needAlphaTesting = function () {
  42760. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42761. };
  42762. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42763. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42764. };
  42765. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42766. return this._diffuseTexture;
  42767. };
  42768. /**
  42769. * Child classes can use it to update shaders
  42770. */
  42771. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42772. if (useInstances === void 0) { useInstances = false; }
  42773. if (subMesh.effect && this.isFrozen) {
  42774. if (this._wasPreviouslyReady && subMesh.effect) {
  42775. return true;
  42776. }
  42777. }
  42778. if (!subMesh._materialDefines) {
  42779. subMesh._materialDefines = new StandardMaterialDefines();
  42780. }
  42781. var scene = this.getScene();
  42782. var defines = subMesh._materialDefines;
  42783. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42784. if (defines._renderId === scene.getRenderId()) {
  42785. return true;
  42786. }
  42787. }
  42788. var engine = scene.getEngine();
  42789. // Lights
  42790. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42791. // Textures
  42792. if (defines._areTexturesDirty) {
  42793. defines._needUVs = false;
  42794. defines.MAINUV1 = false;
  42795. defines.MAINUV2 = false;
  42796. if (scene.texturesEnabled) {
  42797. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42798. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42799. return false;
  42800. }
  42801. else {
  42802. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42803. }
  42804. }
  42805. else {
  42806. defines.DIFFUSE = false;
  42807. }
  42808. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42809. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42810. return false;
  42811. }
  42812. else {
  42813. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42814. }
  42815. }
  42816. else {
  42817. defines.AMBIENT = false;
  42818. }
  42819. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42820. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42821. return false;
  42822. }
  42823. else {
  42824. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42825. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42826. }
  42827. }
  42828. else {
  42829. defines.OPACITY = false;
  42830. }
  42831. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42832. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42833. return false;
  42834. }
  42835. else {
  42836. defines._needNormals = true;
  42837. defines.REFLECTION = true;
  42838. defines.ROUGHNESS = (this._roughness > 0);
  42839. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42840. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42841. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42842. switch (this._reflectionTexture.coordinatesMode) {
  42843. case BABYLON.Texture.CUBIC_MODE:
  42844. case BABYLON.Texture.INVCUBIC_MODE:
  42845. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42846. break;
  42847. case BABYLON.Texture.EXPLICIT_MODE:
  42848. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42849. break;
  42850. case BABYLON.Texture.PLANAR_MODE:
  42851. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42852. break;
  42853. case BABYLON.Texture.PROJECTION_MODE:
  42854. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42855. break;
  42856. case BABYLON.Texture.SKYBOX_MODE:
  42857. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42858. break;
  42859. case BABYLON.Texture.SPHERICAL_MODE:
  42860. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42861. break;
  42862. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42863. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42864. break;
  42865. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42866. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42867. break;
  42868. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42869. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42870. break;
  42871. }
  42872. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42873. }
  42874. }
  42875. else {
  42876. defines.REFLECTION = false;
  42877. }
  42878. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42879. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42880. return false;
  42881. }
  42882. else {
  42883. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42884. }
  42885. }
  42886. else {
  42887. defines.EMISSIVE = false;
  42888. }
  42889. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42890. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42891. return false;
  42892. }
  42893. else {
  42894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42895. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42896. }
  42897. }
  42898. else {
  42899. defines.LIGHTMAP = false;
  42900. }
  42901. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42902. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42903. return false;
  42904. }
  42905. else {
  42906. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42907. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42908. }
  42909. }
  42910. else {
  42911. defines.SPECULAR = false;
  42912. }
  42913. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42914. // Bump texure can not be not blocking.
  42915. if (!this._bumpTexture.isReady()) {
  42916. return false;
  42917. }
  42918. else {
  42919. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42920. defines.PARALLAX = this._useParallax;
  42921. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42922. }
  42923. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42924. }
  42925. else {
  42926. defines.BUMP = false;
  42927. }
  42928. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42929. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42930. return false;
  42931. }
  42932. else {
  42933. defines._needUVs = true;
  42934. defines.REFRACTION = true;
  42935. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42936. }
  42937. }
  42938. else {
  42939. defines.REFRACTION = false;
  42940. }
  42941. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42942. }
  42943. else {
  42944. defines.DIFFUSE = false;
  42945. defines.AMBIENT = false;
  42946. defines.OPACITY = false;
  42947. defines.REFLECTION = false;
  42948. defines.EMISSIVE = false;
  42949. defines.LIGHTMAP = false;
  42950. defines.BUMP = false;
  42951. defines.REFRACTION = false;
  42952. }
  42953. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42954. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42955. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42956. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42957. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42958. }
  42959. if (defines._areImageProcessingDirty) {
  42960. if (!this._imageProcessingConfiguration.isReady()) {
  42961. return false;
  42962. }
  42963. this._imageProcessingConfiguration.prepareDefines(defines);
  42964. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42965. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42966. }
  42967. if (defines._areFresnelDirty) {
  42968. if (StandardMaterial.FresnelEnabled) {
  42969. // Fresnel
  42970. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42971. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42972. this._reflectionFresnelParameters) {
  42973. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42974. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42975. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42976. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42977. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42978. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42979. defines._needNormals = true;
  42980. defines.FRESNEL = true;
  42981. }
  42982. }
  42983. else {
  42984. defines.FRESNEL = false;
  42985. }
  42986. }
  42987. // Misc.
  42988. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42989. // Attribs
  42990. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42991. // Values that need to be evaluated on every frame
  42992. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42993. // Get correct effect
  42994. if (defines.isDirty) {
  42995. defines.markAsProcessed();
  42996. scene.resetCachedMaterial();
  42997. // Fallbacks
  42998. var fallbacks = new BABYLON.EffectFallbacks();
  42999. if (defines.REFLECTION) {
  43000. fallbacks.addFallback(0, "REFLECTION");
  43001. }
  43002. if (defines.SPECULAR) {
  43003. fallbacks.addFallback(0, "SPECULAR");
  43004. }
  43005. if (defines.BUMP) {
  43006. fallbacks.addFallback(0, "BUMP");
  43007. }
  43008. if (defines.PARALLAX) {
  43009. fallbacks.addFallback(1, "PARALLAX");
  43010. }
  43011. if (defines.PARALLAXOCCLUSION) {
  43012. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43013. }
  43014. if (defines.SPECULAROVERALPHA) {
  43015. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43016. }
  43017. if (defines.FOG) {
  43018. fallbacks.addFallback(1, "FOG");
  43019. }
  43020. if (defines.POINTSIZE) {
  43021. fallbacks.addFallback(0, "POINTSIZE");
  43022. }
  43023. if (defines.LOGARITHMICDEPTH) {
  43024. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43025. }
  43026. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43027. if (defines.SPECULARTERM) {
  43028. fallbacks.addFallback(0, "SPECULARTERM");
  43029. }
  43030. if (defines.DIFFUSEFRESNEL) {
  43031. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43032. }
  43033. if (defines.OPACITYFRESNEL) {
  43034. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43035. }
  43036. if (defines.REFLECTIONFRESNEL) {
  43037. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43038. }
  43039. if (defines.EMISSIVEFRESNEL) {
  43040. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43041. }
  43042. if (defines.FRESNEL) {
  43043. fallbacks.addFallback(4, "FRESNEL");
  43044. }
  43045. //Attributes
  43046. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43047. if (defines.NORMAL) {
  43048. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43049. }
  43050. if (defines.UV1) {
  43051. attribs.push(BABYLON.VertexBuffer.UVKind);
  43052. }
  43053. if (defines.UV2) {
  43054. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43055. }
  43056. if (defines.VERTEXCOLOR) {
  43057. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43058. }
  43059. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43060. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43061. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43062. var shaderName = "default";
  43063. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43064. "vFogInfos", "vFogColor", "pointSize",
  43065. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43066. "mBones",
  43067. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43068. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43069. "vReflectionPosition", "vReflectionSize",
  43070. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43071. ];
  43072. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43073. var uniformBuffers = ["Material", "Scene"];
  43074. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43075. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43076. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43077. uniformsNames: uniforms,
  43078. uniformBuffersNames: uniformBuffers,
  43079. samplers: samplers,
  43080. defines: defines,
  43081. maxSimultaneousLights: this._maxSimultaneousLights
  43082. });
  43083. if (this.customShaderNameResolve) {
  43084. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43085. }
  43086. var join = defines.toString();
  43087. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43088. attributes: attribs,
  43089. uniformsNames: uniforms,
  43090. uniformBuffersNames: uniformBuffers,
  43091. samplers: samplers,
  43092. defines: join,
  43093. fallbacks: fallbacks,
  43094. onCompiled: this.onCompiled,
  43095. onError: this.onError,
  43096. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43097. }, engine), defines);
  43098. this.buildUniformLayout();
  43099. }
  43100. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43101. return false;
  43102. }
  43103. defines._renderId = scene.getRenderId();
  43104. this._wasPreviouslyReady = true;
  43105. return true;
  43106. };
  43107. StandardMaterial.prototype.buildUniformLayout = function () {
  43108. // Order is important !
  43109. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43110. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43111. this._uniformBuffer.addUniform("opacityParts", 4);
  43112. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43113. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43114. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43115. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43116. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43117. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43118. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43119. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43120. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43121. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43122. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43123. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43124. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43125. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43126. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43127. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43128. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43129. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43130. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43131. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43132. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43133. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43134. this._uniformBuffer.addUniform("specularMatrix", 16);
  43135. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43136. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43137. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43138. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43139. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43140. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43141. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43142. this._uniformBuffer.addUniform("pointSize", 1);
  43143. this._uniformBuffer.create();
  43144. };
  43145. StandardMaterial.prototype.unbind = function () {
  43146. if (this._activeEffect) {
  43147. var needFlag = false;
  43148. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43149. this._activeEffect.setTexture("reflection2DSampler", null);
  43150. needFlag = true;
  43151. }
  43152. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43153. this._activeEffect.setTexture("refraction2DSampler", null);
  43154. needFlag = true;
  43155. }
  43156. if (needFlag) {
  43157. this._markAllSubMeshesAsTexturesDirty();
  43158. }
  43159. }
  43160. _super.prototype.unbind.call(this);
  43161. };
  43162. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43163. var scene = this.getScene();
  43164. var defines = subMesh._materialDefines;
  43165. if (!defines) {
  43166. return;
  43167. }
  43168. var effect = subMesh.effect;
  43169. if (!effect) {
  43170. return;
  43171. }
  43172. this._activeEffect = effect;
  43173. // Matrices
  43174. this.bindOnlyWorldMatrix(world);
  43175. // Normal Matrix
  43176. if (defines.OBJECTSPACE_NORMALMAP) {
  43177. world.toNormalMatrix(this._normalMatrix);
  43178. this.bindOnlyNormalMatrix(this._normalMatrix);
  43179. }
  43180. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43181. // Bones
  43182. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43183. if (mustRebind) {
  43184. this._uniformBuffer.bindToEffect(effect, "Material");
  43185. this.bindViewProjection(effect);
  43186. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43187. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43188. // Fresnel
  43189. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43190. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43191. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43192. }
  43193. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43194. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43195. }
  43196. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43197. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43198. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43199. }
  43200. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43201. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43202. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43203. }
  43204. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43205. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43206. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43207. }
  43208. }
  43209. // Textures
  43210. if (scene.texturesEnabled) {
  43211. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43212. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43213. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43214. if (this._diffuseTexture.hasAlpha) {
  43215. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43216. }
  43217. }
  43218. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43219. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43220. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43221. }
  43222. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43223. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43224. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43225. }
  43226. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43227. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43228. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43229. if (this._reflectionTexture.boundingBoxSize) {
  43230. var cubeTexture = this._reflectionTexture;
  43231. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43232. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43233. }
  43234. }
  43235. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43236. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43237. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43238. }
  43239. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43240. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43241. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43242. }
  43243. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43244. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43245. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43246. }
  43247. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43248. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43249. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43250. if (scene._mirroredCameraPosition) {
  43251. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43252. }
  43253. else {
  43254. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43255. }
  43256. }
  43257. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43258. var depth = 1.0;
  43259. if (!this._refractionTexture.isCube) {
  43260. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43261. if (this._refractionTexture.depth) {
  43262. depth = this._refractionTexture.depth;
  43263. }
  43264. }
  43265. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43266. }
  43267. }
  43268. // Point size
  43269. if (this.pointsCloud) {
  43270. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43271. }
  43272. if (defines.SPECULARTERM) {
  43273. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43274. }
  43275. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43276. // Diffuse
  43277. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43278. }
  43279. // Textures
  43280. if (scene.texturesEnabled) {
  43281. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43282. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43283. }
  43284. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43285. effect.setTexture("ambientSampler", this._ambientTexture);
  43286. }
  43287. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43288. effect.setTexture("opacitySampler", this._opacityTexture);
  43289. }
  43290. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43291. if (this._reflectionTexture.isCube) {
  43292. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43293. }
  43294. else {
  43295. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43296. }
  43297. }
  43298. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43299. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43300. }
  43301. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43302. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43303. }
  43304. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43305. effect.setTexture("specularSampler", this._specularTexture);
  43306. }
  43307. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43308. effect.setTexture("bumpSampler", this._bumpTexture);
  43309. }
  43310. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43311. var depth = 1.0;
  43312. if (this._refractionTexture.isCube) {
  43313. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43314. }
  43315. else {
  43316. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43317. }
  43318. }
  43319. }
  43320. // Clip plane
  43321. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43322. // Colors
  43323. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43324. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43325. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43326. }
  43327. if (mustRebind || !this.isFrozen) {
  43328. // Lights
  43329. if (scene.lightsEnabled && !this._disableLighting) {
  43330. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43331. }
  43332. // View
  43333. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43334. this.bindView(effect);
  43335. }
  43336. // Fog
  43337. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43338. // Morph targets
  43339. if (defines.NUM_MORPH_INFLUENCERS) {
  43340. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43341. }
  43342. // Log. depth
  43343. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43344. // image processing
  43345. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43346. this._imageProcessingConfiguration.bind(this._activeEffect);
  43347. }
  43348. }
  43349. this._uniformBuffer.update();
  43350. this._afterBind(mesh, this._activeEffect);
  43351. };
  43352. StandardMaterial.prototype.getAnimatables = function () {
  43353. var results = [];
  43354. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43355. results.push(this._diffuseTexture);
  43356. }
  43357. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43358. results.push(this._ambientTexture);
  43359. }
  43360. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43361. results.push(this._opacityTexture);
  43362. }
  43363. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43364. results.push(this._reflectionTexture);
  43365. }
  43366. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43367. results.push(this._emissiveTexture);
  43368. }
  43369. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43370. results.push(this._specularTexture);
  43371. }
  43372. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43373. results.push(this._bumpTexture);
  43374. }
  43375. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43376. results.push(this._lightmapTexture);
  43377. }
  43378. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43379. results.push(this._refractionTexture);
  43380. }
  43381. return results;
  43382. };
  43383. StandardMaterial.prototype.getActiveTextures = function () {
  43384. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43385. if (this._diffuseTexture) {
  43386. activeTextures.push(this._diffuseTexture);
  43387. }
  43388. if (this._ambientTexture) {
  43389. activeTextures.push(this._ambientTexture);
  43390. }
  43391. if (this._opacityTexture) {
  43392. activeTextures.push(this._opacityTexture);
  43393. }
  43394. if (this._reflectionTexture) {
  43395. activeTextures.push(this._reflectionTexture);
  43396. }
  43397. if (this._emissiveTexture) {
  43398. activeTextures.push(this._emissiveTexture);
  43399. }
  43400. if (this._specularTexture) {
  43401. activeTextures.push(this._specularTexture);
  43402. }
  43403. if (this._bumpTexture) {
  43404. activeTextures.push(this._bumpTexture);
  43405. }
  43406. if (this._lightmapTexture) {
  43407. activeTextures.push(this._lightmapTexture);
  43408. }
  43409. if (this._refractionTexture) {
  43410. activeTextures.push(this._refractionTexture);
  43411. }
  43412. return activeTextures;
  43413. };
  43414. StandardMaterial.prototype.hasTexture = function (texture) {
  43415. if (_super.prototype.hasTexture.call(this, texture)) {
  43416. return true;
  43417. }
  43418. if (this._diffuseTexture === texture) {
  43419. return true;
  43420. }
  43421. if (this._ambientTexture === texture) {
  43422. return true;
  43423. }
  43424. if (this._opacityTexture === texture) {
  43425. return true;
  43426. }
  43427. if (this._reflectionTexture === texture) {
  43428. return true;
  43429. }
  43430. if (this._emissiveTexture === texture) {
  43431. return true;
  43432. }
  43433. if (this._specularTexture === texture) {
  43434. return true;
  43435. }
  43436. if (this._bumpTexture === texture) {
  43437. return true;
  43438. }
  43439. if (this._lightmapTexture === texture) {
  43440. return true;
  43441. }
  43442. if (this._refractionTexture === texture) {
  43443. return true;
  43444. }
  43445. return false;
  43446. };
  43447. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43448. if (forceDisposeTextures) {
  43449. if (this._diffuseTexture) {
  43450. this._diffuseTexture.dispose();
  43451. }
  43452. if (this._ambientTexture) {
  43453. this._ambientTexture.dispose();
  43454. }
  43455. if (this._opacityTexture) {
  43456. this._opacityTexture.dispose();
  43457. }
  43458. if (this._reflectionTexture) {
  43459. this._reflectionTexture.dispose();
  43460. }
  43461. if (this._emissiveTexture) {
  43462. this._emissiveTexture.dispose();
  43463. }
  43464. if (this._specularTexture) {
  43465. this._specularTexture.dispose();
  43466. }
  43467. if (this._bumpTexture) {
  43468. this._bumpTexture.dispose();
  43469. }
  43470. if (this._lightmapTexture) {
  43471. this._lightmapTexture.dispose();
  43472. }
  43473. if (this._refractionTexture) {
  43474. this._refractionTexture.dispose();
  43475. }
  43476. }
  43477. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43478. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43479. }
  43480. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43481. };
  43482. StandardMaterial.prototype.clone = function (name) {
  43483. var _this = this;
  43484. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43485. result.name = name;
  43486. result.id = name;
  43487. return result;
  43488. };
  43489. StandardMaterial.prototype.serialize = function () {
  43490. return BABYLON.SerializationHelper.Serialize(this);
  43491. };
  43492. // Statics
  43493. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43494. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43495. };
  43496. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43497. get: function () {
  43498. return StandardMaterial._DiffuseTextureEnabled;
  43499. },
  43500. set: function (value) {
  43501. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43502. return;
  43503. }
  43504. StandardMaterial._DiffuseTextureEnabled = value;
  43505. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43506. },
  43507. enumerable: true,
  43508. configurable: true
  43509. });
  43510. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43511. get: function () {
  43512. return StandardMaterial._AmbientTextureEnabled;
  43513. },
  43514. set: function (value) {
  43515. if (StandardMaterial._AmbientTextureEnabled === value) {
  43516. return;
  43517. }
  43518. StandardMaterial._AmbientTextureEnabled = value;
  43519. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43520. },
  43521. enumerable: true,
  43522. configurable: true
  43523. });
  43524. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43525. get: function () {
  43526. return StandardMaterial._OpacityTextureEnabled;
  43527. },
  43528. set: function (value) {
  43529. if (StandardMaterial._OpacityTextureEnabled === value) {
  43530. return;
  43531. }
  43532. StandardMaterial._OpacityTextureEnabled = value;
  43533. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43534. },
  43535. enumerable: true,
  43536. configurable: true
  43537. });
  43538. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43539. get: function () {
  43540. return StandardMaterial._ReflectionTextureEnabled;
  43541. },
  43542. set: function (value) {
  43543. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43544. return;
  43545. }
  43546. StandardMaterial._ReflectionTextureEnabled = value;
  43547. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43548. },
  43549. enumerable: true,
  43550. configurable: true
  43551. });
  43552. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43553. get: function () {
  43554. return StandardMaterial._EmissiveTextureEnabled;
  43555. },
  43556. set: function (value) {
  43557. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43558. return;
  43559. }
  43560. StandardMaterial._EmissiveTextureEnabled = value;
  43561. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43562. },
  43563. enumerable: true,
  43564. configurable: true
  43565. });
  43566. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43567. get: function () {
  43568. return StandardMaterial._SpecularTextureEnabled;
  43569. },
  43570. set: function (value) {
  43571. if (StandardMaterial._SpecularTextureEnabled === value) {
  43572. return;
  43573. }
  43574. StandardMaterial._SpecularTextureEnabled = value;
  43575. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43576. },
  43577. enumerable: true,
  43578. configurable: true
  43579. });
  43580. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43581. get: function () {
  43582. return StandardMaterial._BumpTextureEnabled;
  43583. },
  43584. set: function (value) {
  43585. if (StandardMaterial._BumpTextureEnabled === value) {
  43586. return;
  43587. }
  43588. StandardMaterial._BumpTextureEnabled = value;
  43589. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43590. },
  43591. enumerable: true,
  43592. configurable: true
  43593. });
  43594. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43595. get: function () {
  43596. return StandardMaterial._LightmapTextureEnabled;
  43597. },
  43598. set: function (value) {
  43599. if (StandardMaterial._LightmapTextureEnabled === value) {
  43600. return;
  43601. }
  43602. StandardMaterial._LightmapTextureEnabled = value;
  43603. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43604. },
  43605. enumerable: true,
  43606. configurable: true
  43607. });
  43608. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43609. get: function () {
  43610. return StandardMaterial._RefractionTextureEnabled;
  43611. },
  43612. set: function (value) {
  43613. if (StandardMaterial._RefractionTextureEnabled === value) {
  43614. return;
  43615. }
  43616. StandardMaterial._RefractionTextureEnabled = value;
  43617. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43618. },
  43619. enumerable: true,
  43620. configurable: true
  43621. });
  43622. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43623. get: function () {
  43624. return StandardMaterial._ColorGradingTextureEnabled;
  43625. },
  43626. set: function (value) {
  43627. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43628. return;
  43629. }
  43630. StandardMaterial._ColorGradingTextureEnabled = value;
  43631. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43632. },
  43633. enumerable: true,
  43634. configurable: true
  43635. });
  43636. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43637. get: function () {
  43638. return StandardMaterial._FresnelEnabled;
  43639. },
  43640. set: function (value) {
  43641. if (StandardMaterial._FresnelEnabled === value) {
  43642. return;
  43643. }
  43644. StandardMaterial._FresnelEnabled = value;
  43645. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43646. },
  43647. enumerable: true,
  43648. configurable: true
  43649. });
  43650. // Flags used to enable or disable a type of texture for all Standard Materials
  43651. StandardMaterial._DiffuseTextureEnabled = true;
  43652. StandardMaterial._AmbientTextureEnabled = true;
  43653. StandardMaterial._OpacityTextureEnabled = true;
  43654. StandardMaterial._ReflectionTextureEnabled = true;
  43655. StandardMaterial._EmissiveTextureEnabled = true;
  43656. StandardMaterial._SpecularTextureEnabled = true;
  43657. StandardMaterial._BumpTextureEnabled = true;
  43658. StandardMaterial._LightmapTextureEnabled = true;
  43659. StandardMaterial._RefractionTextureEnabled = true;
  43660. StandardMaterial._ColorGradingTextureEnabled = true;
  43661. StandardMaterial._FresnelEnabled = true;
  43662. __decorate([
  43663. BABYLON.serializeAsTexture("diffuseTexture")
  43664. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43665. __decorate([
  43666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43667. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43668. __decorate([
  43669. BABYLON.serializeAsTexture("ambientTexture")
  43670. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43671. __decorate([
  43672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43673. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43674. __decorate([
  43675. BABYLON.serializeAsTexture("opacityTexture")
  43676. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43677. __decorate([
  43678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43679. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43680. __decorate([
  43681. BABYLON.serializeAsTexture("reflectionTexture")
  43682. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43683. __decorate([
  43684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43685. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43686. __decorate([
  43687. BABYLON.serializeAsTexture("emissiveTexture")
  43688. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43689. __decorate([
  43690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43691. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43692. __decorate([
  43693. BABYLON.serializeAsTexture("specularTexture")
  43694. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43695. __decorate([
  43696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43697. ], StandardMaterial.prototype, "specularTexture", void 0);
  43698. __decorate([
  43699. BABYLON.serializeAsTexture("bumpTexture")
  43700. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43701. __decorate([
  43702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43703. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43704. __decorate([
  43705. BABYLON.serializeAsTexture("lightmapTexture")
  43706. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43707. __decorate([
  43708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43709. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43710. __decorate([
  43711. BABYLON.serializeAsTexture("refractionTexture")
  43712. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43713. __decorate([
  43714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43715. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43716. __decorate([
  43717. BABYLON.serializeAsColor3("ambient")
  43718. ], StandardMaterial.prototype, "ambientColor", void 0);
  43719. __decorate([
  43720. BABYLON.serializeAsColor3("diffuse")
  43721. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43722. __decorate([
  43723. BABYLON.serializeAsColor3("specular")
  43724. ], StandardMaterial.prototype, "specularColor", void 0);
  43725. __decorate([
  43726. BABYLON.serializeAsColor3("emissive")
  43727. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43728. __decorate([
  43729. BABYLON.serialize()
  43730. ], StandardMaterial.prototype, "specularPower", void 0);
  43731. __decorate([
  43732. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43733. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43734. __decorate([
  43735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43736. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43737. __decorate([
  43738. BABYLON.serialize("useEmissiveAsIllumination")
  43739. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43740. __decorate([
  43741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43742. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43743. __decorate([
  43744. BABYLON.serialize("linkEmissiveWithDiffuse")
  43745. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43746. __decorate([
  43747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43748. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43749. __decorate([
  43750. BABYLON.serialize("useSpecularOverAlpha")
  43751. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43752. __decorate([
  43753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43754. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43755. __decorate([
  43756. BABYLON.serialize("useReflectionOverAlpha")
  43757. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43758. __decorate([
  43759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43760. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43761. __decorate([
  43762. BABYLON.serialize("disableLighting")
  43763. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43764. __decorate([
  43765. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43766. ], StandardMaterial.prototype, "disableLighting", void 0);
  43767. __decorate([
  43768. BABYLON.serialize("useObjectSpaceNormalMap")
  43769. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43770. __decorate([
  43771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43772. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43773. __decorate([
  43774. BABYLON.serialize("useParallax")
  43775. ], StandardMaterial.prototype, "_useParallax", void 0);
  43776. __decorate([
  43777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43778. ], StandardMaterial.prototype, "useParallax", void 0);
  43779. __decorate([
  43780. BABYLON.serialize("useParallaxOcclusion")
  43781. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43782. __decorate([
  43783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43784. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43785. __decorate([
  43786. BABYLON.serialize()
  43787. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43788. __decorate([
  43789. BABYLON.serialize("roughness")
  43790. ], StandardMaterial.prototype, "_roughness", void 0);
  43791. __decorate([
  43792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43793. ], StandardMaterial.prototype, "roughness", void 0);
  43794. __decorate([
  43795. BABYLON.serialize()
  43796. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43797. __decorate([
  43798. BABYLON.serialize()
  43799. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43800. __decorate([
  43801. BABYLON.serialize()
  43802. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43803. __decorate([
  43804. BABYLON.serialize("useLightmapAsShadowmap")
  43805. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43806. __decorate([
  43807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43808. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43809. __decorate([
  43810. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43811. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43812. __decorate([
  43813. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43814. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43815. __decorate([
  43816. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43817. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43818. __decorate([
  43819. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43820. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43821. __decorate([
  43822. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43823. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43824. __decorate([
  43825. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43826. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43827. __decorate([
  43828. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43829. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43830. __decorate([
  43831. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43832. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43833. __decorate([
  43834. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43835. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43836. __decorate([
  43837. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43838. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43839. __decorate([
  43840. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43841. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43842. __decorate([
  43843. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43844. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43845. __decorate([
  43846. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43847. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43848. __decorate([
  43849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43850. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43851. __decorate([
  43852. BABYLON.serialize("maxSimultaneousLights")
  43853. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43854. __decorate([
  43855. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43856. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43857. __decorate([
  43858. BABYLON.serialize("invertNormalMapX")
  43859. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43860. __decorate([
  43861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43862. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43863. __decorate([
  43864. BABYLON.serialize("invertNormalMapY")
  43865. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43866. __decorate([
  43867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43868. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43869. __decorate([
  43870. BABYLON.serialize("twoSidedLighting")
  43871. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43872. __decorate([
  43873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43874. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43875. __decorate([
  43876. BABYLON.serialize()
  43877. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43878. return StandardMaterial;
  43879. }(BABYLON.PushMaterial));
  43880. BABYLON.StandardMaterial = StandardMaterial;
  43881. })(BABYLON || (BABYLON = {}));
  43882. //# sourceMappingURL=babylon.standardMaterial.js.map
  43883. var BABYLON;
  43884. (function (BABYLON) {
  43885. /**
  43886. * Manages the defines for the PBR Material.
  43887. * @ignoreChildren
  43888. */
  43889. var PBRMaterialDefines = /** @class */ (function (_super) {
  43890. __extends(PBRMaterialDefines, _super);
  43891. /**
  43892. * Initializes the PBR Material defines.
  43893. */
  43894. function PBRMaterialDefines() {
  43895. var _this = _super.call(this) || this;
  43896. _this.PBR = true;
  43897. _this.MAINUV1 = false;
  43898. _this.MAINUV2 = false;
  43899. _this.UV1 = false;
  43900. _this.UV2 = false;
  43901. _this.ALBEDO = false;
  43902. _this.ALBEDODIRECTUV = 0;
  43903. _this.VERTEXCOLOR = false;
  43904. _this.AMBIENT = false;
  43905. _this.AMBIENTDIRECTUV = 0;
  43906. _this.AMBIENTINGRAYSCALE = false;
  43907. _this.OPACITY = false;
  43908. _this.VERTEXALPHA = false;
  43909. _this.OPACITYDIRECTUV = 0;
  43910. _this.OPACITYRGB = false;
  43911. _this.ALPHATEST = false;
  43912. _this.DEPTHPREPASS = false;
  43913. _this.ALPHABLEND = false;
  43914. _this.ALPHAFROMALBEDO = false;
  43915. _this.ALPHATESTVALUE = "0.5";
  43916. _this.SPECULAROVERALPHA = false;
  43917. _this.RADIANCEOVERALPHA = false;
  43918. _this.ALPHAFRESNEL = false;
  43919. _this.LINEARALPHAFRESNEL = false;
  43920. _this.PREMULTIPLYALPHA = false;
  43921. _this.EMISSIVE = false;
  43922. _this.EMISSIVEDIRECTUV = 0;
  43923. _this.REFLECTIVITY = false;
  43924. _this.REFLECTIVITYDIRECTUV = 0;
  43925. _this.SPECULARTERM = false;
  43926. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43927. _this.MICROSURFACEAUTOMATIC = false;
  43928. _this.LODBASEDMICROSFURACE = false;
  43929. _this.MICROSURFACEMAP = false;
  43930. _this.MICROSURFACEMAPDIRECTUV = 0;
  43931. _this.METALLICWORKFLOW = false;
  43932. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43933. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43934. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43935. _this.AOSTOREINMETALMAPRED = false;
  43936. _this.ENVIRONMENTBRDF = false;
  43937. _this.NORMAL = false;
  43938. _this.TANGENT = false;
  43939. _this.BUMP = false;
  43940. _this.BUMPDIRECTUV = 0;
  43941. _this.OBJECTSPACE_NORMALMAP = false;
  43942. _this.PARALLAX = false;
  43943. _this.PARALLAXOCCLUSION = false;
  43944. _this.NORMALXYSCALE = true;
  43945. _this.LIGHTMAP = false;
  43946. _this.LIGHTMAPDIRECTUV = 0;
  43947. _this.USELIGHTMAPASSHADOWMAP = false;
  43948. _this.GAMMALIGHTMAP = false;
  43949. _this.REFLECTION = false;
  43950. _this.REFLECTIONMAP_3D = false;
  43951. _this.REFLECTIONMAP_SPHERICAL = false;
  43952. _this.REFLECTIONMAP_PLANAR = false;
  43953. _this.REFLECTIONMAP_CUBIC = false;
  43954. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43955. _this.REFLECTIONMAP_PROJECTION = false;
  43956. _this.REFLECTIONMAP_SKYBOX = false;
  43957. _this.REFLECTIONMAP_EXPLICIT = false;
  43958. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43959. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43960. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43961. _this.INVERTCUBICMAP = false;
  43962. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43963. _this.USESPHERICALINVERTEX = false;
  43964. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43965. _this.LODINREFLECTIONALPHA = false;
  43966. _this.GAMMAREFLECTION = false;
  43967. _this.RADIANCEOCCLUSION = false;
  43968. _this.HORIZONOCCLUSION = false;
  43969. _this.REFRACTION = false;
  43970. _this.REFRACTIONMAP_3D = false;
  43971. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43972. _this.LODINREFRACTIONALPHA = false;
  43973. _this.GAMMAREFRACTION = false;
  43974. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43975. _this.INSTANCES = false;
  43976. _this.NUM_BONE_INFLUENCERS = 0;
  43977. _this.BonesPerMesh = 0;
  43978. _this.NONUNIFORMSCALING = false;
  43979. _this.MORPHTARGETS = false;
  43980. _this.MORPHTARGETS_NORMAL = false;
  43981. _this.MORPHTARGETS_TANGENT = false;
  43982. _this.NUM_MORPH_INFLUENCERS = 0;
  43983. _this.IMAGEPROCESSING = false;
  43984. _this.VIGNETTE = false;
  43985. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43986. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43987. _this.TONEMAPPING = false;
  43988. _this.CONTRAST = false;
  43989. _this.COLORCURVES = false;
  43990. _this.COLORGRADING = false;
  43991. _this.COLORGRADING3D = false;
  43992. _this.SAMPLER3DGREENDEPTH = false;
  43993. _this.SAMPLER3DBGRMAP = false;
  43994. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43995. _this.EXPOSURE = false;
  43996. _this.USEPHYSICALLIGHTFALLOFF = false;
  43997. _this.TWOSIDEDLIGHTING = false;
  43998. _this.SHADOWFLOAT = false;
  43999. _this.CLIPPLANE = false;
  44000. _this.POINTSIZE = false;
  44001. _this.FOG = false;
  44002. _this.LOGARITHMICDEPTH = false;
  44003. _this.FORCENORMALFORWARD = false;
  44004. _this.GEOMETRYAA = false;
  44005. _this.UNLIT = false;
  44006. _this.rebuild();
  44007. return _this;
  44008. }
  44009. /**
  44010. * Resets the PBR Material defines.
  44011. */
  44012. PBRMaterialDefines.prototype.reset = function () {
  44013. _super.prototype.reset.call(this);
  44014. this.ALPHATESTVALUE = "0.5";
  44015. this.PBR = true;
  44016. };
  44017. return PBRMaterialDefines;
  44018. }(BABYLON.MaterialDefines));
  44019. /**
  44020. * The Physically based material base class of BJS.
  44021. *
  44022. * This offers the main features of a standard PBR material.
  44023. * For more information, please refer to the documentation :
  44024. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44025. */
  44026. var PBRBaseMaterial = /** @class */ (function (_super) {
  44027. __extends(PBRBaseMaterial, _super);
  44028. /**
  44029. * Instantiates a new PBRMaterial instance.
  44030. *
  44031. * @param name The material name
  44032. * @param scene The scene the material will be use in.
  44033. */
  44034. function PBRBaseMaterial(name, scene) {
  44035. var _this = _super.call(this, name, scene) || this;
  44036. /**
  44037. * Intensity of the direct lights e.g. the four lights available in your scene.
  44038. * This impacts both the direct diffuse and specular highlights.
  44039. */
  44040. _this._directIntensity = 1.0;
  44041. /**
  44042. * Intensity of the emissive part of the material.
  44043. * This helps controlling the emissive effect without modifying the emissive color.
  44044. */
  44045. _this._emissiveIntensity = 1.0;
  44046. /**
  44047. * Intensity of the environment e.g. how much the environment will light the object
  44048. * either through harmonics for rough material or through the refelction for shiny ones.
  44049. */
  44050. _this._environmentIntensity = 1.0;
  44051. /**
  44052. * This is a special control allowing the reduction of the specular highlights coming from the
  44053. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44054. */
  44055. _this._specularIntensity = 1.0;
  44056. /**
  44057. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44058. */
  44059. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44060. /**
  44061. * Debug Control allowing disabling the bump map on this material.
  44062. */
  44063. _this._disableBumpMap = false;
  44064. /**
  44065. * AKA Occlusion Texture Intensity in other nomenclature.
  44066. */
  44067. _this._ambientTextureStrength = 1.0;
  44068. /**
  44069. * The color of a material in ambient lighting.
  44070. */
  44071. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44072. /**
  44073. * AKA Diffuse Color in other nomenclature.
  44074. */
  44075. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44076. /**
  44077. * AKA Specular Color in other nomenclature.
  44078. */
  44079. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44080. /**
  44081. * The color applied when light is reflected from a material.
  44082. */
  44083. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44084. /**
  44085. * The color applied when light is emitted from a material.
  44086. */
  44087. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44088. /**
  44089. * AKA Glossiness in other nomenclature.
  44090. */
  44091. _this._microSurface = 0.9;
  44092. /**
  44093. * source material index of refraction (IOR)' / 'destination material IOR.
  44094. */
  44095. _this._indexOfRefraction = 0.66;
  44096. /**
  44097. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44098. */
  44099. _this._invertRefractionY = false;
  44100. /**
  44101. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44102. * Materials half opaque for instance using refraction could benefit from this control.
  44103. */
  44104. _this._linkRefractionWithTransparency = false;
  44105. /**
  44106. * Specifies that the material will use the light map as a show map.
  44107. */
  44108. _this._useLightmapAsShadowmap = false;
  44109. /**
  44110. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44111. * makes the reflect vector face the model (under horizon).
  44112. */
  44113. _this._useHorizonOcclusion = true;
  44114. /**
  44115. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44116. * too much the area relying on ambient texture to define their ambient occlusion.
  44117. */
  44118. _this._useRadianceOcclusion = true;
  44119. /**
  44120. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44121. */
  44122. _this._useAlphaFromAlbedoTexture = false;
  44123. /**
  44124. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44125. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44126. */
  44127. _this._useSpecularOverAlpha = true;
  44128. /**
  44129. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44130. */
  44131. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44132. /**
  44133. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44134. */
  44135. _this._useRoughnessFromMetallicTextureAlpha = true;
  44136. /**
  44137. * Specifies if the metallic texture contains the roughness information in its green channel.
  44138. */
  44139. _this._useRoughnessFromMetallicTextureGreen = false;
  44140. /**
  44141. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44142. */
  44143. _this._useMetallnessFromMetallicTextureBlue = false;
  44144. /**
  44145. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44146. */
  44147. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44148. /**
  44149. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44150. */
  44151. _this._useAmbientInGrayScale = false;
  44152. /**
  44153. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44154. * The material will try to infer what glossiness each pixel should be.
  44155. */
  44156. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44157. /**
  44158. * BJS is using an harcoded light falloff based on a manually sets up range.
  44159. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44160. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44161. */
  44162. _this._usePhysicalLightFalloff = true;
  44163. /**
  44164. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44165. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44166. */
  44167. _this._useRadianceOverAlpha = true;
  44168. /**
  44169. * Allows using an object space normal map (instead of tangent space).
  44170. */
  44171. _this._useObjectSpaceNormalMap = false;
  44172. /**
  44173. * Allows using the bump map in parallax mode.
  44174. */
  44175. _this._useParallax = false;
  44176. /**
  44177. * Allows using the bump map in parallax occlusion mode.
  44178. */
  44179. _this._useParallaxOcclusion = false;
  44180. /**
  44181. * Controls the scale bias of the parallax mode.
  44182. */
  44183. _this._parallaxScaleBias = 0.05;
  44184. /**
  44185. * If sets to true, disables all the lights affecting the material.
  44186. */
  44187. _this._disableLighting = false;
  44188. /**
  44189. * Number of Simultaneous lights allowed on the material.
  44190. */
  44191. _this._maxSimultaneousLights = 4;
  44192. /**
  44193. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44194. */
  44195. _this._invertNormalMapX = false;
  44196. /**
  44197. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44198. */
  44199. _this._invertNormalMapY = false;
  44200. /**
  44201. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44202. */
  44203. _this._twoSidedLighting = false;
  44204. /**
  44205. * Defines the alpha limits in alpha test mode.
  44206. */
  44207. _this._alphaCutOff = 0.4;
  44208. /**
  44209. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44210. */
  44211. _this._forceAlphaTest = false;
  44212. /**
  44213. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44214. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44215. */
  44216. _this._useAlphaFresnel = false;
  44217. /**
  44218. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44219. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44220. */
  44221. _this._useLinearAlphaFresnel = false;
  44222. /**
  44223. * The transparency mode of the material.
  44224. */
  44225. _this._transparencyMode = null;
  44226. /**
  44227. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44228. * from cos thetav and roughness:
  44229. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44230. */
  44231. _this._environmentBRDFTexture = null;
  44232. /**
  44233. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44234. */
  44235. _this._forceIrradianceInFragment = false;
  44236. /**
  44237. * Force normal to face away from face.
  44238. */
  44239. _this._forceNormalForward = false;
  44240. /**
  44241. * Enables specular anti aliasing in the PBR shader.
  44242. * It will both interacts on the Geometry for analytical and IBL lighting.
  44243. * It also prefilter the roughness map based on the bump values.
  44244. */
  44245. _this._enableSpecularAntiAliasing = false;
  44246. /**
  44247. * Stores the available render targets.
  44248. */
  44249. _this._renderTargets = new BABYLON.SmartArray(16);
  44250. /**
  44251. * Sets the global ambient color for the material used in lighting calculations.
  44252. */
  44253. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44254. /**
  44255. * If set to true, no lighting calculations will be applied.
  44256. */
  44257. _this._unlit = false;
  44258. // Setup the default processing configuration to the scene.
  44259. _this._attachImageProcessingConfiguration(null);
  44260. _this.getRenderTargetTextures = function () {
  44261. _this._renderTargets.reset();
  44262. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44263. _this._renderTargets.push(_this._reflectionTexture);
  44264. }
  44265. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44266. _this._renderTargets.push(_this._refractionTexture);
  44267. }
  44268. return _this._renderTargets;
  44269. };
  44270. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44271. return _this;
  44272. }
  44273. /**
  44274. * Attaches a new image processing configuration to the PBR Material.
  44275. * @param configuration
  44276. */
  44277. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44278. var _this = this;
  44279. if (configuration === this._imageProcessingConfiguration) {
  44280. return;
  44281. }
  44282. // Detaches observer.
  44283. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44284. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44285. }
  44286. // Pick the scene configuration if needed.
  44287. if (!configuration) {
  44288. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44289. }
  44290. else {
  44291. this._imageProcessingConfiguration = configuration;
  44292. }
  44293. // Attaches observer.
  44294. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44295. _this._markAllSubMeshesAsImageProcessingDirty();
  44296. });
  44297. };
  44298. /**
  44299. * Gets the name of the material class.
  44300. */
  44301. PBRBaseMaterial.prototype.getClassName = function () {
  44302. return "PBRBaseMaterial";
  44303. };
  44304. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44305. /**
  44306. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44307. */
  44308. get: function () {
  44309. return this._useLogarithmicDepth;
  44310. },
  44311. /**
  44312. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44313. */
  44314. set: function (value) {
  44315. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44316. },
  44317. enumerable: true,
  44318. configurable: true
  44319. });
  44320. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44321. /**
  44322. * Gets the current transparency mode.
  44323. */
  44324. get: function () {
  44325. return this._transparencyMode;
  44326. },
  44327. /**
  44328. * Sets the transparency mode of the material.
  44329. */
  44330. set: function (value) {
  44331. if (this._transparencyMode === value) {
  44332. return;
  44333. }
  44334. this._transparencyMode = value;
  44335. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44336. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44337. },
  44338. enumerable: true,
  44339. configurable: true
  44340. });
  44341. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44342. /**
  44343. * Returns true if alpha blending should be disabled.
  44344. */
  44345. get: function () {
  44346. return (this._linkRefractionWithTransparency ||
  44347. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44348. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44349. },
  44350. enumerable: true,
  44351. configurable: true
  44352. });
  44353. /**
  44354. * Specifies whether or not this material should be rendered in alpha blend mode.
  44355. */
  44356. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44357. if (this._disableAlphaBlending) {
  44358. return false;
  44359. }
  44360. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44361. };
  44362. /**
  44363. * Specifies if the mesh will require alpha blending.
  44364. * @param mesh - BJS mesh.
  44365. */
  44366. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44367. if (this._disableAlphaBlending) {
  44368. return false;
  44369. }
  44370. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44371. };
  44372. /**
  44373. * Specifies whether or not this material should be rendered in alpha test mode.
  44374. */
  44375. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44376. if (this._forceAlphaTest) {
  44377. return true;
  44378. }
  44379. if (this._linkRefractionWithTransparency) {
  44380. return false;
  44381. }
  44382. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44383. };
  44384. /**
  44385. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44386. */
  44387. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44388. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44389. };
  44390. /**
  44391. * Gets the texture used for the alpha test.
  44392. */
  44393. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44394. return this._albedoTexture;
  44395. };
  44396. /**
  44397. * Specifies that the submesh is ready to be used.
  44398. * @param mesh - BJS mesh.
  44399. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44400. * @param useInstances - Specifies that instances should be used.
  44401. * @returns - boolean indicating that the submesh is ready or not.
  44402. */
  44403. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44404. if (subMesh.effect && this.isFrozen) {
  44405. if (this._wasPreviouslyReady) {
  44406. return true;
  44407. }
  44408. }
  44409. if (!subMesh._materialDefines) {
  44410. subMesh._materialDefines = new PBRMaterialDefines();
  44411. }
  44412. var defines = subMesh._materialDefines;
  44413. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44414. if (defines._renderId === this.getScene().getRenderId()) {
  44415. return true;
  44416. }
  44417. }
  44418. var scene = this.getScene();
  44419. var engine = scene.getEngine();
  44420. if (defines._areTexturesDirty) {
  44421. if (scene.texturesEnabled) {
  44422. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44423. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44424. return false;
  44425. }
  44426. }
  44427. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44428. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44429. return false;
  44430. }
  44431. }
  44432. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44433. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44434. return false;
  44435. }
  44436. }
  44437. var reflectionTexture = this._getReflectionTexture();
  44438. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44439. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44440. return false;
  44441. }
  44442. }
  44443. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44444. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44445. return false;
  44446. }
  44447. }
  44448. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44449. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44450. return false;
  44451. }
  44452. }
  44453. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44454. if (this._metallicTexture) {
  44455. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44456. return false;
  44457. }
  44458. }
  44459. else if (this._reflectivityTexture) {
  44460. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44461. return false;
  44462. }
  44463. }
  44464. if (this._microSurfaceTexture) {
  44465. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44466. return false;
  44467. }
  44468. }
  44469. }
  44470. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44471. // Bump texture cannot be not blocking.
  44472. if (!this._bumpTexture.isReady()) {
  44473. return false;
  44474. }
  44475. }
  44476. var refractionTexture = this._getRefractionTexture();
  44477. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44478. if (!refractionTexture.isReadyOrNotBlocking()) {
  44479. return false;
  44480. }
  44481. }
  44482. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44483. // This is blocking.
  44484. if (!this._environmentBRDFTexture.isReady()) {
  44485. return false;
  44486. }
  44487. }
  44488. }
  44489. }
  44490. if (defines._areImageProcessingDirty) {
  44491. if (!this._imageProcessingConfiguration.isReady()) {
  44492. return false;
  44493. }
  44494. }
  44495. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44496. mesh.createNormals(true);
  44497. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44498. }
  44499. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44500. if (effect) {
  44501. scene.resetCachedMaterial();
  44502. subMesh.setEffect(effect, defines);
  44503. this.buildUniformLayout();
  44504. }
  44505. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44506. return false;
  44507. }
  44508. defines._renderId = scene.getRenderId();
  44509. this._wasPreviouslyReady = true;
  44510. return true;
  44511. };
  44512. /**
  44513. * Specifies if the material uses metallic roughness workflow.
  44514. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44515. */
  44516. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44517. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44518. return true;
  44519. }
  44520. return false;
  44521. };
  44522. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44523. if (onCompiled === void 0) { onCompiled = null; }
  44524. if (onError === void 0) { onError = null; }
  44525. if (useInstances === void 0) { useInstances = null; }
  44526. if (useClipPlane === void 0) { useClipPlane = null; }
  44527. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44528. if (!defines.isDirty) {
  44529. return null;
  44530. }
  44531. defines.markAsProcessed();
  44532. var scene = this.getScene();
  44533. var engine = scene.getEngine();
  44534. // Fallbacks
  44535. var fallbacks = new BABYLON.EffectFallbacks();
  44536. var fallbackRank = 0;
  44537. if (defines.USESPHERICALINVERTEX) {
  44538. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44539. }
  44540. if (defines.FOG) {
  44541. fallbacks.addFallback(fallbackRank, "FOG");
  44542. }
  44543. if (defines.POINTSIZE) {
  44544. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44545. }
  44546. if (defines.LOGARITHMICDEPTH) {
  44547. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44548. }
  44549. if (defines.PARALLAX) {
  44550. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44551. }
  44552. if (defines.PARALLAXOCCLUSION) {
  44553. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44554. }
  44555. if (defines.ENVIRONMENTBRDF) {
  44556. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44557. }
  44558. if (defines.TANGENT) {
  44559. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44560. }
  44561. if (defines.BUMP) {
  44562. fallbacks.addFallback(fallbackRank++, "BUMP");
  44563. }
  44564. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44565. if (defines.SPECULARTERM) {
  44566. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44567. }
  44568. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44569. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44570. }
  44571. if (defines.LIGHTMAP) {
  44572. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44573. }
  44574. if (defines.NORMAL) {
  44575. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44576. }
  44577. if (defines.AMBIENT) {
  44578. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44579. }
  44580. if (defines.EMISSIVE) {
  44581. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44582. }
  44583. if (defines.VERTEXCOLOR) {
  44584. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44585. }
  44586. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44587. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44588. }
  44589. if (defines.MORPHTARGETS) {
  44590. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44591. }
  44592. //Attributes
  44593. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44594. if (defines.NORMAL) {
  44595. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44596. }
  44597. if (defines.TANGENT) {
  44598. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44599. }
  44600. if (defines.UV1) {
  44601. attribs.push(BABYLON.VertexBuffer.UVKind);
  44602. }
  44603. if (defines.UV2) {
  44604. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44605. }
  44606. if (defines.VERTEXCOLOR) {
  44607. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44608. }
  44609. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44610. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44611. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44612. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44613. "vFogInfos", "vFogColor", "pointSize",
  44614. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44615. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44616. "mBones",
  44617. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44618. "vLightingIntensity",
  44619. "logarithmicDepthConstant",
  44620. "vSphericalX", "vSphericalY", "vSphericalZ",
  44621. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44622. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44623. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44624. "vTangentSpaceParams"
  44625. ];
  44626. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44627. "bumpSampler", "lightmapSampler", "opacitySampler",
  44628. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44629. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44630. "microSurfaceSampler", "environmentBrdfSampler"];
  44631. var uniformBuffers = ["Material", "Scene"];
  44632. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44633. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44634. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44635. uniformsNames: uniforms,
  44636. uniformBuffersNames: uniformBuffers,
  44637. samplers: samplers,
  44638. defines: defines,
  44639. maxSimultaneousLights: this._maxSimultaneousLights
  44640. });
  44641. var join = defines.toString();
  44642. return engine.createEffect("pbr", {
  44643. attributes: attribs,
  44644. uniformsNames: uniforms,
  44645. uniformBuffersNames: uniformBuffers,
  44646. samplers: samplers,
  44647. defines: join,
  44648. fallbacks: fallbacks,
  44649. onCompiled: onCompiled,
  44650. onError: onError,
  44651. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44652. }, engine);
  44653. };
  44654. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44655. if (useInstances === void 0) { useInstances = null; }
  44656. if (useClipPlane === void 0) { useClipPlane = null; }
  44657. var scene = this.getScene();
  44658. var engine = scene.getEngine();
  44659. // Lights
  44660. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44661. defines._needNormals = true;
  44662. // Textures
  44663. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44664. if (defines._areTexturesDirty) {
  44665. defines._needUVs = false;
  44666. if (scene.texturesEnabled) {
  44667. if (scene.getEngine().getCaps().textureLOD) {
  44668. defines.LODBASEDMICROSFURACE = true;
  44669. }
  44670. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44671. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44672. }
  44673. else {
  44674. defines.ALBEDO = false;
  44675. }
  44676. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44677. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44678. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44679. }
  44680. else {
  44681. defines.AMBIENT = false;
  44682. }
  44683. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44684. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44685. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44686. }
  44687. else {
  44688. defines.OPACITY = false;
  44689. }
  44690. var reflectionTexture = this._getReflectionTexture();
  44691. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44692. defines.REFLECTION = true;
  44693. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44694. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44695. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44696. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44697. defines.INVERTCUBICMAP = true;
  44698. }
  44699. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44700. switch (reflectionTexture.coordinatesMode) {
  44701. case BABYLON.Texture.CUBIC_MODE:
  44702. case BABYLON.Texture.INVCUBIC_MODE:
  44703. defines.REFLECTIONMAP_CUBIC = true;
  44704. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44705. break;
  44706. case BABYLON.Texture.EXPLICIT_MODE:
  44707. defines.REFLECTIONMAP_EXPLICIT = true;
  44708. break;
  44709. case BABYLON.Texture.PLANAR_MODE:
  44710. defines.REFLECTIONMAP_PLANAR = true;
  44711. break;
  44712. case BABYLON.Texture.PROJECTION_MODE:
  44713. defines.REFLECTIONMAP_PROJECTION = true;
  44714. break;
  44715. case BABYLON.Texture.SKYBOX_MODE:
  44716. defines.REFLECTIONMAP_SKYBOX = true;
  44717. break;
  44718. case BABYLON.Texture.SPHERICAL_MODE:
  44719. defines.REFLECTIONMAP_SPHERICAL = true;
  44720. break;
  44721. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44722. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44723. break;
  44724. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44725. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44726. break;
  44727. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44728. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44729. break;
  44730. }
  44731. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44732. if (reflectionTexture.sphericalPolynomial) {
  44733. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44734. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44735. defines.USESPHERICALINVERTEX = false;
  44736. }
  44737. else {
  44738. defines.USESPHERICALINVERTEX = true;
  44739. }
  44740. }
  44741. }
  44742. }
  44743. else {
  44744. defines.REFLECTION = false;
  44745. defines.REFLECTIONMAP_3D = false;
  44746. defines.REFLECTIONMAP_SPHERICAL = false;
  44747. defines.REFLECTIONMAP_PLANAR = false;
  44748. defines.REFLECTIONMAP_CUBIC = false;
  44749. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44750. defines.REFLECTIONMAP_PROJECTION = false;
  44751. defines.REFLECTIONMAP_SKYBOX = false;
  44752. defines.REFLECTIONMAP_EXPLICIT = false;
  44753. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44754. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44755. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44756. defines.INVERTCUBICMAP = false;
  44757. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44758. defines.USESPHERICALINVERTEX = false;
  44759. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44760. defines.LODINREFLECTIONALPHA = false;
  44761. defines.GAMMAREFLECTION = false;
  44762. }
  44763. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44764. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44765. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44766. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44767. }
  44768. else {
  44769. defines.LIGHTMAP = false;
  44770. }
  44771. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44772. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44773. }
  44774. else {
  44775. defines.EMISSIVE = false;
  44776. }
  44777. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44778. if (this._metallicTexture) {
  44779. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44780. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44781. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44782. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44783. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44784. }
  44785. else if (this._reflectivityTexture) {
  44786. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44787. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44788. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44789. }
  44790. else {
  44791. defines.REFLECTIVITY = false;
  44792. }
  44793. if (this._microSurfaceTexture) {
  44794. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44795. }
  44796. else {
  44797. defines.MICROSURFACEMAP = false;
  44798. }
  44799. }
  44800. else {
  44801. defines.REFLECTIVITY = false;
  44802. defines.MICROSURFACEMAP = false;
  44803. }
  44804. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44805. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44806. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44807. defines.PARALLAX = true;
  44808. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44809. }
  44810. else {
  44811. defines.PARALLAX = false;
  44812. }
  44813. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44814. }
  44815. else {
  44816. defines.BUMP = false;
  44817. }
  44818. var refractionTexture = this._getRefractionTexture();
  44819. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44820. defines.REFRACTION = true;
  44821. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44822. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44823. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44824. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44825. if (this._linkRefractionWithTransparency) {
  44826. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44827. }
  44828. }
  44829. else {
  44830. defines.REFRACTION = false;
  44831. }
  44832. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44833. defines.ENVIRONMENTBRDF = true;
  44834. }
  44835. else {
  44836. defines.ENVIRONMENTBRDF = false;
  44837. }
  44838. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44839. defines.ALPHAFROMALBEDO = true;
  44840. }
  44841. else {
  44842. defines.ALPHAFROMALBEDO = false;
  44843. }
  44844. }
  44845. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44846. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44847. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44848. if (!this.backFaceCulling && this._twoSidedLighting) {
  44849. defines.TWOSIDEDLIGHTING = true;
  44850. }
  44851. else {
  44852. defines.TWOSIDEDLIGHTING = false;
  44853. }
  44854. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44855. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44856. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44857. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44858. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44859. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44860. }
  44861. if (defines._areImageProcessingDirty) {
  44862. this._imageProcessingConfiguration.prepareDefines(defines);
  44863. }
  44864. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44865. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44866. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44867. // Misc.
  44868. if (defines._areMiscDirty) {
  44869. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44870. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44871. }
  44872. // Values that need to be evaluated on every frame
  44873. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44874. // Attribs
  44875. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44876. };
  44877. /**
  44878. * Force shader compilation
  44879. */
  44880. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44881. var _this = this;
  44882. var localOptions = __assign({ clipPlane: false }, options);
  44883. var defines = new PBRMaterialDefines();
  44884. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44885. if (effect.isReady()) {
  44886. if (onCompiled) {
  44887. onCompiled(this);
  44888. }
  44889. }
  44890. else {
  44891. effect.onCompileObservable.add(function () {
  44892. if (onCompiled) {
  44893. onCompiled(_this);
  44894. }
  44895. });
  44896. }
  44897. };
  44898. /**
  44899. * Initializes the uniform buffer layout for the shader.
  44900. */
  44901. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44902. // Order is important !
  44903. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44904. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44905. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44906. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44907. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44908. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44909. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44910. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44911. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44912. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44913. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44914. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44915. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44916. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44917. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44918. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44919. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44920. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44921. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44922. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44923. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44924. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44925. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44926. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44927. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44928. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44929. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44930. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44931. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44932. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44933. this._uniformBuffer.addUniform("pointSize", 1);
  44934. this._uniformBuffer.create();
  44935. };
  44936. /**
  44937. * Unbinds the textures.
  44938. */
  44939. PBRBaseMaterial.prototype.unbind = function () {
  44940. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44941. this._uniformBuffer.setTexture("reflectionSampler", null);
  44942. }
  44943. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44944. this._uniformBuffer.setTexture("refractionSampler", null);
  44945. }
  44946. _super.prototype.unbind.call(this);
  44947. };
  44948. /**
  44949. * Binds the submesh data.
  44950. * @param world - The world matrix.
  44951. * @param mesh - The BJS mesh.
  44952. * @param subMesh - A submesh of the BJS mesh.
  44953. */
  44954. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44955. var scene = this.getScene();
  44956. var defines = subMesh._materialDefines;
  44957. if (!defines) {
  44958. return;
  44959. }
  44960. var effect = subMesh.effect;
  44961. if (!effect) {
  44962. return;
  44963. }
  44964. this._activeEffect = effect;
  44965. // Matrices
  44966. this.bindOnlyWorldMatrix(world);
  44967. // Normal Matrix
  44968. if (defines.OBJECTSPACE_NORMALMAP) {
  44969. world.toNormalMatrix(this._normalMatrix);
  44970. this.bindOnlyNormalMatrix(this._normalMatrix);
  44971. }
  44972. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44973. // Bones
  44974. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44975. var reflectionTexture = null;
  44976. if (mustRebind) {
  44977. this._uniformBuffer.bindToEffect(effect, "Material");
  44978. this.bindViewProjection(effect);
  44979. reflectionTexture = this._getReflectionTexture();
  44980. var refractionTexture = this._getRefractionTexture();
  44981. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44982. // Texture uniforms
  44983. if (scene.texturesEnabled) {
  44984. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44985. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44986. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44987. }
  44988. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44989. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44990. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44991. }
  44992. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44993. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44994. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44995. }
  44996. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44997. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44998. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44999. if (reflectionTexture.boundingBoxSize) {
  45000. var cubeTexture = reflectionTexture;
  45001. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45002. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45003. }
  45004. var polynomials = reflectionTexture.sphericalPolynomial;
  45005. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45006. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45007. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45008. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45009. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45010. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45011. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45012. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45013. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45014. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45015. }
  45016. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45017. }
  45018. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45019. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45020. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45021. }
  45022. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45023. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45024. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45025. }
  45026. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45027. if (this._metallicTexture) {
  45028. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45029. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45030. }
  45031. else if (this._reflectivityTexture) {
  45032. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45033. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45034. }
  45035. if (this._microSurfaceTexture) {
  45036. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45037. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45038. }
  45039. }
  45040. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45041. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45042. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45043. if (scene._mirroredCameraPosition) {
  45044. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45045. }
  45046. else {
  45047. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45048. }
  45049. }
  45050. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45051. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45052. var depth = 1.0;
  45053. if (!refractionTexture.isCube) {
  45054. if (refractionTexture.depth) {
  45055. depth = refractionTexture.depth;
  45056. }
  45057. }
  45058. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45059. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45060. }
  45061. }
  45062. // Point size
  45063. if (this.pointsCloud) {
  45064. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45065. }
  45066. // Colors
  45067. if (defines.METALLICWORKFLOW) {
  45068. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45069. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45070. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45071. }
  45072. else {
  45073. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45074. }
  45075. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45076. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45077. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45078. // Misc
  45079. this._lightingInfos.x = this._directIntensity;
  45080. this._lightingInfos.y = this._emissiveIntensity;
  45081. this._lightingInfos.z = this._environmentIntensity;
  45082. this._lightingInfos.w = this._specularIntensity;
  45083. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45084. }
  45085. // Textures
  45086. if (scene.texturesEnabled) {
  45087. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45088. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45089. }
  45090. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45091. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45092. }
  45093. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45094. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45095. }
  45096. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45097. if (defines.LODBASEDMICROSFURACE) {
  45098. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45099. }
  45100. else {
  45101. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45102. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45103. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45104. }
  45105. }
  45106. if (defines.ENVIRONMENTBRDF) {
  45107. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45108. }
  45109. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45110. if (defines.LODBASEDMICROSFURACE) {
  45111. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45112. }
  45113. else {
  45114. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45115. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45116. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45117. }
  45118. }
  45119. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45120. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45121. }
  45122. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45123. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45124. }
  45125. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45126. if (this._metallicTexture) {
  45127. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45128. }
  45129. else if (this._reflectivityTexture) {
  45130. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45131. }
  45132. if (this._microSurfaceTexture) {
  45133. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45134. }
  45135. }
  45136. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45137. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45138. }
  45139. }
  45140. // Clip plane
  45141. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45142. // Colors
  45143. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45144. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45145. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45146. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45147. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45148. }
  45149. if (mustRebind || !this.isFrozen) {
  45150. // Lights
  45151. if (scene.lightsEnabled && !this._disableLighting) {
  45152. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45153. }
  45154. // View
  45155. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45156. this.bindView(effect);
  45157. }
  45158. // Fog
  45159. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45160. // Morph targets
  45161. if (defines.NUM_MORPH_INFLUENCERS) {
  45162. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45163. }
  45164. // image processing
  45165. this._imageProcessingConfiguration.bind(this._activeEffect);
  45166. // Log. depth
  45167. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45168. }
  45169. this._uniformBuffer.update();
  45170. this._afterBind(mesh);
  45171. };
  45172. /**
  45173. * Returns the animatable textures.
  45174. * @returns - Array of animatable textures.
  45175. */
  45176. PBRBaseMaterial.prototype.getAnimatables = function () {
  45177. var results = [];
  45178. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45179. results.push(this._albedoTexture);
  45180. }
  45181. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45182. results.push(this._ambientTexture);
  45183. }
  45184. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45185. results.push(this._opacityTexture);
  45186. }
  45187. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45188. results.push(this._reflectionTexture);
  45189. }
  45190. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45191. results.push(this._emissiveTexture);
  45192. }
  45193. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45194. results.push(this._metallicTexture);
  45195. }
  45196. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45197. results.push(this._reflectivityTexture);
  45198. }
  45199. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45200. results.push(this._bumpTexture);
  45201. }
  45202. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45203. results.push(this._lightmapTexture);
  45204. }
  45205. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45206. results.push(this._refractionTexture);
  45207. }
  45208. return results;
  45209. };
  45210. /**
  45211. * Returns the texture used for reflections.
  45212. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45213. */
  45214. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45215. if (this._reflectionTexture) {
  45216. return this._reflectionTexture;
  45217. }
  45218. return this.getScene().environmentTexture;
  45219. };
  45220. /**
  45221. * Returns the texture used for refraction or null if none is used.
  45222. * @returns - Refection texture if present. If no refraction texture and refraction
  45223. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45224. */
  45225. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45226. if (this._refractionTexture) {
  45227. return this._refractionTexture;
  45228. }
  45229. if (this._linkRefractionWithTransparency) {
  45230. return this.getScene().environmentTexture;
  45231. }
  45232. return null;
  45233. };
  45234. /**
  45235. * Disposes the resources of the material.
  45236. * @param forceDisposeEffect - Forces the disposal of effects.
  45237. * @param forceDisposeTextures - Forces the disposal of all textures.
  45238. */
  45239. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45240. if (forceDisposeTextures) {
  45241. if (this._albedoTexture) {
  45242. this._albedoTexture.dispose();
  45243. }
  45244. if (this._ambientTexture) {
  45245. this._ambientTexture.dispose();
  45246. }
  45247. if (this._opacityTexture) {
  45248. this._opacityTexture.dispose();
  45249. }
  45250. if (this._reflectionTexture) {
  45251. this._reflectionTexture.dispose();
  45252. }
  45253. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45254. this._environmentBRDFTexture.dispose();
  45255. }
  45256. if (this._emissiveTexture) {
  45257. this._emissiveTexture.dispose();
  45258. }
  45259. if (this._metallicTexture) {
  45260. this._metallicTexture.dispose();
  45261. }
  45262. if (this._reflectivityTexture) {
  45263. this._reflectivityTexture.dispose();
  45264. }
  45265. if (this._bumpTexture) {
  45266. this._bumpTexture.dispose();
  45267. }
  45268. if (this._lightmapTexture) {
  45269. this._lightmapTexture.dispose();
  45270. }
  45271. if (this._refractionTexture) {
  45272. this._refractionTexture.dispose();
  45273. }
  45274. }
  45275. this._renderTargets.dispose();
  45276. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45277. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45278. }
  45279. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45280. };
  45281. /**
  45282. * Stores the reflectivity values based on metallic roughness workflow.
  45283. */
  45284. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45285. __decorate([
  45286. BABYLON.serializeAsImageProcessingConfiguration()
  45287. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45288. __decorate([
  45289. BABYLON.serialize()
  45290. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45291. __decorate([
  45292. BABYLON.serialize()
  45293. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45294. return PBRBaseMaterial;
  45295. }(BABYLON.PushMaterial));
  45296. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45297. })(BABYLON || (BABYLON = {}));
  45298. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45299. var BABYLON;
  45300. (function (BABYLON) {
  45301. /**
  45302. * The Physically based simple base material of BJS.
  45303. *
  45304. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45305. * It is used as the base class for both the specGloss and metalRough conventions.
  45306. */
  45307. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45308. __extends(PBRBaseSimpleMaterial, _super);
  45309. /**
  45310. * Instantiates a new PBRMaterial instance.
  45311. *
  45312. * @param name The material name
  45313. * @param scene The scene the material will be use in.
  45314. */
  45315. function PBRBaseSimpleMaterial(name, scene) {
  45316. var _this = _super.call(this, name, scene) || this;
  45317. /**
  45318. * Number of Simultaneous lights allowed on the material.
  45319. */
  45320. _this.maxSimultaneousLights = 4;
  45321. /**
  45322. * If sets to true, disables all the lights affecting the material.
  45323. */
  45324. _this.disableLighting = false;
  45325. /**
  45326. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45327. */
  45328. _this.invertNormalMapX = false;
  45329. /**
  45330. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45331. */
  45332. _this.invertNormalMapY = false;
  45333. /**
  45334. * Emissivie color used to self-illuminate the model.
  45335. */
  45336. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45337. /**
  45338. * Occlusion Channel Strenght.
  45339. */
  45340. _this.occlusionStrength = 1.0;
  45341. _this.useLightmapAsShadowmap = false;
  45342. _this._useAlphaFromAlbedoTexture = true;
  45343. _this._useAmbientInGrayScale = true;
  45344. return _this;
  45345. }
  45346. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45347. /**
  45348. * Gets the current double sided mode.
  45349. */
  45350. get: function () {
  45351. return this._twoSidedLighting;
  45352. },
  45353. /**
  45354. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45355. */
  45356. set: function (value) {
  45357. if (this._twoSidedLighting === value) {
  45358. return;
  45359. }
  45360. this._twoSidedLighting = value;
  45361. this.backFaceCulling = !value;
  45362. this._markAllSubMeshesAsTexturesDirty();
  45363. },
  45364. enumerable: true,
  45365. configurable: true
  45366. });
  45367. /**
  45368. * Return the active textures of the material.
  45369. */
  45370. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45371. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45372. if (this.environmentTexture) {
  45373. activeTextures.push(this.environmentTexture);
  45374. }
  45375. if (this.normalTexture) {
  45376. activeTextures.push(this.normalTexture);
  45377. }
  45378. if (this.emissiveTexture) {
  45379. activeTextures.push(this.emissiveTexture);
  45380. }
  45381. if (this.occlusionTexture) {
  45382. activeTextures.push(this.occlusionTexture);
  45383. }
  45384. if (this.lightmapTexture) {
  45385. activeTextures.push(this.lightmapTexture);
  45386. }
  45387. return activeTextures;
  45388. };
  45389. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45390. if (_super.prototype.hasTexture.call(this, texture)) {
  45391. return true;
  45392. }
  45393. if (this.lightmapTexture === texture) {
  45394. return true;
  45395. }
  45396. return false;
  45397. };
  45398. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45399. return "PBRBaseSimpleMaterial";
  45400. };
  45401. __decorate([
  45402. BABYLON.serialize(),
  45403. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45404. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45405. __decorate([
  45406. BABYLON.serialize(),
  45407. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45408. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45409. __decorate([
  45410. BABYLON.serializeAsTexture(),
  45411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45412. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45413. __decorate([
  45414. BABYLON.serialize(),
  45415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45416. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45417. __decorate([
  45418. BABYLON.serialize(),
  45419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45420. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45421. __decorate([
  45422. BABYLON.serializeAsTexture(),
  45423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45424. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45425. __decorate([
  45426. BABYLON.serializeAsColor3("emissive"),
  45427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45428. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45429. __decorate([
  45430. BABYLON.serializeAsTexture(),
  45431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45432. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45433. __decorate([
  45434. BABYLON.serialize(),
  45435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45436. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45437. __decorate([
  45438. BABYLON.serializeAsTexture(),
  45439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45440. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45441. __decorate([
  45442. BABYLON.serialize(),
  45443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45444. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45445. __decorate([
  45446. BABYLON.serialize()
  45447. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45448. __decorate([
  45449. BABYLON.serializeAsTexture(),
  45450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45451. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45452. __decorate([
  45453. BABYLON.serialize(),
  45454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45455. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45456. return PBRBaseSimpleMaterial;
  45457. }(BABYLON.PBRBaseMaterial));
  45458. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45459. })(BABYLON || (BABYLON = {}));
  45460. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45461. var BABYLON;
  45462. (function (BABYLON) {
  45463. /**
  45464. * The Physically based material of BJS.
  45465. *
  45466. * This offers the main features of a standard PBR material.
  45467. * For more information, please refer to the documentation :
  45468. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45469. */
  45470. var PBRMaterial = /** @class */ (function (_super) {
  45471. __extends(PBRMaterial, _super);
  45472. /**
  45473. * Instantiates a new PBRMaterial instance.
  45474. *
  45475. * @param name The material name
  45476. * @param scene The scene the material will be use in.
  45477. */
  45478. function PBRMaterial(name, scene) {
  45479. var _this = _super.call(this, name, scene) || this;
  45480. /**
  45481. * Intensity of the direct lights e.g. the four lights available in your scene.
  45482. * This impacts both the direct diffuse and specular highlights.
  45483. */
  45484. _this.directIntensity = 1.0;
  45485. /**
  45486. * Intensity of the emissive part of the material.
  45487. * This helps controlling the emissive effect without modifying the emissive color.
  45488. */
  45489. _this.emissiveIntensity = 1.0;
  45490. /**
  45491. * Intensity of the environment e.g. how much the environment will light the object
  45492. * either through harmonics for rough material or through the refelction for shiny ones.
  45493. */
  45494. _this.environmentIntensity = 1.0;
  45495. /**
  45496. * This is a special control allowing the reduction of the specular highlights coming from the
  45497. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45498. */
  45499. _this.specularIntensity = 1.0;
  45500. /**
  45501. * Debug Control allowing disabling the bump map on this material.
  45502. */
  45503. _this.disableBumpMap = false;
  45504. /**
  45505. * AKA Occlusion Texture Intensity in other nomenclature.
  45506. */
  45507. _this.ambientTextureStrength = 1.0;
  45508. /**
  45509. * The color of a material in ambient lighting.
  45510. */
  45511. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45512. /**
  45513. * AKA Diffuse Color in other nomenclature.
  45514. */
  45515. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45516. /**
  45517. * AKA Specular Color in other nomenclature.
  45518. */
  45519. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45520. /**
  45521. * The color reflected from the material.
  45522. */
  45523. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45524. /**
  45525. * The color emitted from the material.
  45526. */
  45527. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45528. /**
  45529. * AKA Glossiness in other nomenclature.
  45530. */
  45531. _this.microSurface = 1.0;
  45532. /**
  45533. * source material index of refraction (IOR)' / 'destination material IOR.
  45534. */
  45535. _this.indexOfRefraction = 0.66;
  45536. /**
  45537. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45538. */
  45539. _this.invertRefractionY = false;
  45540. /**
  45541. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45542. * Materials half opaque for instance using refraction could benefit from this control.
  45543. */
  45544. _this.linkRefractionWithTransparency = false;
  45545. _this.useLightmapAsShadowmap = false;
  45546. /**
  45547. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45548. */
  45549. _this.useAlphaFromAlbedoTexture = false;
  45550. /**
  45551. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45552. */
  45553. _this.forceAlphaTest = false;
  45554. /**
  45555. * Defines the alpha limits in alpha test mode.
  45556. */
  45557. _this.alphaCutOff = 0.4;
  45558. /**
  45559. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45560. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45561. */
  45562. _this.useSpecularOverAlpha = true;
  45563. /**
  45564. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45565. */
  45566. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45567. /**
  45568. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45569. */
  45570. _this.useRoughnessFromMetallicTextureAlpha = true;
  45571. /**
  45572. * Specifies if the metallic texture contains the roughness information in its green channel.
  45573. */
  45574. _this.useRoughnessFromMetallicTextureGreen = false;
  45575. /**
  45576. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45577. */
  45578. _this.useMetallnessFromMetallicTextureBlue = false;
  45579. /**
  45580. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45581. */
  45582. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45583. /**
  45584. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45585. */
  45586. _this.useAmbientInGrayScale = false;
  45587. /**
  45588. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45589. * The material will try to infer what glossiness each pixel should be.
  45590. */
  45591. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45592. /**
  45593. * BJS is using an harcoded light falloff based on a manually sets up range.
  45594. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45595. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45596. */
  45597. _this.usePhysicalLightFalloff = true;
  45598. /**
  45599. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45600. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45601. */
  45602. _this.useRadianceOverAlpha = true;
  45603. /**
  45604. * Allows using an object space normal map (instead of tangent space).
  45605. */
  45606. _this.useObjectSpaceNormalMap = false;
  45607. /**
  45608. * Allows using the bump map in parallax mode.
  45609. */
  45610. _this.useParallax = false;
  45611. /**
  45612. * Allows using the bump map in parallax occlusion mode.
  45613. */
  45614. _this.useParallaxOcclusion = false;
  45615. /**
  45616. * Controls the scale bias of the parallax mode.
  45617. */
  45618. _this.parallaxScaleBias = 0.05;
  45619. /**
  45620. * If sets to true, disables all the lights affecting the material.
  45621. */
  45622. _this.disableLighting = false;
  45623. /**
  45624. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45625. */
  45626. _this.forceIrradianceInFragment = false;
  45627. /**
  45628. * Number of Simultaneous lights allowed on the material.
  45629. */
  45630. _this.maxSimultaneousLights = 4;
  45631. /**
  45632. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45633. */
  45634. _this.invertNormalMapX = false;
  45635. /**
  45636. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45637. */
  45638. _this.invertNormalMapY = false;
  45639. /**
  45640. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45641. */
  45642. _this.twoSidedLighting = false;
  45643. /**
  45644. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45645. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45646. */
  45647. _this.useAlphaFresnel = false;
  45648. /**
  45649. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45650. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45651. */
  45652. _this.useLinearAlphaFresnel = false;
  45653. /**
  45654. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45655. * And/Or occlude the blended part.
  45656. */
  45657. _this.environmentBRDFTexture = null;
  45658. /**
  45659. * Force normal to face away from face.
  45660. */
  45661. _this.forceNormalForward = false;
  45662. /**
  45663. * Enables specular anti aliasing in the PBR shader.
  45664. * It will both interacts on the Geometry for analytical and IBL lighting.
  45665. * It also prefilter the roughness map based on the bump values.
  45666. */
  45667. _this.enableSpecularAntiAliasing = false;
  45668. /**
  45669. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45670. * makes the reflect vector face the model (under horizon).
  45671. */
  45672. _this.useHorizonOcclusion = true;
  45673. /**
  45674. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45675. * too much the area relying on ambient texture to define their ambient occlusion.
  45676. */
  45677. _this.useRadianceOcclusion = true;
  45678. /**
  45679. * If set to true, no lighting calculations will be applied.
  45680. */
  45681. _this.unlit = false;
  45682. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45683. return _this;
  45684. }
  45685. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45686. /**
  45687. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45688. */
  45689. get: function () {
  45690. return this._PBRMATERIAL_OPAQUE;
  45691. },
  45692. enumerable: true,
  45693. configurable: true
  45694. });
  45695. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45696. /**
  45697. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45698. */
  45699. get: function () {
  45700. return this._PBRMATERIAL_ALPHATEST;
  45701. },
  45702. enumerable: true,
  45703. configurable: true
  45704. });
  45705. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45706. /**
  45707. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45708. */
  45709. get: function () {
  45710. return this._PBRMATERIAL_ALPHABLEND;
  45711. },
  45712. enumerable: true,
  45713. configurable: true
  45714. });
  45715. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45716. /**
  45717. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45718. * They are also discarded below the alpha cutoff threshold to improve performances.
  45719. */
  45720. get: function () {
  45721. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45722. },
  45723. enumerable: true,
  45724. configurable: true
  45725. });
  45726. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45727. /**
  45728. * Gets the image processing configuration used either in this material.
  45729. */
  45730. get: function () {
  45731. return this._imageProcessingConfiguration;
  45732. },
  45733. /**
  45734. * Sets the Default image processing configuration used either in the this material.
  45735. *
  45736. * If sets to null, the scene one is in use.
  45737. */
  45738. set: function (value) {
  45739. this._attachImageProcessingConfiguration(value);
  45740. // Ensure the effect will be rebuilt.
  45741. this._markAllSubMeshesAsTexturesDirty();
  45742. },
  45743. enumerable: true,
  45744. configurable: true
  45745. });
  45746. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45747. /**
  45748. * Gets wether the color curves effect is enabled.
  45749. */
  45750. get: function () {
  45751. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45752. },
  45753. /**
  45754. * Sets wether the color curves effect is enabled.
  45755. */
  45756. set: function (value) {
  45757. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45758. },
  45759. enumerable: true,
  45760. configurable: true
  45761. });
  45762. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45763. /**
  45764. * Gets wether the color grading effect is enabled.
  45765. */
  45766. get: function () {
  45767. return this.imageProcessingConfiguration.colorGradingEnabled;
  45768. },
  45769. /**
  45770. * Gets wether the color grading effect is enabled.
  45771. */
  45772. set: function (value) {
  45773. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45774. },
  45775. enumerable: true,
  45776. configurable: true
  45777. });
  45778. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45779. /**
  45780. * Gets wether tonemapping is enabled or not.
  45781. */
  45782. get: function () {
  45783. return this._imageProcessingConfiguration.toneMappingEnabled;
  45784. },
  45785. /**
  45786. * Sets wether tonemapping is enabled or not
  45787. */
  45788. set: function (value) {
  45789. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45790. },
  45791. enumerable: true,
  45792. configurable: true
  45793. });
  45794. ;
  45795. ;
  45796. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45797. /**
  45798. * The camera exposure used on this material.
  45799. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45800. * This corresponds to a photographic exposure.
  45801. */
  45802. get: function () {
  45803. return this._imageProcessingConfiguration.exposure;
  45804. },
  45805. /**
  45806. * The camera exposure used on this material.
  45807. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45808. * This corresponds to a photographic exposure.
  45809. */
  45810. set: function (value) {
  45811. this._imageProcessingConfiguration.exposure = value;
  45812. },
  45813. enumerable: true,
  45814. configurable: true
  45815. });
  45816. ;
  45817. ;
  45818. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45819. /**
  45820. * Gets The camera contrast used on this material.
  45821. */
  45822. get: function () {
  45823. return this._imageProcessingConfiguration.contrast;
  45824. },
  45825. /**
  45826. * Sets The camera contrast used on this material.
  45827. */
  45828. set: function (value) {
  45829. this._imageProcessingConfiguration.contrast = value;
  45830. },
  45831. enumerable: true,
  45832. configurable: true
  45833. });
  45834. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45835. /**
  45836. * Gets the Color Grading 2D Lookup Texture.
  45837. */
  45838. get: function () {
  45839. return this._imageProcessingConfiguration.colorGradingTexture;
  45840. },
  45841. /**
  45842. * Sets the Color Grading 2D Lookup Texture.
  45843. */
  45844. set: function (value) {
  45845. this._imageProcessingConfiguration.colorGradingTexture = value;
  45846. },
  45847. enumerable: true,
  45848. configurable: true
  45849. });
  45850. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45851. /**
  45852. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45853. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45854. * 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;
  45855. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45856. */
  45857. get: function () {
  45858. return this._imageProcessingConfiguration.colorCurves;
  45859. },
  45860. /**
  45861. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45862. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45863. * 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;
  45864. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45865. */
  45866. set: function (value) {
  45867. this._imageProcessingConfiguration.colorCurves = value;
  45868. },
  45869. enumerable: true,
  45870. configurable: true
  45871. });
  45872. /**
  45873. * Returns the name of this material class.
  45874. */
  45875. PBRMaterial.prototype.getClassName = function () {
  45876. return "PBRMaterial";
  45877. };
  45878. /**
  45879. * Returns an array of the actively used textures.
  45880. * @returns - Array of BaseTextures
  45881. */
  45882. PBRMaterial.prototype.getActiveTextures = function () {
  45883. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45884. if (this._albedoTexture) {
  45885. activeTextures.push(this._albedoTexture);
  45886. }
  45887. if (this._ambientTexture) {
  45888. activeTextures.push(this._ambientTexture);
  45889. }
  45890. if (this._opacityTexture) {
  45891. activeTextures.push(this._opacityTexture);
  45892. }
  45893. if (this._reflectionTexture) {
  45894. activeTextures.push(this._reflectionTexture);
  45895. }
  45896. if (this._emissiveTexture) {
  45897. activeTextures.push(this._emissiveTexture);
  45898. }
  45899. if (this._reflectivityTexture) {
  45900. activeTextures.push(this._reflectivityTexture);
  45901. }
  45902. if (this._metallicTexture) {
  45903. activeTextures.push(this._metallicTexture);
  45904. }
  45905. if (this._microSurfaceTexture) {
  45906. activeTextures.push(this._microSurfaceTexture);
  45907. }
  45908. if (this._bumpTexture) {
  45909. activeTextures.push(this._bumpTexture);
  45910. }
  45911. if (this._lightmapTexture) {
  45912. activeTextures.push(this._lightmapTexture);
  45913. }
  45914. if (this._refractionTexture) {
  45915. activeTextures.push(this._refractionTexture);
  45916. }
  45917. return activeTextures;
  45918. };
  45919. /**
  45920. * Checks to see if a texture is used in the material.
  45921. * @param texture - Base texture to use.
  45922. * @returns - Boolean specifying if a texture is used in the material.
  45923. */
  45924. PBRMaterial.prototype.hasTexture = function (texture) {
  45925. if (_super.prototype.hasTexture.call(this, texture)) {
  45926. return true;
  45927. }
  45928. if (this._albedoTexture === texture) {
  45929. return true;
  45930. }
  45931. if (this._ambientTexture === texture) {
  45932. return true;
  45933. }
  45934. if (this._opacityTexture === texture) {
  45935. return true;
  45936. }
  45937. if (this._reflectionTexture === texture) {
  45938. return true;
  45939. }
  45940. if (this._reflectivityTexture === texture) {
  45941. return true;
  45942. }
  45943. if (this._metallicTexture === texture) {
  45944. return true;
  45945. }
  45946. if (this._microSurfaceTexture === texture) {
  45947. return true;
  45948. }
  45949. if (this._bumpTexture === texture) {
  45950. return true;
  45951. }
  45952. if (this._lightmapTexture === texture) {
  45953. return true;
  45954. }
  45955. if (this._refractionTexture === texture) {
  45956. return true;
  45957. }
  45958. return false;
  45959. };
  45960. /**
  45961. * Makes a duplicate of the current material.
  45962. * @param name - name to use for the new material.
  45963. */
  45964. PBRMaterial.prototype.clone = function (name) {
  45965. var _this = this;
  45966. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45967. clone.id = name;
  45968. clone.name = name;
  45969. return clone;
  45970. };
  45971. /**
  45972. * Serializes this PBR Material.
  45973. * @returns - An object with the serialized material.
  45974. */
  45975. PBRMaterial.prototype.serialize = function () {
  45976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45977. serializationObject.customType = "BABYLON.PBRMaterial";
  45978. return serializationObject;
  45979. };
  45980. // Statics
  45981. /**
  45982. * Parses a PBR Material from a serialized object.
  45983. * @param source - Serialized object.
  45984. * @param scene - BJS scene instance.
  45985. * @param rootUrl - url for the scene object
  45986. * @returns - PBRMaterial
  45987. */
  45988. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45989. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45990. };
  45991. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45992. /**
  45993. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45994. */
  45995. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45996. /**
  45997. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45998. */
  45999. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46000. /**
  46001. * 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.
  46002. * They are also discarded below the alpha cutoff threshold to improve performances.
  46003. */
  46004. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46005. __decorate([
  46006. BABYLON.serialize(),
  46007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46008. ], PBRMaterial.prototype, "directIntensity", void 0);
  46009. __decorate([
  46010. BABYLON.serialize(),
  46011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46012. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46013. __decorate([
  46014. BABYLON.serialize(),
  46015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46016. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46017. __decorate([
  46018. BABYLON.serialize(),
  46019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46020. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46021. __decorate([
  46022. BABYLON.serialize(),
  46023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46024. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46025. __decorate([
  46026. BABYLON.serializeAsTexture(),
  46027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46028. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46029. __decorate([
  46030. BABYLON.serializeAsTexture(),
  46031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46032. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46033. __decorate([
  46034. BABYLON.serialize(),
  46035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46036. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46037. __decorate([
  46038. BABYLON.serializeAsTexture(),
  46039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46040. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46041. __decorate([
  46042. BABYLON.serializeAsTexture(),
  46043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46044. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46045. __decorate([
  46046. BABYLON.serializeAsTexture(),
  46047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46048. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46049. __decorate([
  46050. BABYLON.serializeAsTexture(),
  46051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46052. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46053. __decorate([
  46054. BABYLON.serializeAsTexture(),
  46055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46056. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46057. __decorate([
  46058. BABYLON.serialize(),
  46059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46060. ], PBRMaterial.prototype, "metallic", void 0);
  46061. __decorate([
  46062. BABYLON.serialize(),
  46063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46064. ], PBRMaterial.prototype, "roughness", void 0);
  46065. __decorate([
  46066. BABYLON.serializeAsTexture(),
  46067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46068. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46069. __decorate([
  46070. BABYLON.serializeAsTexture(),
  46071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46072. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46073. __decorate([
  46074. BABYLON.serializeAsTexture(),
  46075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46076. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46077. __decorate([
  46078. BABYLON.serializeAsTexture(),
  46079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46080. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46081. __decorate([
  46082. BABYLON.serializeAsColor3("ambient"),
  46083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46084. ], PBRMaterial.prototype, "ambientColor", void 0);
  46085. __decorate([
  46086. BABYLON.serializeAsColor3("albedo"),
  46087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46088. ], PBRMaterial.prototype, "albedoColor", void 0);
  46089. __decorate([
  46090. BABYLON.serializeAsColor3("reflectivity"),
  46091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46092. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46093. __decorate([
  46094. BABYLON.serializeAsColor3("reflection"),
  46095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46096. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46097. __decorate([
  46098. BABYLON.serializeAsColor3("emissive"),
  46099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46100. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46101. __decorate([
  46102. BABYLON.serialize(),
  46103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46104. ], PBRMaterial.prototype, "microSurface", void 0);
  46105. __decorate([
  46106. BABYLON.serialize(),
  46107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46108. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46109. __decorate([
  46110. BABYLON.serialize(),
  46111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46112. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46113. __decorate([
  46114. BABYLON.serialize(),
  46115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46116. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46117. __decorate([
  46118. BABYLON.serialize(),
  46119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46120. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46121. __decorate([
  46122. BABYLON.serialize(),
  46123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46124. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46125. __decorate([
  46126. BABYLON.serialize(),
  46127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46128. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46129. __decorate([
  46130. BABYLON.serialize(),
  46131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46132. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46133. __decorate([
  46134. BABYLON.serialize(),
  46135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46136. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46137. __decorate([
  46138. BABYLON.serialize(),
  46139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46140. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46141. __decorate([
  46142. BABYLON.serialize(),
  46143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46144. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46145. __decorate([
  46146. BABYLON.serialize(),
  46147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46148. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46149. __decorate([
  46150. BABYLON.serialize(),
  46151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46152. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46153. __decorate([
  46154. BABYLON.serialize(),
  46155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46156. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46157. __decorate([
  46158. BABYLON.serialize(),
  46159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46160. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46161. __decorate([
  46162. BABYLON.serialize(),
  46163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46164. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46165. __decorate([
  46166. BABYLON.serialize(),
  46167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46168. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46169. __decorate([
  46170. BABYLON.serialize(),
  46171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46172. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46173. __decorate([
  46174. BABYLON.serialize(),
  46175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46176. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46177. __decorate([
  46178. BABYLON.serialize(),
  46179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46180. ], PBRMaterial.prototype, "useParallax", void 0);
  46181. __decorate([
  46182. BABYLON.serialize(),
  46183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46184. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46185. __decorate([
  46186. BABYLON.serialize(),
  46187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46188. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46189. __decorate([
  46190. BABYLON.serialize(),
  46191. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46192. ], PBRMaterial.prototype, "disableLighting", void 0);
  46193. __decorate([
  46194. BABYLON.serialize(),
  46195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46196. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46197. __decorate([
  46198. BABYLON.serialize(),
  46199. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46200. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46201. __decorate([
  46202. BABYLON.serialize(),
  46203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46204. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46205. __decorate([
  46206. BABYLON.serialize(),
  46207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46208. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46209. __decorate([
  46210. BABYLON.serialize(),
  46211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46212. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46213. __decorate([
  46214. BABYLON.serialize(),
  46215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46216. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46217. __decorate([
  46218. BABYLON.serialize(),
  46219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46220. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46221. __decorate([
  46222. BABYLON.serializeAsTexture(),
  46223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46224. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46225. __decorate([
  46226. BABYLON.serialize(),
  46227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46228. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46229. __decorate([
  46230. BABYLON.serialize(),
  46231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46232. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46233. __decorate([
  46234. BABYLON.serialize(),
  46235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46236. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46237. __decorate([
  46238. BABYLON.serialize(),
  46239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46240. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46241. __decorate([
  46242. BABYLON.serialize(),
  46243. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46244. ], PBRMaterial.prototype, "unlit", void 0);
  46245. return PBRMaterial;
  46246. }(BABYLON.PBRBaseMaterial));
  46247. BABYLON.PBRMaterial = PBRMaterial;
  46248. })(BABYLON || (BABYLON = {}));
  46249. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46250. var BABYLON;
  46251. (function (BABYLON) {
  46252. /**
  46253. * The PBR material of BJS following the metal roughness convention.
  46254. *
  46255. * This fits to the PBR convention in the GLTF definition:
  46256. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46257. */
  46258. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46259. __extends(PBRMetallicRoughnessMaterial, _super);
  46260. /**
  46261. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46262. *
  46263. * @param name The material name
  46264. * @param scene The scene the material will be use in.
  46265. */
  46266. function PBRMetallicRoughnessMaterial(name, scene) {
  46267. var _this = _super.call(this, name, scene) || this;
  46268. _this._useRoughnessFromMetallicTextureAlpha = false;
  46269. _this._useRoughnessFromMetallicTextureGreen = true;
  46270. _this._useMetallnessFromMetallicTextureBlue = true;
  46271. _this.metallic = 1.0;
  46272. _this.roughness = 1.0;
  46273. return _this;
  46274. }
  46275. /**
  46276. * Return the currrent class name of the material.
  46277. */
  46278. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46279. return "PBRMetallicRoughnessMaterial";
  46280. };
  46281. /**
  46282. * Return the active textures of the material.
  46283. */
  46284. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46285. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46286. if (this.baseTexture) {
  46287. activeTextures.push(this.baseTexture);
  46288. }
  46289. if (this.metallicRoughnessTexture) {
  46290. activeTextures.push(this.metallicRoughnessTexture);
  46291. }
  46292. return activeTextures;
  46293. };
  46294. /**
  46295. * Checks to see if a texture is used in the material.
  46296. * @param texture - Base texture to use.
  46297. * @returns - Boolean specifying if a texture is used in the material.
  46298. */
  46299. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46300. if (_super.prototype.hasTexture.call(this, texture)) {
  46301. return true;
  46302. }
  46303. if (this.baseTexture === texture) {
  46304. return true;
  46305. }
  46306. if (this.metallicRoughnessTexture === texture) {
  46307. return true;
  46308. }
  46309. return false;
  46310. };
  46311. /**
  46312. * Makes a duplicate of the current material.
  46313. * @param name - name to use for the new material.
  46314. */
  46315. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46316. var _this = this;
  46317. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46318. clone.id = name;
  46319. clone.name = name;
  46320. return clone;
  46321. };
  46322. /**
  46323. * Serialize the material to a parsable JSON object.
  46324. */
  46325. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46326. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46327. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46328. return serializationObject;
  46329. };
  46330. /**
  46331. * Parses a JSON object correponding to the serialize function.
  46332. */
  46333. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46334. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46335. };
  46336. __decorate([
  46337. BABYLON.serializeAsColor3(),
  46338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46339. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46340. __decorate([
  46341. BABYLON.serializeAsTexture(),
  46342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46343. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46344. __decorate([
  46345. BABYLON.serialize(),
  46346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46347. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46348. __decorate([
  46349. BABYLON.serialize(),
  46350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46351. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46352. __decorate([
  46353. BABYLON.serializeAsTexture(),
  46354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46355. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46356. return PBRMetallicRoughnessMaterial;
  46357. }(BABYLON.PBRBaseSimpleMaterial));
  46358. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46359. })(BABYLON || (BABYLON = {}));
  46360. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46361. var BABYLON;
  46362. (function (BABYLON) {
  46363. /**
  46364. * The PBR material of BJS following the specular glossiness convention.
  46365. *
  46366. * This fits to the PBR convention in the GLTF definition:
  46367. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46368. */
  46369. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46370. __extends(PBRSpecularGlossinessMaterial, _super);
  46371. /**
  46372. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46373. *
  46374. * @param name The material name
  46375. * @param scene The scene the material will be use in.
  46376. */
  46377. function PBRSpecularGlossinessMaterial(name, scene) {
  46378. var _this = _super.call(this, name, scene) || this;
  46379. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46380. return _this;
  46381. }
  46382. /**
  46383. * Return the currrent class name of the material.
  46384. */
  46385. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46386. return "PBRSpecularGlossinessMaterial";
  46387. };
  46388. /**
  46389. * Return the active textures of the material.
  46390. */
  46391. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46392. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46393. if (this.diffuseTexture) {
  46394. activeTextures.push(this.diffuseTexture);
  46395. }
  46396. if (this.specularGlossinessTexture) {
  46397. activeTextures.push(this.specularGlossinessTexture);
  46398. }
  46399. return activeTextures;
  46400. };
  46401. /**
  46402. * Checks to see if a texture is used in the material.
  46403. * @param texture - Base texture to use.
  46404. * @returns - Boolean specifying if a texture is used in the material.
  46405. */
  46406. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46407. if (_super.prototype.hasTexture.call(this, texture)) {
  46408. return true;
  46409. }
  46410. if (this.diffuseTexture === texture) {
  46411. return true;
  46412. }
  46413. if (this.specularGlossinessTexture === texture) {
  46414. return true;
  46415. }
  46416. return false;
  46417. };
  46418. /**
  46419. * Makes a duplicate of the current material.
  46420. * @param name - name to use for the new material.
  46421. */
  46422. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46423. var _this = this;
  46424. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46425. clone.id = name;
  46426. clone.name = name;
  46427. return clone;
  46428. };
  46429. /**
  46430. * Serialize the material to a parsable JSON object.
  46431. */
  46432. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46433. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46434. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46435. return serializationObject;
  46436. };
  46437. /**
  46438. * Parses a JSON object correponding to the serialize function.
  46439. */
  46440. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46441. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46442. };
  46443. __decorate([
  46444. BABYLON.serializeAsColor3("diffuse"),
  46445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46446. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46447. __decorate([
  46448. BABYLON.serializeAsTexture(),
  46449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46450. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46451. __decorate([
  46452. BABYLON.serializeAsColor3("specular"),
  46453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46454. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46455. __decorate([
  46456. BABYLON.serialize(),
  46457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46458. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46459. __decorate([
  46460. BABYLON.serializeAsTexture(),
  46461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46462. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46463. return PBRSpecularGlossinessMaterial;
  46464. }(BABYLON.PBRBaseSimpleMaterial));
  46465. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46466. })(BABYLON || (BABYLON = {}));
  46467. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46468. var BABYLON;
  46469. (function (BABYLON) {
  46470. BABYLON.CameraInputTypes = {};
  46471. var CameraInputsManager = /** @class */ (function () {
  46472. function CameraInputsManager(camera) {
  46473. this.attached = {};
  46474. this.camera = camera;
  46475. this.checkInputs = function () { };
  46476. }
  46477. /**
  46478. * Add an input method to a camera.
  46479. * builtin inputs example: camera.inputs.addGamepad();
  46480. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46481. * @param input camera input method
  46482. */
  46483. CameraInputsManager.prototype.add = function (input) {
  46484. var type = input.getSimpleName();
  46485. if (this.attached[type]) {
  46486. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46487. return;
  46488. }
  46489. this.attached[type] = input;
  46490. input.camera = this.camera;
  46491. //for checkInputs, we are dynamically creating a function
  46492. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46493. if (input.checkInputs) {
  46494. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46495. }
  46496. if (this.attachedElement) {
  46497. input.attachControl(this.attachedElement);
  46498. }
  46499. };
  46500. /**
  46501. * Remove a specific input method from a camera
  46502. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46503. * @param inputToRemove camera input method
  46504. */
  46505. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46506. for (var cam in this.attached) {
  46507. var input = this.attached[cam];
  46508. if (input === inputToRemove) {
  46509. input.detachControl(this.attachedElement);
  46510. input.camera = null;
  46511. delete this.attached[cam];
  46512. this.rebuildInputCheck();
  46513. }
  46514. }
  46515. };
  46516. CameraInputsManager.prototype.removeByType = function (inputType) {
  46517. for (var cam in this.attached) {
  46518. var input = this.attached[cam];
  46519. if (input.getClassName() === inputType) {
  46520. input.detachControl(this.attachedElement);
  46521. input.camera = null;
  46522. delete this.attached[cam];
  46523. this.rebuildInputCheck();
  46524. }
  46525. }
  46526. };
  46527. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46528. var current = this.checkInputs;
  46529. return function () {
  46530. current();
  46531. fn();
  46532. };
  46533. };
  46534. CameraInputsManager.prototype.attachInput = function (input) {
  46535. if (this.attachedElement) {
  46536. input.attachControl(this.attachedElement, this.noPreventDefault);
  46537. }
  46538. };
  46539. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46540. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46541. if (this.attachedElement) {
  46542. return;
  46543. }
  46544. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46545. this.attachedElement = element;
  46546. this.noPreventDefault = noPreventDefault;
  46547. for (var cam in this.attached) {
  46548. this.attached[cam].attachControl(element, noPreventDefault);
  46549. }
  46550. };
  46551. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46552. if (disconnect === void 0) { disconnect = false; }
  46553. if (this.attachedElement !== element) {
  46554. return;
  46555. }
  46556. for (var cam in this.attached) {
  46557. this.attached[cam].detachControl(element);
  46558. if (disconnect) {
  46559. this.attached[cam].camera = null;
  46560. }
  46561. }
  46562. this.attachedElement = null;
  46563. };
  46564. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46565. this.checkInputs = function () { };
  46566. for (var cam in this.attached) {
  46567. var input = this.attached[cam];
  46568. if (input.checkInputs) {
  46569. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46570. }
  46571. }
  46572. };
  46573. /**
  46574. * Remove all attached input methods from a camera
  46575. */
  46576. CameraInputsManager.prototype.clear = function () {
  46577. if (this.attachedElement) {
  46578. this.detachElement(this.attachedElement, true);
  46579. }
  46580. this.attached = {};
  46581. this.attachedElement = null;
  46582. this.checkInputs = function () { };
  46583. };
  46584. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46585. var inputs = {};
  46586. for (var cam in this.attached) {
  46587. var input = this.attached[cam];
  46588. var res = BABYLON.SerializationHelper.Serialize(input);
  46589. inputs[input.getClassName()] = res;
  46590. }
  46591. serializedCamera.inputsmgr = inputs;
  46592. };
  46593. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46594. var parsedInputs = parsedCamera.inputsmgr;
  46595. if (parsedInputs) {
  46596. this.clear();
  46597. for (var n in parsedInputs) {
  46598. var construct = BABYLON.CameraInputTypes[n];
  46599. if (construct) {
  46600. var parsedinput = parsedInputs[n];
  46601. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46602. this.add(input);
  46603. }
  46604. }
  46605. }
  46606. else {
  46607. //2016-03-08 this part is for managing backward compatibility
  46608. for (var n in this.attached) {
  46609. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46610. if (construct) {
  46611. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46612. this.remove(this.attached[n]);
  46613. this.add(input);
  46614. }
  46615. }
  46616. }
  46617. };
  46618. return CameraInputsManager;
  46619. }());
  46620. BABYLON.CameraInputsManager = CameraInputsManager;
  46621. })(BABYLON || (BABYLON = {}));
  46622. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46623. var BABYLON;
  46624. (function (BABYLON) {
  46625. var TargetCamera = /** @class */ (function (_super) {
  46626. __extends(TargetCamera, _super);
  46627. function TargetCamera(name, position, scene) {
  46628. var _this = _super.call(this, name, position, scene) || this;
  46629. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46630. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46631. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46632. _this.speed = 2.0;
  46633. _this.noRotationConstraint = false;
  46634. _this.lockedTarget = null;
  46635. _this._currentTarget = BABYLON.Vector3.Zero();
  46636. _this._viewMatrix = BABYLON.Matrix.Zero();
  46637. _this._camMatrix = BABYLON.Matrix.Zero();
  46638. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46639. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46640. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46641. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46642. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46643. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46644. _this._tempMatrix = BABYLON.Matrix.Zero();
  46645. return _this;
  46646. }
  46647. TargetCamera.prototype.getFrontPosition = function (distance) {
  46648. this.getWorldMatrix();
  46649. var direction = this.getTarget().subtract(this.position);
  46650. direction.normalize();
  46651. direction.scaleInPlace(distance);
  46652. return this.globalPosition.add(direction);
  46653. };
  46654. TargetCamera.prototype._getLockedTargetPosition = function () {
  46655. if (!this.lockedTarget) {
  46656. return null;
  46657. }
  46658. if (this.lockedTarget.absolutePosition) {
  46659. this.lockedTarget.computeWorldMatrix();
  46660. }
  46661. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46662. };
  46663. TargetCamera.prototype.storeState = function () {
  46664. this._storedPosition = this.position.clone();
  46665. this._storedRotation = this.rotation.clone();
  46666. if (this.rotationQuaternion) {
  46667. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46668. }
  46669. return _super.prototype.storeState.call(this);
  46670. };
  46671. /**
  46672. * Restored camera state. You must call storeState() first
  46673. */
  46674. TargetCamera.prototype._restoreStateValues = function () {
  46675. if (!_super.prototype._restoreStateValues.call(this)) {
  46676. return false;
  46677. }
  46678. this.position = this._storedPosition.clone();
  46679. this.rotation = this._storedRotation.clone();
  46680. if (this.rotationQuaternion) {
  46681. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46682. }
  46683. this.cameraDirection.copyFromFloats(0, 0, 0);
  46684. this.cameraRotation.copyFromFloats(0, 0);
  46685. return true;
  46686. };
  46687. // Cache
  46688. TargetCamera.prototype._initCache = function () {
  46689. _super.prototype._initCache.call(this);
  46690. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46691. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46692. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46693. };
  46694. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46695. if (!ignoreParentClass) {
  46696. _super.prototype._updateCache.call(this);
  46697. }
  46698. var lockedTargetPosition = this._getLockedTargetPosition();
  46699. if (!lockedTargetPosition) {
  46700. this._cache.lockedTarget = null;
  46701. }
  46702. else {
  46703. if (!this._cache.lockedTarget) {
  46704. this._cache.lockedTarget = lockedTargetPosition.clone();
  46705. }
  46706. else {
  46707. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46708. }
  46709. }
  46710. this._cache.rotation.copyFrom(this.rotation);
  46711. if (this.rotationQuaternion)
  46712. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46713. };
  46714. // Synchronized
  46715. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46716. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46717. return false;
  46718. }
  46719. var lockedTargetPosition = this._getLockedTargetPosition();
  46720. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46721. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46722. };
  46723. // Methods
  46724. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46725. var engine = this.getEngine();
  46726. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46727. };
  46728. // Target
  46729. TargetCamera.prototype.setTarget = function (target) {
  46730. this.upVector.normalize();
  46731. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46732. this._camMatrix.invert();
  46733. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46734. var vDir = target.subtract(this.position);
  46735. if (vDir.x >= 0.0) {
  46736. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46737. }
  46738. else {
  46739. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46740. }
  46741. this.rotation.z = 0;
  46742. if (isNaN(this.rotation.x)) {
  46743. this.rotation.x = 0;
  46744. }
  46745. if (isNaN(this.rotation.y)) {
  46746. this.rotation.y = 0;
  46747. }
  46748. if (isNaN(this.rotation.z)) {
  46749. this.rotation.z = 0;
  46750. }
  46751. if (this.rotationQuaternion) {
  46752. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46753. }
  46754. };
  46755. /**
  46756. * Return the current target position of the camera. This value is expressed in local space.
  46757. */
  46758. TargetCamera.prototype.getTarget = function () {
  46759. return this._currentTarget;
  46760. };
  46761. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46762. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46763. };
  46764. TargetCamera.prototype._updatePosition = function () {
  46765. if (this.parent) {
  46766. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46767. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46768. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46769. return;
  46770. }
  46771. this.position.addInPlace(this.cameraDirection);
  46772. };
  46773. TargetCamera.prototype._checkInputs = function () {
  46774. var needToMove = this._decideIfNeedsToMove();
  46775. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46776. // Move
  46777. if (needToMove) {
  46778. this._updatePosition();
  46779. }
  46780. // Rotate
  46781. if (needToRotate) {
  46782. this.rotation.x += this.cameraRotation.x;
  46783. this.rotation.y += this.cameraRotation.y;
  46784. //rotate, if quaternion is set and rotation was used
  46785. if (this.rotationQuaternion) {
  46786. var len = this.rotation.lengthSquared();
  46787. if (len) {
  46788. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46789. }
  46790. }
  46791. if (!this.noRotationConstraint) {
  46792. var limit = (Math.PI / 2) * 0.95;
  46793. if (this.rotation.x > limit)
  46794. this.rotation.x = limit;
  46795. if (this.rotation.x < -limit)
  46796. this.rotation.x = -limit;
  46797. }
  46798. }
  46799. // Inertia
  46800. if (needToMove) {
  46801. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46802. this.cameraDirection.x = 0;
  46803. }
  46804. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46805. this.cameraDirection.y = 0;
  46806. }
  46807. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46808. this.cameraDirection.z = 0;
  46809. }
  46810. this.cameraDirection.scaleInPlace(this.inertia);
  46811. }
  46812. if (needToRotate) {
  46813. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46814. this.cameraRotation.x = 0;
  46815. }
  46816. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46817. this.cameraRotation.y = 0;
  46818. }
  46819. this.cameraRotation.scaleInPlace(this.inertia);
  46820. }
  46821. _super.prototype._checkInputs.call(this);
  46822. };
  46823. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46824. if (this.rotationQuaternion) {
  46825. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46826. }
  46827. else {
  46828. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46829. }
  46830. //update the up vector!
  46831. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46832. };
  46833. TargetCamera.prototype._getViewMatrix = function () {
  46834. if (this.lockedTarget) {
  46835. this.setTarget(this._getLockedTargetPosition());
  46836. }
  46837. // Compute
  46838. this._updateCameraRotationMatrix();
  46839. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46840. // Computing target and final matrix
  46841. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46842. if (this.getScene().useRightHandedSystem) {
  46843. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46844. }
  46845. else {
  46846. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46847. }
  46848. return this._viewMatrix;
  46849. };
  46850. /**
  46851. * @override
  46852. * Override Camera.createRigCamera
  46853. */
  46854. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46855. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46856. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46857. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46858. if (!this.rotationQuaternion) {
  46859. this.rotationQuaternion = new BABYLON.Quaternion();
  46860. }
  46861. rigCamera._cameraRigParams = {};
  46862. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46863. }
  46864. return rigCamera;
  46865. }
  46866. return null;
  46867. };
  46868. /**
  46869. * @override
  46870. * Override Camera._updateRigCameras
  46871. */
  46872. TargetCamera.prototype._updateRigCameras = function () {
  46873. var camLeft = this._rigCameras[0];
  46874. var camRight = this._rigCameras[1];
  46875. switch (this.cameraRigMode) {
  46876. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46877. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46878. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46879. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46880. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46881. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46882. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46883. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46884. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46885. camLeft.setTarget(this.getTarget());
  46886. camRight.setTarget(this.getTarget());
  46887. break;
  46888. case BABYLON.Camera.RIG_MODE_VR:
  46889. if (camLeft.rotationQuaternion) {
  46890. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46891. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46892. }
  46893. else {
  46894. camLeft.rotation.copyFrom(this.rotation);
  46895. camRight.rotation.copyFrom(this.rotation);
  46896. }
  46897. camLeft.position.copyFrom(this.position);
  46898. camRight.position.copyFrom(this.position);
  46899. break;
  46900. }
  46901. _super.prototype._updateRigCameras.call(this);
  46902. };
  46903. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46904. if (!this._rigCamTransformMatrix) {
  46905. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46906. }
  46907. var target = this.getTarget();
  46908. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46909. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46910. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46911. };
  46912. TargetCamera.prototype.getClassName = function () {
  46913. return "TargetCamera";
  46914. };
  46915. __decorate([
  46916. BABYLON.serializeAsVector3()
  46917. ], TargetCamera.prototype, "rotation", void 0);
  46918. __decorate([
  46919. BABYLON.serialize()
  46920. ], TargetCamera.prototype, "speed", void 0);
  46921. __decorate([
  46922. BABYLON.serializeAsMeshReference("lockedTargetId")
  46923. ], TargetCamera.prototype, "lockedTarget", void 0);
  46924. return TargetCamera;
  46925. }(BABYLON.Camera));
  46926. BABYLON.TargetCamera = TargetCamera;
  46927. })(BABYLON || (BABYLON = {}));
  46928. //# sourceMappingURL=babylon.targetCamera.js.map
  46929. var BABYLON;
  46930. (function (BABYLON) {
  46931. var FreeCameraMouseInput = /** @class */ (function () {
  46932. function FreeCameraMouseInput(touchEnabled) {
  46933. if (touchEnabled === void 0) { touchEnabled = true; }
  46934. this.touchEnabled = touchEnabled;
  46935. this.buttons = [0, 1, 2];
  46936. this.angularSensibility = 2000.0;
  46937. this.previousPosition = null;
  46938. }
  46939. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46940. var _this = this;
  46941. var engine = this.camera.getEngine();
  46942. if (!this._pointerInput) {
  46943. this._pointerInput = function (p, s) {
  46944. var evt = p.event;
  46945. if (engine.isInVRExclusivePointerMode) {
  46946. return;
  46947. }
  46948. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46949. return;
  46950. }
  46951. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46952. return;
  46953. }
  46954. var srcElement = (evt.srcElement || evt.target);
  46955. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46956. try {
  46957. srcElement.setPointerCapture(evt.pointerId);
  46958. }
  46959. catch (e) {
  46960. //Nothing to do with the error. Execution will continue.
  46961. }
  46962. _this.previousPosition = {
  46963. x: evt.clientX,
  46964. y: evt.clientY
  46965. };
  46966. if (!noPreventDefault) {
  46967. evt.preventDefault();
  46968. element.focus();
  46969. }
  46970. }
  46971. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46972. try {
  46973. srcElement.releasePointerCapture(evt.pointerId);
  46974. }
  46975. catch (e) {
  46976. //Nothing to do with the error.
  46977. }
  46978. _this.previousPosition = null;
  46979. if (!noPreventDefault) {
  46980. evt.preventDefault();
  46981. }
  46982. }
  46983. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46984. if (!_this.previousPosition || engine.isPointerLock) {
  46985. return;
  46986. }
  46987. var offsetX = evt.clientX - _this.previousPosition.x;
  46988. var offsetY = evt.clientY - _this.previousPosition.y;
  46989. if (_this.camera.getScene().useRightHandedSystem) {
  46990. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46991. }
  46992. else {
  46993. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46994. }
  46995. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46996. _this.previousPosition = {
  46997. x: evt.clientX,
  46998. y: evt.clientY
  46999. };
  47000. if (!noPreventDefault) {
  47001. evt.preventDefault();
  47002. }
  47003. }
  47004. };
  47005. }
  47006. this._onMouseMove = function (evt) {
  47007. if (!engine.isPointerLock) {
  47008. return;
  47009. }
  47010. if (engine.isInVRExclusivePointerMode) {
  47011. return;
  47012. }
  47013. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47014. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47015. if (_this.camera.getScene().useRightHandedSystem) {
  47016. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  47017. }
  47018. else {
  47019. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47020. }
  47021. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47022. _this.previousPosition = null;
  47023. if (!noPreventDefault) {
  47024. evt.preventDefault();
  47025. }
  47026. };
  47027. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47028. element.addEventListener("mousemove", this._onMouseMove, false);
  47029. };
  47030. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47031. if (this._observer && element) {
  47032. this.camera.getScene().onPointerObservable.remove(this._observer);
  47033. if (this._onMouseMove) {
  47034. element.removeEventListener("mousemove", this._onMouseMove);
  47035. }
  47036. this._observer = null;
  47037. this._onMouseMove = null;
  47038. this.previousPosition = null;
  47039. }
  47040. };
  47041. FreeCameraMouseInput.prototype.getClassName = function () {
  47042. return "FreeCameraMouseInput";
  47043. };
  47044. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47045. return "mouse";
  47046. };
  47047. __decorate([
  47048. BABYLON.serialize()
  47049. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47050. __decorate([
  47051. BABYLON.serialize()
  47052. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47053. return FreeCameraMouseInput;
  47054. }());
  47055. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47056. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47057. })(BABYLON || (BABYLON = {}));
  47058. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47059. var BABYLON;
  47060. (function (BABYLON) {
  47061. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47062. function FreeCameraKeyboardMoveInput() {
  47063. this._keys = new Array();
  47064. this.keysUp = [38];
  47065. this.keysDown = [40];
  47066. this.keysLeft = [37];
  47067. this.keysRight = [39];
  47068. }
  47069. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47070. var _this = this;
  47071. if (this._onCanvasBlurObserver) {
  47072. return;
  47073. }
  47074. this._scene = this.camera.getScene();
  47075. this._engine = this._scene.getEngine();
  47076. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47077. _this._keys = [];
  47078. });
  47079. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47080. var evt = info.event;
  47081. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47082. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47083. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47084. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47085. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47086. var index = _this._keys.indexOf(evt.keyCode);
  47087. if (index === -1) {
  47088. _this._keys.push(evt.keyCode);
  47089. }
  47090. if (!noPreventDefault) {
  47091. evt.preventDefault();
  47092. }
  47093. }
  47094. }
  47095. else {
  47096. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47097. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47098. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47099. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47100. var index = _this._keys.indexOf(evt.keyCode);
  47101. if (index >= 0) {
  47102. _this._keys.splice(index, 1);
  47103. }
  47104. if (!noPreventDefault) {
  47105. evt.preventDefault();
  47106. }
  47107. }
  47108. }
  47109. });
  47110. };
  47111. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47112. if (this._scene) {
  47113. if (this._onKeyboardObserver) {
  47114. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47115. }
  47116. if (this._onCanvasBlurObserver) {
  47117. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47118. }
  47119. this._onKeyboardObserver = null;
  47120. this._onCanvasBlurObserver = null;
  47121. }
  47122. this._keys = [];
  47123. };
  47124. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47125. if (this._onKeyboardObserver) {
  47126. var camera = this.camera;
  47127. // Keyboard
  47128. for (var index = 0; index < this._keys.length; index++) {
  47129. var keyCode = this._keys[index];
  47130. var speed = camera._computeLocalCameraSpeed();
  47131. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47132. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47133. }
  47134. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47135. camera._localDirection.copyFromFloats(0, 0, speed);
  47136. }
  47137. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47138. camera._localDirection.copyFromFloats(speed, 0, 0);
  47139. }
  47140. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47141. camera._localDirection.copyFromFloats(0, 0, -speed);
  47142. }
  47143. if (camera.getScene().useRightHandedSystem) {
  47144. camera._localDirection.z *= -1;
  47145. }
  47146. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47147. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47148. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47149. }
  47150. }
  47151. };
  47152. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47153. return "FreeCameraKeyboardMoveInput";
  47154. };
  47155. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47156. this._keys = [];
  47157. };
  47158. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47159. return "keyboard";
  47160. };
  47161. __decorate([
  47162. BABYLON.serialize()
  47163. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47164. __decorate([
  47165. BABYLON.serialize()
  47166. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47167. __decorate([
  47168. BABYLON.serialize()
  47169. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47170. __decorate([
  47171. BABYLON.serialize()
  47172. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47173. return FreeCameraKeyboardMoveInput;
  47174. }());
  47175. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47176. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47177. })(BABYLON || (BABYLON = {}));
  47178. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47179. var BABYLON;
  47180. (function (BABYLON) {
  47181. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47182. __extends(FreeCameraInputsManager, _super);
  47183. function FreeCameraInputsManager(camera) {
  47184. return _super.call(this, camera) || this;
  47185. }
  47186. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47187. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47188. return this;
  47189. };
  47190. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47191. if (touchEnabled === void 0) { touchEnabled = true; }
  47192. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47193. return this;
  47194. };
  47195. FreeCameraInputsManager.prototype.addGamepad = function () {
  47196. this.add(new BABYLON.FreeCameraGamepadInput());
  47197. return this;
  47198. };
  47199. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47200. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47201. return this;
  47202. };
  47203. FreeCameraInputsManager.prototype.addTouch = function () {
  47204. this.add(new BABYLON.FreeCameraTouchInput());
  47205. return this;
  47206. };
  47207. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47208. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47209. return this;
  47210. };
  47211. return FreeCameraInputsManager;
  47212. }(BABYLON.CameraInputsManager));
  47213. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47214. })(BABYLON || (BABYLON = {}));
  47215. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47216. var BABYLON;
  47217. (function (BABYLON) {
  47218. var FreeCamera = /** @class */ (function (_super) {
  47219. __extends(FreeCamera, _super);
  47220. function FreeCamera(name, position, scene) {
  47221. var _this = _super.call(this, name, position, scene) || this;
  47222. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47223. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47224. _this.checkCollisions = false;
  47225. _this.applyGravity = false;
  47226. _this._needMoveForGravity = false;
  47227. _this._oldPosition = BABYLON.Vector3.Zero();
  47228. _this._diffPosition = BABYLON.Vector3.Zero();
  47229. _this._newPosition = BABYLON.Vector3.Zero();
  47230. // Collisions
  47231. _this._collisionMask = -1;
  47232. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47233. if (collidedMesh === void 0) { collidedMesh = null; }
  47234. //TODO move this to the collision coordinator!
  47235. if (_this.getScene().workerCollisions)
  47236. newPosition.multiplyInPlace(_this._collider._radius);
  47237. var updatePosition = function (newPos) {
  47238. _this._newPosition.copyFrom(newPos);
  47239. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47240. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47241. _this.position.addInPlace(_this._diffPosition);
  47242. if (_this.onCollide && collidedMesh) {
  47243. _this.onCollide(collidedMesh);
  47244. }
  47245. }
  47246. };
  47247. updatePosition(newPosition);
  47248. };
  47249. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47250. _this.inputs.addKeyboard().addMouse();
  47251. return _this;
  47252. }
  47253. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47254. //-- begin properties for backward compatibility for inputs
  47255. /**
  47256. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47257. * Higher values reduce sensitivity.
  47258. */
  47259. get: function () {
  47260. var mouse = this.inputs.attached["mouse"];
  47261. if (mouse)
  47262. return mouse.angularSensibility;
  47263. return 0;
  47264. },
  47265. /**
  47266. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47267. * Higher values reduce sensitivity.
  47268. */
  47269. set: function (value) {
  47270. var mouse = this.inputs.attached["mouse"];
  47271. if (mouse)
  47272. mouse.angularSensibility = value;
  47273. },
  47274. enumerable: true,
  47275. configurable: true
  47276. });
  47277. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47278. get: function () {
  47279. var keyboard = this.inputs.attached["keyboard"];
  47280. if (keyboard)
  47281. return keyboard.keysUp;
  47282. return [];
  47283. },
  47284. set: function (value) {
  47285. var keyboard = this.inputs.attached["keyboard"];
  47286. if (keyboard)
  47287. keyboard.keysUp = value;
  47288. },
  47289. enumerable: true,
  47290. configurable: true
  47291. });
  47292. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47293. get: function () {
  47294. var keyboard = this.inputs.attached["keyboard"];
  47295. if (keyboard)
  47296. return keyboard.keysDown;
  47297. return [];
  47298. },
  47299. set: function (value) {
  47300. var keyboard = this.inputs.attached["keyboard"];
  47301. if (keyboard)
  47302. keyboard.keysDown = value;
  47303. },
  47304. enumerable: true,
  47305. configurable: true
  47306. });
  47307. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47308. get: function () {
  47309. var keyboard = this.inputs.attached["keyboard"];
  47310. if (keyboard)
  47311. return keyboard.keysLeft;
  47312. return [];
  47313. },
  47314. set: function (value) {
  47315. var keyboard = this.inputs.attached["keyboard"];
  47316. if (keyboard)
  47317. keyboard.keysLeft = value;
  47318. },
  47319. enumerable: true,
  47320. configurable: true
  47321. });
  47322. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47323. get: function () {
  47324. var keyboard = this.inputs.attached["keyboard"];
  47325. if (keyboard)
  47326. return keyboard.keysRight;
  47327. return [];
  47328. },
  47329. set: function (value) {
  47330. var keyboard = this.inputs.attached["keyboard"];
  47331. if (keyboard)
  47332. keyboard.keysRight = value;
  47333. },
  47334. enumerable: true,
  47335. configurable: true
  47336. });
  47337. // Controls
  47338. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47339. this.inputs.attachElement(element, noPreventDefault);
  47340. };
  47341. FreeCamera.prototype.detachControl = function (element) {
  47342. this.inputs.detachElement(element);
  47343. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47344. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47345. };
  47346. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47347. get: function () {
  47348. return this._collisionMask;
  47349. },
  47350. set: function (mask) {
  47351. this._collisionMask = !isNaN(mask) ? mask : -1;
  47352. },
  47353. enumerable: true,
  47354. configurable: true
  47355. });
  47356. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47357. var globalPosition;
  47358. if (this.parent) {
  47359. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47360. }
  47361. else {
  47362. globalPosition = this.position;
  47363. }
  47364. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47365. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47366. if (!this._collider) {
  47367. this._collider = new BABYLON.Collider();
  47368. }
  47369. this._collider._radius = this.ellipsoid;
  47370. this._collider.collisionMask = this._collisionMask;
  47371. //no need for clone, as long as gravity is not on.
  47372. var actualDisplacement = displacement;
  47373. //add gravity to the direction to prevent the dual-collision checking
  47374. if (this.applyGravity) {
  47375. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47376. actualDisplacement = displacement.add(this.getScene().gravity);
  47377. }
  47378. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47379. };
  47380. FreeCamera.prototype._checkInputs = function () {
  47381. if (!this._localDirection) {
  47382. this._localDirection = BABYLON.Vector3.Zero();
  47383. this._transformedDirection = BABYLON.Vector3.Zero();
  47384. }
  47385. this.inputs.checkInputs();
  47386. _super.prototype._checkInputs.call(this);
  47387. };
  47388. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47389. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47390. };
  47391. FreeCamera.prototype._updatePosition = function () {
  47392. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47393. this._collideWithWorld(this.cameraDirection);
  47394. }
  47395. else {
  47396. _super.prototype._updatePosition.call(this);
  47397. }
  47398. };
  47399. FreeCamera.prototype.dispose = function () {
  47400. this.inputs.clear();
  47401. _super.prototype.dispose.call(this);
  47402. };
  47403. FreeCamera.prototype.getClassName = function () {
  47404. return "FreeCamera";
  47405. };
  47406. __decorate([
  47407. BABYLON.serializeAsVector3()
  47408. ], FreeCamera.prototype, "ellipsoid", void 0);
  47409. __decorate([
  47410. BABYLON.serializeAsVector3()
  47411. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47412. __decorate([
  47413. BABYLON.serialize()
  47414. ], FreeCamera.prototype, "checkCollisions", void 0);
  47415. __decorate([
  47416. BABYLON.serialize()
  47417. ], FreeCamera.prototype, "applyGravity", void 0);
  47418. return FreeCamera;
  47419. }(BABYLON.TargetCamera));
  47420. BABYLON.FreeCamera = FreeCamera;
  47421. })(BABYLON || (BABYLON = {}));
  47422. //# sourceMappingURL=babylon.freeCamera.js.map
  47423. var BABYLON;
  47424. (function (BABYLON) {
  47425. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47426. function ArcRotateCameraKeyboardMoveInput() {
  47427. this._keys = new Array();
  47428. this.keysUp = [38];
  47429. this.keysDown = [40];
  47430. this.keysLeft = [37];
  47431. this.keysRight = [39];
  47432. this.keysReset = [220];
  47433. this.panningSensibility = 50.0;
  47434. this.zoomingSensibility = 25.0;
  47435. this.useAltToZoom = true;
  47436. }
  47437. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47438. var _this = this;
  47439. if (this._onCanvasBlurObserver) {
  47440. return;
  47441. }
  47442. this._scene = this.camera.getScene();
  47443. this._engine = this._scene.getEngine();
  47444. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47445. _this._keys = [];
  47446. });
  47447. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47448. var evt = info.event;
  47449. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47450. _this._ctrlPressed = evt.ctrlKey;
  47451. _this._altPressed = evt.altKey;
  47452. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47453. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47454. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47455. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47456. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47457. var index = _this._keys.indexOf(evt.keyCode);
  47458. if (index === -1) {
  47459. _this._keys.push(evt.keyCode);
  47460. }
  47461. if (evt.preventDefault) {
  47462. if (!noPreventDefault) {
  47463. evt.preventDefault();
  47464. }
  47465. }
  47466. }
  47467. }
  47468. else {
  47469. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47470. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47471. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47472. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47473. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47474. var index = _this._keys.indexOf(evt.keyCode);
  47475. if (index >= 0) {
  47476. _this._keys.splice(index, 1);
  47477. }
  47478. if (evt.preventDefault) {
  47479. if (!noPreventDefault) {
  47480. evt.preventDefault();
  47481. }
  47482. }
  47483. }
  47484. }
  47485. });
  47486. };
  47487. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47488. if (this._scene) {
  47489. if (this._onKeyboardObserver) {
  47490. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47491. }
  47492. if (this._onCanvasBlurObserver) {
  47493. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47494. }
  47495. this._onKeyboardObserver = null;
  47496. this._onCanvasBlurObserver = null;
  47497. }
  47498. this._keys = [];
  47499. };
  47500. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47501. if (this._onKeyboardObserver) {
  47502. var camera = this.camera;
  47503. for (var index = 0; index < this._keys.length; index++) {
  47504. var keyCode = this._keys[index];
  47505. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47506. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47507. camera.inertialPanningX -= 1 / this.panningSensibility;
  47508. }
  47509. else {
  47510. camera.inertialAlphaOffset -= 0.01;
  47511. }
  47512. }
  47513. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47514. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47515. camera.inertialPanningY += 1 / this.panningSensibility;
  47516. }
  47517. else if (this._altPressed && this.useAltToZoom) {
  47518. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47519. }
  47520. else {
  47521. camera.inertialBetaOffset -= 0.01;
  47522. }
  47523. }
  47524. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47525. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47526. camera.inertialPanningX += 1 / this.panningSensibility;
  47527. }
  47528. else {
  47529. camera.inertialAlphaOffset += 0.01;
  47530. }
  47531. }
  47532. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47533. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47534. camera.inertialPanningY -= 1 / this.panningSensibility;
  47535. }
  47536. else if (this._altPressed && this.useAltToZoom) {
  47537. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47538. }
  47539. else {
  47540. camera.inertialBetaOffset += 0.01;
  47541. }
  47542. }
  47543. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47544. camera.restoreState();
  47545. }
  47546. }
  47547. }
  47548. };
  47549. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47550. return "ArcRotateCameraKeyboardMoveInput";
  47551. };
  47552. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47553. return "keyboard";
  47554. };
  47555. __decorate([
  47556. BABYLON.serialize()
  47557. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47558. __decorate([
  47559. BABYLON.serialize()
  47560. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47561. __decorate([
  47562. BABYLON.serialize()
  47563. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47564. __decorate([
  47565. BABYLON.serialize()
  47566. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47567. __decorate([
  47568. BABYLON.serialize()
  47569. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47570. __decorate([
  47571. BABYLON.serialize()
  47572. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47573. __decorate([
  47574. BABYLON.serialize()
  47575. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47576. __decorate([
  47577. BABYLON.serialize()
  47578. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47579. return ArcRotateCameraKeyboardMoveInput;
  47580. }());
  47581. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47582. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47583. })(BABYLON || (BABYLON = {}));
  47584. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47585. var BABYLON;
  47586. (function (BABYLON) {
  47587. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47588. function ArcRotateCameraMouseWheelInput() {
  47589. this.wheelPrecision = 3.0;
  47590. /**
  47591. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47592. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47593. */
  47594. this.wheelDeltaPercentage = 0;
  47595. }
  47596. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47597. var _this = this;
  47598. this._wheel = function (p, s) {
  47599. //sanity check - this should be a PointerWheel event.
  47600. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47601. return;
  47602. var event = p.event;
  47603. var delta = 0;
  47604. if (event.wheelDelta) {
  47605. if (_this.wheelDeltaPercentage) {
  47606. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47607. if (event.wheelDelta > 0) {
  47608. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47609. }
  47610. else {
  47611. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47612. }
  47613. }
  47614. else {
  47615. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47616. }
  47617. }
  47618. else if (event.detail) {
  47619. delta = -event.detail / _this.wheelPrecision;
  47620. }
  47621. if (delta)
  47622. _this.camera.inertialRadiusOffset += delta;
  47623. if (event.preventDefault) {
  47624. if (!noPreventDefault) {
  47625. event.preventDefault();
  47626. }
  47627. }
  47628. };
  47629. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47630. };
  47631. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47632. if (this._observer && element) {
  47633. this.camera.getScene().onPointerObservable.remove(this._observer);
  47634. this._observer = null;
  47635. this._wheel = null;
  47636. }
  47637. };
  47638. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47639. return "ArcRotateCameraMouseWheelInput";
  47640. };
  47641. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47642. return "mousewheel";
  47643. };
  47644. __decorate([
  47645. BABYLON.serialize()
  47646. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47647. __decorate([
  47648. BABYLON.serialize()
  47649. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47650. return ArcRotateCameraMouseWheelInput;
  47651. }());
  47652. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47653. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47654. })(BABYLON || (BABYLON = {}));
  47655. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47656. var BABYLON;
  47657. (function (BABYLON) {
  47658. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47659. function ArcRotateCameraPointersInput() {
  47660. this.buttons = [0, 1, 2];
  47661. this.angularSensibilityX = 1000.0;
  47662. this.angularSensibilityY = 1000.0;
  47663. this.pinchPrecision = 12.0;
  47664. /**
  47665. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47666. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47667. */
  47668. this.pinchDeltaPercentage = 0;
  47669. this.panningSensibility = 1000.0;
  47670. this.multiTouchPanning = true;
  47671. this.multiTouchPanAndZoom = true;
  47672. this._isPanClick = false;
  47673. this.pinchInwards = true;
  47674. }
  47675. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47676. var _this = this;
  47677. var engine = this.camera.getEngine();
  47678. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47679. var pointA = null;
  47680. var pointB = null;
  47681. var previousPinchSquaredDistance = 0;
  47682. var initialDistance = 0;
  47683. var twoFingerActivityCount = 0;
  47684. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47685. this._pointerInput = function (p, s) {
  47686. var evt = p.event;
  47687. var isTouch = p.event.pointerType === "touch";
  47688. if (engine.isInVRExclusivePointerMode) {
  47689. return;
  47690. }
  47691. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47692. return;
  47693. }
  47694. var srcElement = (evt.srcElement || evt.target);
  47695. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47696. try {
  47697. srcElement.setPointerCapture(evt.pointerId);
  47698. }
  47699. catch (e) {
  47700. //Nothing to do with the error. Execution will continue.
  47701. }
  47702. // Manage panning with pan button click
  47703. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47704. // manage pointers
  47705. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47706. if (pointA === null) {
  47707. pointA = cacheSoloPointer;
  47708. }
  47709. else if (pointB === null) {
  47710. pointB = cacheSoloPointer;
  47711. }
  47712. if (!noPreventDefault) {
  47713. evt.preventDefault();
  47714. element.focus();
  47715. }
  47716. }
  47717. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47718. _this.camera.restoreState();
  47719. }
  47720. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47721. try {
  47722. srcElement.releasePointerCapture(evt.pointerId);
  47723. }
  47724. catch (e) {
  47725. //Nothing to do with the error.
  47726. }
  47727. cacheSoloPointer = null;
  47728. previousPinchSquaredDistance = 0;
  47729. previousMultiTouchPanPosition.isPaning = false;
  47730. previousMultiTouchPanPosition.isPinching = false;
  47731. twoFingerActivityCount = 0;
  47732. initialDistance = 0;
  47733. if (!isTouch) {
  47734. pointB = null; // Mouse and pen are mono pointer
  47735. }
  47736. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47737. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47738. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47739. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47740. if (engine._badOS) {
  47741. pointA = pointB = null;
  47742. }
  47743. else {
  47744. //only remove the impacted pointer in case of multitouch allowing on most
  47745. //platforms switching from rotate to zoom and pan seamlessly.
  47746. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47747. pointA = pointB;
  47748. pointB = null;
  47749. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47750. }
  47751. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47752. pointB = null;
  47753. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47754. }
  47755. else {
  47756. pointA = pointB = null;
  47757. }
  47758. }
  47759. if (!noPreventDefault) {
  47760. evt.preventDefault();
  47761. }
  47762. }
  47763. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47764. if (!noPreventDefault) {
  47765. evt.preventDefault();
  47766. }
  47767. // One button down
  47768. if (pointA && pointB === null && cacheSoloPointer) {
  47769. if (_this.panningSensibility !== 0 &&
  47770. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47771. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47772. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47773. }
  47774. else {
  47775. var offsetX = evt.clientX - cacheSoloPointer.x;
  47776. var offsetY = evt.clientY - cacheSoloPointer.y;
  47777. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47778. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47779. }
  47780. cacheSoloPointer.x = evt.clientX;
  47781. cacheSoloPointer.y = evt.clientY;
  47782. }
  47783. // Two buttons down: pinch/pan
  47784. else if (pointA && pointB) {
  47785. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47786. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47787. ed.x = evt.clientX;
  47788. ed.y = evt.clientY;
  47789. var direction = _this.pinchInwards ? 1 : -1;
  47790. var distX = pointA.x - pointB.x;
  47791. var distY = pointA.y - pointB.y;
  47792. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47793. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47794. if (previousPinchSquaredDistance === 0) {
  47795. initialDistance = pinchDistance;
  47796. previousPinchSquaredDistance = pinchSquaredDistance;
  47797. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47798. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47799. return;
  47800. }
  47801. if (_this.multiTouchPanAndZoom) {
  47802. if (_this.pinchDeltaPercentage) {
  47803. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47804. }
  47805. else {
  47806. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47807. (_this.pinchPrecision *
  47808. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47809. direction);
  47810. }
  47811. if (_this.panningSensibility !== 0) {
  47812. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47813. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47814. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47815. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47816. previousMultiTouchPanPosition.x = pointersCenterX;
  47817. previousMultiTouchPanPosition.y = pointersCenterY;
  47818. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47819. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47820. }
  47821. }
  47822. else {
  47823. twoFingerActivityCount++;
  47824. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47825. if (_this.pinchDeltaPercentage) {
  47826. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47827. }
  47828. else {
  47829. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47830. (_this.pinchPrecision *
  47831. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47832. direction);
  47833. }
  47834. previousMultiTouchPanPosition.isPaning = false;
  47835. previousMultiTouchPanPosition.isPinching = true;
  47836. }
  47837. else {
  47838. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47839. if (!previousMultiTouchPanPosition.isPaning) {
  47840. previousMultiTouchPanPosition.isPaning = true;
  47841. previousMultiTouchPanPosition.isPinching = false;
  47842. previousMultiTouchPanPosition.x = ed.x;
  47843. previousMultiTouchPanPosition.y = ed.y;
  47844. return;
  47845. }
  47846. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47847. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47848. }
  47849. }
  47850. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47851. previousMultiTouchPanPosition.x = ed.x;
  47852. previousMultiTouchPanPosition.y = ed.y;
  47853. }
  47854. }
  47855. previousPinchSquaredDistance = pinchSquaredDistance;
  47856. }
  47857. }
  47858. };
  47859. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47860. this._onContextMenu = function (evt) {
  47861. evt.preventDefault();
  47862. };
  47863. if (!this.camera._useCtrlForPanning) {
  47864. element.addEventListener("contextmenu", this._onContextMenu, false);
  47865. }
  47866. this._onLostFocus = function () {
  47867. //this._keys = [];
  47868. pointA = pointB = null;
  47869. previousPinchSquaredDistance = 0;
  47870. previousMultiTouchPanPosition.isPaning = false;
  47871. previousMultiTouchPanPosition.isPinching = false;
  47872. twoFingerActivityCount = 0;
  47873. cacheSoloPointer = null;
  47874. initialDistance = 0;
  47875. };
  47876. this._onMouseMove = function (evt) {
  47877. if (!engine.isPointerLock) {
  47878. return;
  47879. }
  47880. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47881. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47882. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47883. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47884. if (!noPreventDefault) {
  47885. evt.preventDefault();
  47886. }
  47887. };
  47888. this._onGestureStart = function (e) {
  47889. if (window.MSGesture === undefined) {
  47890. return;
  47891. }
  47892. if (!_this._MSGestureHandler) {
  47893. _this._MSGestureHandler = new MSGesture();
  47894. _this._MSGestureHandler.target = element;
  47895. }
  47896. _this._MSGestureHandler.addPointer(e.pointerId);
  47897. };
  47898. this._onGesture = function (e) {
  47899. _this.camera.radius *= e.scale;
  47900. if (e.preventDefault) {
  47901. if (!noPreventDefault) {
  47902. e.stopPropagation();
  47903. e.preventDefault();
  47904. }
  47905. }
  47906. };
  47907. element.addEventListener("mousemove", this._onMouseMove, false);
  47908. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47909. element.addEventListener("MSGestureChange", this._onGesture, false);
  47910. BABYLON.Tools.RegisterTopRootEvents([
  47911. { name: "blur", handler: this._onLostFocus }
  47912. ]);
  47913. };
  47914. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47915. if (this._onLostFocus) {
  47916. BABYLON.Tools.UnregisterTopRootEvents([
  47917. { name: "blur", handler: this._onLostFocus }
  47918. ]);
  47919. }
  47920. if (element && this._observer) {
  47921. this.camera.getScene().onPointerObservable.remove(this._observer);
  47922. this._observer = null;
  47923. if (this._onContextMenu) {
  47924. element.removeEventListener("contextmenu", this._onContextMenu);
  47925. }
  47926. if (this._onMouseMove) {
  47927. element.removeEventListener("mousemove", this._onMouseMove);
  47928. }
  47929. if (this._onGestureStart) {
  47930. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47931. }
  47932. if (this._onGesture) {
  47933. element.removeEventListener("MSGestureChange", this._onGesture);
  47934. }
  47935. this._isPanClick = false;
  47936. this.pinchInwards = true;
  47937. this._onMouseMove = null;
  47938. this._onGestureStart = null;
  47939. this._onGesture = null;
  47940. this._MSGestureHandler = null;
  47941. this._onLostFocus = null;
  47942. this._onContextMenu = null;
  47943. }
  47944. };
  47945. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47946. return "ArcRotateCameraPointersInput";
  47947. };
  47948. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47949. return "pointers";
  47950. };
  47951. __decorate([
  47952. BABYLON.serialize()
  47953. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47954. __decorate([
  47955. BABYLON.serialize()
  47956. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47957. __decorate([
  47958. BABYLON.serialize()
  47959. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47960. __decorate([
  47961. BABYLON.serialize()
  47962. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47963. __decorate([
  47964. BABYLON.serialize()
  47965. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47966. __decorate([
  47967. BABYLON.serialize()
  47968. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47969. __decorate([
  47970. BABYLON.serialize()
  47971. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47972. __decorate([
  47973. BABYLON.serialize()
  47974. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47975. return ArcRotateCameraPointersInput;
  47976. }());
  47977. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47978. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47979. })(BABYLON || (BABYLON = {}));
  47980. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47981. var BABYLON;
  47982. (function (BABYLON) {
  47983. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47984. __extends(ArcRotateCameraInputsManager, _super);
  47985. function ArcRotateCameraInputsManager(camera) {
  47986. return _super.call(this, camera) || this;
  47987. }
  47988. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47989. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47990. return this;
  47991. };
  47992. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47993. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47994. return this;
  47995. };
  47996. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47997. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47998. return this;
  47999. };
  48000. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48001. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48002. return this;
  48003. };
  48004. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48005. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48006. return this;
  48007. };
  48008. return ArcRotateCameraInputsManager;
  48009. }(BABYLON.CameraInputsManager));
  48010. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48011. })(BABYLON || (BABYLON = {}));
  48012. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48013. var BABYLON;
  48014. (function (BABYLON) {
  48015. var ArcRotateCamera = /** @class */ (function (_super) {
  48016. __extends(ArcRotateCamera, _super);
  48017. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  48018. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48019. _this.inertialAlphaOffset = 0;
  48020. _this.inertialBetaOffset = 0;
  48021. _this.inertialRadiusOffset = 0;
  48022. _this.lowerAlphaLimit = null;
  48023. _this.upperAlphaLimit = null;
  48024. _this.lowerBetaLimit = 0.01;
  48025. _this.upperBetaLimit = Math.PI;
  48026. _this.lowerRadiusLimit = null;
  48027. _this.upperRadiusLimit = null;
  48028. _this.inertialPanningX = 0;
  48029. _this.inertialPanningY = 0;
  48030. _this.pinchToPanMaxDistance = 20;
  48031. _this.panningDistanceLimit = null;
  48032. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48033. _this.panningInertia = 0.9;
  48034. //-- end properties for backward compatibility for inputs
  48035. _this.zoomOnFactor = 1;
  48036. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48037. _this.allowUpsideDown = true;
  48038. _this._viewMatrix = new BABYLON.Matrix();
  48039. // Panning
  48040. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48041. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48042. _this.checkCollisions = false;
  48043. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48044. _this._previousPosition = BABYLON.Vector3.Zero();
  48045. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48046. _this._newPosition = BABYLON.Vector3.Zero();
  48047. _this._computationVector = BABYLON.Vector3.Zero();
  48048. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48049. if (collidedMesh === void 0) { collidedMesh = null; }
  48050. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48051. newPosition.multiplyInPlace(_this._collider._radius);
  48052. }
  48053. if (!collidedMesh) {
  48054. _this._previousPosition.copyFrom(_this.position);
  48055. }
  48056. else {
  48057. _this.setPosition(newPosition);
  48058. if (_this.onCollide) {
  48059. _this.onCollide(collidedMesh);
  48060. }
  48061. }
  48062. // Recompute because of constraints
  48063. var cosa = Math.cos(_this.alpha);
  48064. var sina = Math.sin(_this.alpha);
  48065. var cosb = Math.cos(_this.beta);
  48066. var sinb = Math.sin(_this.beta);
  48067. if (sinb === 0) {
  48068. sinb = 0.0001;
  48069. }
  48070. var target = _this._getTargetPosition();
  48071. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48072. target.addToRef(_this._computationVector, _this._newPosition);
  48073. _this.position.copyFrom(_this._newPosition);
  48074. var up = _this.upVector;
  48075. if (_this.allowUpsideDown && _this.beta < 0) {
  48076. up = up.clone();
  48077. up = up.negate();
  48078. }
  48079. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48080. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48081. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48082. _this._collisionTriggered = false;
  48083. };
  48084. _this._target = BABYLON.Vector3.Zero();
  48085. if (target) {
  48086. _this.setTarget(target);
  48087. }
  48088. _this.alpha = alpha;
  48089. _this.beta = beta;
  48090. _this.radius = radius;
  48091. _this.getViewMatrix();
  48092. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48093. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48094. return _this;
  48095. }
  48096. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48097. get: function () {
  48098. return this._target;
  48099. },
  48100. set: function (value) {
  48101. this.setTarget(value);
  48102. },
  48103. enumerable: true,
  48104. configurable: true
  48105. });
  48106. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48107. //-- begin properties for backward compatibility for inputs
  48108. get: function () {
  48109. var pointers = this.inputs.attached["pointers"];
  48110. if (pointers)
  48111. return pointers.angularSensibilityX;
  48112. return 0;
  48113. },
  48114. set: function (value) {
  48115. var pointers = this.inputs.attached["pointers"];
  48116. if (pointers) {
  48117. pointers.angularSensibilityX = value;
  48118. }
  48119. },
  48120. enumerable: true,
  48121. configurable: true
  48122. });
  48123. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48124. get: function () {
  48125. var pointers = this.inputs.attached["pointers"];
  48126. if (pointers)
  48127. return pointers.angularSensibilityY;
  48128. return 0;
  48129. },
  48130. set: function (value) {
  48131. var pointers = this.inputs.attached["pointers"];
  48132. if (pointers) {
  48133. pointers.angularSensibilityY = value;
  48134. }
  48135. },
  48136. enumerable: true,
  48137. configurable: true
  48138. });
  48139. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48140. get: function () {
  48141. var pointers = this.inputs.attached["pointers"];
  48142. if (pointers)
  48143. return pointers.pinchPrecision;
  48144. return 0;
  48145. },
  48146. set: function (value) {
  48147. var pointers = this.inputs.attached["pointers"];
  48148. if (pointers) {
  48149. pointers.pinchPrecision = value;
  48150. }
  48151. },
  48152. enumerable: true,
  48153. configurable: true
  48154. });
  48155. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48156. get: function () {
  48157. var pointers = this.inputs.attached["pointers"];
  48158. if (pointers)
  48159. return pointers.pinchDeltaPercentage;
  48160. return 0;
  48161. },
  48162. set: function (value) {
  48163. var pointers = this.inputs.attached["pointers"];
  48164. if (pointers) {
  48165. pointers.pinchDeltaPercentage = value;
  48166. }
  48167. },
  48168. enumerable: true,
  48169. configurable: true
  48170. });
  48171. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48172. get: function () {
  48173. var pointers = this.inputs.attached["pointers"];
  48174. if (pointers)
  48175. return pointers.panningSensibility;
  48176. return 0;
  48177. },
  48178. set: function (value) {
  48179. var pointers = this.inputs.attached["pointers"];
  48180. if (pointers) {
  48181. pointers.panningSensibility = value;
  48182. }
  48183. },
  48184. enumerable: true,
  48185. configurable: true
  48186. });
  48187. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48188. get: function () {
  48189. var keyboard = this.inputs.attached["keyboard"];
  48190. if (keyboard)
  48191. return keyboard.keysUp;
  48192. return [];
  48193. },
  48194. set: function (value) {
  48195. var keyboard = this.inputs.attached["keyboard"];
  48196. if (keyboard)
  48197. keyboard.keysUp = value;
  48198. },
  48199. enumerable: true,
  48200. configurable: true
  48201. });
  48202. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48203. get: function () {
  48204. var keyboard = this.inputs.attached["keyboard"];
  48205. if (keyboard)
  48206. return keyboard.keysDown;
  48207. return [];
  48208. },
  48209. set: function (value) {
  48210. var keyboard = this.inputs.attached["keyboard"];
  48211. if (keyboard)
  48212. keyboard.keysDown = value;
  48213. },
  48214. enumerable: true,
  48215. configurable: true
  48216. });
  48217. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48218. get: function () {
  48219. var keyboard = this.inputs.attached["keyboard"];
  48220. if (keyboard)
  48221. return keyboard.keysLeft;
  48222. return [];
  48223. },
  48224. set: function (value) {
  48225. var keyboard = this.inputs.attached["keyboard"];
  48226. if (keyboard)
  48227. keyboard.keysLeft = value;
  48228. },
  48229. enumerable: true,
  48230. configurable: true
  48231. });
  48232. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48233. get: function () {
  48234. var keyboard = this.inputs.attached["keyboard"];
  48235. if (keyboard)
  48236. return keyboard.keysRight;
  48237. return [];
  48238. },
  48239. set: function (value) {
  48240. var keyboard = this.inputs.attached["keyboard"];
  48241. if (keyboard)
  48242. keyboard.keysRight = value;
  48243. },
  48244. enumerable: true,
  48245. configurable: true
  48246. });
  48247. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48248. get: function () {
  48249. var mousewheel = this.inputs.attached["mousewheel"];
  48250. if (mousewheel)
  48251. return mousewheel.wheelPrecision;
  48252. return 0;
  48253. },
  48254. set: function (value) {
  48255. var mousewheel = this.inputs.attached["mousewheel"];
  48256. if (mousewheel)
  48257. mousewheel.wheelPrecision = value;
  48258. },
  48259. enumerable: true,
  48260. configurable: true
  48261. });
  48262. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48263. get: function () {
  48264. var mousewheel = this.inputs.attached["mousewheel"];
  48265. if (mousewheel)
  48266. return mousewheel.wheelDeltaPercentage;
  48267. return 0;
  48268. },
  48269. set: function (value) {
  48270. var mousewheel = this.inputs.attached["mousewheel"];
  48271. if (mousewheel)
  48272. mousewheel.wheelDeltaPercentage = value;
  48273. },
  48274. enumerable: true,
  48275. configurable: true
  48276. });
  48277. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48278. get: function () {
  48279. return this._bouncingBehavior;
  48280. },
  48281. enumerable: true,
  48282. configurable: true
  48283. });
  48284. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48285. get: function () {
  48286. return this._bouncingBehavior != null;
  48287. },
  48288. set: function (value) {
  48289. if (value === this.useBouncingBehavior) {
  48290. return;
  48291. }
  48292. if (value) {
  48293. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48294. this.addBehavior(this._bouncingBehavior);
  48295. }
  48296. else if (this._bouncingBehavior) {
  48297. this.removeBehavior(this._bouncingBehavior);
  48298. this._bouncingBehavior = null;
  48299. }
  48300. },
  48301. enumerable: true,
  48302. configurable: true
  48303. });
  48304. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48305. get: function () {
  48306. return this._framingBehavior;
  48307. },
  48308. enumerable: true,
  48309. configurable: true
  48310. });
  48311. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48312. get: function () {
  48313. return this._framingBehavior != null;
  48314. },
  48315. set: function (value) {
  48316. if (value === this.useFramingBehavior) {
  48317. return;
  48318. }
  48319. if (value) {
  48320. this._framingBehavior = new BABYLON.FramingBehavior();
  48321. this.addBehavior(this._framingBehavior);
  48322. }
  48323. else if (this._framingBehavior) {
  48324. this.removeBehavior(this._framingBehavior);
  48325. this._framingBehavior = null;
  48326. }
  48327. },
  48328. enumerable: true,
  48329. configurable: true
  48330. });
  48331. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48332. get: function () {
  48333. return this._autoRotationBehavior;
  48334. },
  48335. enumerable: true,
  48336. configurable: true
  48337. });
  48338. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48339. get: function () {
  48340. return this._autoRotationBehavior != null;
  48341. },
  48342. set: function (value) {
  48343. if (value === this.useAutoRotationBehavior) {
  48344. return;
  48345. }
  48346. if (value) {
  48347. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48348. this.addBehavior(this._autoRotationBehavior);
  48349. }
  48350. else if (this._autoRotationBehavior) {
  48351. this.removeBehavior(this._autoRotationBehavior);
  48352. this._autoRotationBehavior = null;
  48353. }
  48354. },
  48355. enumerable: true,
  48356. configurable: true
  48357. });
  48358. // Cache
  48359. ArcRotateCamera.prototype._initCache = function () {
  48360. _super.prototype._initCache.call(this);
  48361. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48362. this._cache.alpha = undefined;
  48363. this._cache.beta = undefined;
  48364. this._cache.radius = undefined;
  48365. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48366. };
  48367. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48368. if (!ignoreParentClass) {
  48369. _super.prototype._updateCache.call(this);
  48370. }
  48371. this._cache._target.copyFrom(this._getTargetPosition());
  48372. this._cache.alpha = this.alpha;
  48373. this._cache.beta = this.beta;
  48374. this._cache.radius = this.radius;
  48375. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48376. };
  48377. ArcRotateCamera.prototype._getTargetPosition = function () {
  48378. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48379. var pos = this._targetHost.getAbsolutePosition();
  48380. if (this._targetBoundingCenter) {
  48381. pos.addToRef(this._targetBoundingCenter, this._target);
  48382. }
  48383. else {
  48384. this._target.copyFrom(pos);
  48385. }
  48386. }
  48387. var lockedTargetPosition = this._getLockedTargetPosition();
  48388. if (lockedTargetPosition) {
  48389. return lockedTargetPosition;
  48390. }
  48391. return this._target;
  48392. };
  48393. ArcRotateCamera.prototype.storeState = function () {
  48394. this._storedAlpha = this.alpha;
  48395. this._storedBeta = this.beta;
  48396. this._storedRadius = this.radius;
  48397. this._storedTarget = this._getTargetPosition().clone();
  48398. return _super.prototype.storeState.call(this);
  48399. };
  48400. /**
  48401. * Restored camera state. You must call storeState() first
  48402. */
  48403. ArcRotateCamera.prototype._restoreStateValues = function () {
  48404. if (!_super.prototype._restoreStateValues.call(this)) {
  48405. return false;
  48406. }
  48407. this.alpha = this._storedAlpha;
  48408. this.beta = this._storedBeta;
  48409. this.radius = this._storedRadius;
  48410. this.setTarget(this._storedTarget.clone());
  48411. this.inertialAlphaOffset = 0;
  48412. this.inertialBetaOffset = 0;
  48413. this.inertialRadiusOffset = 0;
  48414. this.inertialPanningX = 0;
  48415. this.inertialPanningY = 0;
  48416. return true;
  48417. };
  48418. // Synchronized
  48419. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48420. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48421. return false;
  48422. return this._cache._target.equals(this._getTargetPosition())
  48423. && this._cache.alpha === this.alpha
  48424. && this._cache.beta === this.beta
  48425. && this._cache.radius === this.radius
  48426. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48427. };
  48428. // Methods
  48429. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48430. var _this = this;
  48431. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48432. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48433. this._useCtrlForPanning = useCtrlForPanning;
  48434. this._panningMouseButton = panningMouseButton;
  48435. this.inputs.attachElement(element, noPreventDefault);
  48436. this._reset = function () {
  48437. _this.inertialAlphaOffset = 0;
  48438. _this.inertialBetaOffset = 0;
  48439. _this.inertialRadiusOffset = 0;
  48440. _this.inertialPanningX = 0;
  48441. _this.inertialPanningY = 0;
  48442. };
  48443. };
  48444. ArcRotateCamera.prototype.detachControl = function (element) {
  48445. this.inputs.detachElement(element);
  48446. if (this._reset) {
  48447. this._reset();
  48448. }
  48449. };
  48450. ArcRotateCamera.prototype._checkInputs = function () {
  48451. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48452. if (this._collisionTriggered) {
  48453. return;
  48454. }
  48455. this.inputs.checkInputs();
  48456. // Inertia
  48457. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48458. if (this.getScene().useRightHandedSystem) {
  48459. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48460. }
  48461. else {
  48462. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48463. }
  48464. this.beta += this.inertialBetaOffset;
  48465. this.radius -= this.inertialRadiusOffset;
  48466. this.inertialAlphaOffset *= this.inertia;
  48467. this.inertialBetaOffset *= this.inertia;
  48468. this.inertialRadiusOffset *= this.inertia;
  48469. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48470. this.inertialAlphaOffset = 0;
  48471. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48472. this.inertialBetaOffset = 0;
  48473. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48474. this.inertialRadiusOffset = 0;
  48475. }
  48476. // Panning inertia
  48477. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48478. if (!this._localDirection) {
  48479. this._localDirection = BABYLON.Vector3.Zero();
  48480. this._transformedDirection = BABYLON.Vector3.Zero();
  48481. }
  48482. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48483. this._localDirection.multiplyInPlace(this.panningAxis);
  48484. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48485. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48486. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48487. if (!this.panningAxis.y) {
  48488. this._transformedDirection.y = 0;
  48489. }
  48490. if (!this._targetHost) {
  48491. if (this.panningDistanceLimit) {
  48492. this._transformedDirection.addInPlace(this._target);
  48493. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48494. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48495. this._target.copyFrom(this._transformedDirection);
  48496. }
  48497. }
  48498. else {
  48499. this._target.addInPlace(this._transformedDirection);
  48500. }
  48501. }
  48502. this.inertialPanningX *= this.panningInertia;
  48503. this.inertialPanningY *= this.panningInertia;
  48504. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48505. this.inertialPanningX = 0;
  48506. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48507. this.inertialPanningY = 0;
  48508. }
  48509. // Limits
  48510. this._checkLimits();
  48511. _super.prototype._checkInputs.call(this);
  48512. };
  48513. ArcRotateCamera.prototype._checkLimits = function () {
  48514. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48515. if (this.allowUpsideDown && this.beta > Math.PI) {
  48516. this.beta = this.beta - (2 * Math.PI);
  48517. }
  48518. }
  48519. else {
  48520. if (this.beta < this.lowerBetaLimit) {
  48521. this.beta = this.lowerBetaLimit;
  48522. }
  48523. }
  48524. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48525. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48526. this.beta = this.beta + (2 * Math.PI);
  48527. }
  48528. }
  48529. else {
  48530. if (this.beta > this.upperBetaLimit) {
  48531. this.beta = this.upperBetaLimit;
  48532. }
  48533. }
  48534. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48535. this.alpha = this.lowerAlphaLimit;
  48536. }
  48537. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48538. this.alpha = this.upperAlphaLimit;
  48539. }
  48540. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48541. this.radius = this.lowerRadiusLimit;
  48542. }
  48543. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48544. this.radius = this.upperRadiusLimit;
  48545. }
  48546. };
  48547. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48548. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48549. this.radius = this._computationVector.length();
  48550. if (this.radius === 0) {
  48551. this.radius = 0.0001; // Just to avoid division by zero
  48552. }
  48553. // Alpha
  48554. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48555. if (this._computationVector.z < 0) {
  48556. this.alpha = 2 * Math.PI - this.alpha;
  48557. }
  48558. // Beta
  48559. this.beta = Math.acos(this._computationVector.y / this.radius);
  48560. this._checkLimits();
  48561. };
  48562. ArcRotateCamera.prototype.setPosition = function (position) {
  48563. if (this.position.equals(position)) {
  48564. return;
  48565. }
  48566. this.position.copyFrom(position);
  48567. this.rebuildAnglesAndRadius();
  48568. };
  48569. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48570. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48571. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48572. if (target.getBoundingInfo) {
  48573. if (toBoundingCenter) {
  48574. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48575. }
  48576. else {
  48577. this._targetBoundingCenter = null;
  48578. }
  48579. this._targetHost = target;
  48580. this._target = this._getTargetPosition();
  48581. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48582. }
  48583. else {
  48584. var newTarget = target;
  48585. var currentTarget = this._getTargetPosition();
  48586. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48587. return;
  48588. }
  48589. this._targetHost = null;
  48590. this._target = newTarget;
  48591. this._targetBoundingCenter = null;
  48592. this.onMeshTargetChangedObservable.notifyObservers(null);
  48593. }
  48594. this.rebuildAnglesAndRadius();
  48595. };
  48596. ArcRotateCamera.prototype._getViewMatrix = function () {
  48597. // Compute
  48598. var cosa = Math.cos(this.alpha);
  48599. var sina = Math.sin(this.alpha);
  48600. var cosb = Math.cos(this.beta);
  48601. var sinb = Math.sin(this.beta);
  48602. if (sinb === 0) {
  48603. sinb = 0.0001;
  48604. }
  48605. var target = this._getTargetPosition();
  48606. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48607. target.addToRef(this._computationVector, this._newPosition);
  48608. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48609. if (!this._collider) {
  48610. this._collider = new BABYLON.Collider();
  48611. }
  48612. this._collider._radius = this.collisionRadius;
  48613. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48614. this._collisionTriggered = true;
  48615. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48616. }
  48617. else {
  48618. this.position.copyFrom(this._newPosition);
  48619. var up = this.upVector;
  48620. if (this.allowUpsideDown && sinb < 0) {
  48621. up = up.clone();
  48622. up = up.negate();
  48623. }
  48624. if (this.getScene().useRightHandedSystem) {
  48625. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48626. }
  48627. else {
  48628. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48629. }
  48630. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48631. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48632. }
  48633. this._currentTarget = target;
  48634. return this._viewMatrix;
  48635. };
  48636. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48637. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48638. meshes = meshes || this.getScene().meshes;
  48639. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48640. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48641. this.radius = distance * this.zoomOnFactor;
  48642. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48643. };
  48644. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48645. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48646. var meshesOrMinMaxVector;
  48647. var distance;
  48648. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48649. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48650. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48651. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48652. }
  48653. else { //minMaxVector and distance
  48654. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48655. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48656. distance = minMaxVectorAndDistance.distance;
  48657. }
  48658. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48659. if (!doNotUpdateMaxZ) {
  48660. this.maxZ = distance * 2;
  48661. }
  48662. };
  48663. /**
  48664. * @override
  48665. * Override Camera.createRigCamera
  48666. */
  48667. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48668. var alphaShift = 0;
  48669. switch (this.cameraRigMode) {
  48670. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48671. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48672. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48673. case BABYLON.Camera.RIG_MODE_VR:
  48674. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48675. break;
  48676. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48677. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48678. break;
  48679. }
  48680. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48681. rigCam._cameraRigParams = {};
  48682. return rigCam;
  48683. };
  48684. /**
  48685. * @override
  48686. * Override Camera._updateRigCameras
  48687. */
  48688. ArcRotateCamera.prototype._updateRigCameras = function () {
  48689. var camLeft = this._rigCameras[0];
  48690. var camRight = this._rigCameras[1];
  48691. camLeft.beta = camRight.beta = this.beta;
  48692. camLeft.radius = camRight.radius = this.radius;
  48693. switch (this.cameraRigMode) {
  48694. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48695. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48696. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48697. case BABYLON.Camera.RIG_MODE_VR:
  48698. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48699. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48700. break;
  48701. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48702. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48703. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48704. break;
  48705. }
  48706. _super.prototype._updateRigCameras.call(this);
  48707. };
  48708. ArcRotateCamera.prototype.dispose = function () {
  48709. this.inputs.clear();
  48710. _super.prototype.dispose.call(this);
  48711. };
  48712. ArcRotateCamera.prototype.getClassName = function () {
  48713. return "ArcRotateCamera";
  48714. };
  48715. __decorate([
  48716. BABYLON.serialize()
  48717. ], ArcRotateCamera.prototype, "alpha", void 0);
  48718. __decorate([
  48719. BABYLON.serialize()
  48720. ], ArcRotateCamera.prototype, "beta", void 0);
  48721. __decorate([
  48722. BABYLON.serialize()
  48723. ], ArcRotateCamera.prototype, "radius", void 0);
  48724. __decorate([
  48725. BABYLON.serializeAsVector3("target")
  48726. ], ArcRotateCamera.prototype, "_target", void 0);
  48727. __decorate([
  48728. BABYLON.serialize()
  48729. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48730. __decorate([
  48731. BABYLON.serialize()
  48732. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48733. __decorate([
  48734. BABYLON.serialize()
  48735. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48736. __decorate([
  48737. BABYLON.serialize()
  48738. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48739. __decorate([
  48740. BABYLON.serialize()
  48741. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48742. __decorate([
  48743. BABYLON.serialize()
  48744. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48745. __decorate([
  48746. BABYLON.serialize()
  48747. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48748. __decorate([
  48749. BABYLON.serialize()
  48750. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48751. __decorate([
  48752. BABYLON.serialize()
  48753. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48754. __decorate([
  48755. BABYLON.serialize()
  48756. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48757. __decorate([
  48758. BABYLON.serialize()
  48759. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48760. __decorate([
  48761. BABYLON.serialize()
  48762. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48763. __decorate([
  48764. BABYLON.serialize()
  48765. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48766. __decorate([
  48767. BABYLON.serializeAsVector3()
  48768. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48769. __decorate([
  48770. BABYLON.serialize()
  48771. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48772. __decorate([
  48773. BABYLON.serialize()
  48774. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48775. __decorate([
  48776. BABYLON.serialize()
  48777. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48778. return ArcRotateCamera;
  48779. }(BABYLON.TargetCamera));
  48780. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48781. })(BABYLON || (BABYLON = {}));
  48782. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48783. var BABYLON;
  48784. (function (BABYLON) {
  48785. /**
  48786. * The HemisphericLight simulates the ambient environment light,
  48787. * so the passed direction is the light reflection direction, not the incoming direction.
  48788. */
  48789. var HemisphericLight = /** @class */ (function (_super) {
  48790. __extends(HemisphericLight, _super);
  48791. /**
  48792. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48793. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48794. * The HemisphericLight can't cast shadows.
  48795. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48796. * @param name The friendly name of the light
  48797. * @param direction The direction of the light reflection
  48798. * @param scene The scene the light belongs to
  48799. */
  48800. function HemisphericLight(name, direction, scene) {
  48801. var _this = _super.call(this, name, scene) || this;
  48802. /**
  48803. * The groundColor is the light in the opposite direction to the one specified during creation.
  48804. * 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.
  48805. */
  48806. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48807. _this.direction = direction || BABYLON.Vector3.Up();
  48808. return _this;
  48809. }
  48810. HemisphericLight.prototype._buildUniformLayout = function () {
  48811. this._uniformBuffer.addUniform("vLightData", 4);
  48812. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48813. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48814. this._uniformBuffer.addUniform("vLightGround", 3);
  48815. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48816. this._uniformBuffer.addUniform("depthValues", 2);
  48817. this._uniformBuffer.create();
  48818. };
  48819. /**
  48820. * Returns the string "HemisphericLight".
  48821. * @return The class name
  48822. */
  48823. HemisphericLight.prototype.getClassName = function () {
  48824. return "HemisphericLight";
  48825. };
  48826. /**
  48827. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48828. * Returns the updated direction.
  48829. * @param target The target the direction should point to
  48830. * @return The computed direction
  48831. */
  48832. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48833. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48834. return this.direction;
  48835. };
  48836. /**
  48837. * Returns the shadow generator associated to the light.
  48838. * @returns Always null for hemispheric lights because it does not support shadows.
  48839. */
  48840. HemisphericLight.prototype.getShadowGenerator = function () {
  48841. return null;
  48842. };
  48843. /**
  48844. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48845. * @param effect The effect to update
  48846. * @param lightIndex The index of the light in the effect to update
  48847. * @returns The hemispheric light
  48848. */
  48849. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48850. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48851. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48852. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48853. return this;
  48854. };
  48855. /**
  48856. * @ignore internal use only.
  48857. */
  48858. HemisphericLight.prototype._getWorldMatrix = function () {
  48859. if (!this._worldMatrix) {
  48860. this._worldMatrix = BABYLON.Matrix.Identity();
  48861. }
  48862. return this._worldMatrix;
  48863. };
  48864. /**
  48865. * Returns the integer 3.
  48866. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48867. */
  48868. HemisphericLight.prototype.getTypeID = function () {
  48869. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48870. };
  48871. __decorate([
  48872. BABYLON.serializeAsColor3()
  48873. ], HemisphericLight.prototype, "groundColor", void 0);
  48874. __decorate([
  48875. BABYLON.serializeAsVector3()
  48876. ], HemisphericLight.prototype, "direction", void 0);
  48877. return HemisphericLight;
  48878. }(BABYLON.Light));
  48879. BABYLON.HemisphericLight = HemisphericLight;
  48880. })(BABYLON || (BABYLON = {}));
  48881. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48882. var BABYLON;
  48883. (function (BABYLON) {
  48884. /**
  48885. * Base implementation IShadowLight
  48886. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48887. */
  48888. var ShadowLight = /** @class */ (function (_super) {
  48889. __extends(ShadowLight, _super);
  48890. function ShadowLight() {
  48891. var _this = _super !== null && _super.apply(this, arguments) || this;
  48892. _this._needProjectionMatrixCompute = true;
  48893. return _this;
  48894. }
  48895. ShadowLight.prototype._setPosition = function (value) {
  48896. this._position = value;
  48897. };
  48898. Object.defineProperty(ShadowLight.prototype, "position", {
  48899. /**
  48900. * Sets the position the shadow will be casted from. Also use as the light position for both
  48901. * point and spot lights.
  48902. */
  48903. get: function () {
  48904. return this._position;
  48905. },
  48906. /**
  48907. * Sets the position the shadow will be casted from. Also use as the light position for both
  48908. * point and spot lights.
  48909. */
  48910. set: function (value) {
  48911. this._setPosition(value);
  48912. },
  48913. enumerable: true,
  48914. configurable: true
  48915. });
  48916. ShadowLight.prototype._setDirection = function (value) {
  48917. this._direction = value;
  48918. };
  48919. Object.defineProperty(ShadowLight.prototype, "direction", {
  48920. /**
  48921. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48922. * Also use as the light direction on spot and directional lights.
  48923. */
  48924. get: function () {
  48925. return this._direction;
  48926. },
  48927. /**
  48928. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48929. * Also use as the light direction on spot and directional lights.
  48930. */
  48931. set: function (value) {
  48932. this._setDirection(value);
  48933. },
  48934. enumerable: true,
  48935. configurable: true
  48936. });
  48937. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48938. /**
  48939. * Gets the shadow projection clipping minimum z value.
  48940. */
  48941. get: function () {
  48942. return this._shadowMinZ;
  48943. },
  48944. /**
  48945. * Sets the shadow projection clipping minimum z value.
  48946. */
  48947. set: function (value) {
  48948. this._shadowMinZ = value;
  48949. this.forceProjectionMatrixCompute();
  48950. },
  48951. enumerable: true,
  48952. configurable: true
  48953. });
  48954. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48955. /**
  48956. * Sets the shadow projection clipping maximum z value.
  48957. */
  48958. get: function () {
  48959. return this._shadowMaxZ;
  48960. },
  48961. /**
  48962. * Gets the shadow projection clipping maximum z value.
  48963. */
  48964. set: function (value) {
  48965. this._shadowMaxZ = value;
  48966. this.forceProjectionMatrixCompute();
  48967. },
  48968. enumerable: true,
  48969. configurable: true
  48970. });
  48971. /**
  48972. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48973. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48974. */
  48975. ShadowLight.prototype.computeTransformedInformation = function () {
  48976. if (this.parent && this.parent.getWorldMatrix) {
  48977. if (!this.transformedPosition) {
  48978. this.transformedPosition = BABYLON.Vector3.Zero();
  48979. }
  48980. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48981. // In case the direction is present.
  48982. if (this.direction) {
  48983. if (!this.transformedDirection) {
  48984. this.transformedDirection = BABYLON.Vector3.Zero();
  48985. }
  48986. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48987. }
  48988. return true;
  48989. }
  48990. return false;
  48991. };
  48992. /**
  48993. * Return the depth scale used for the shadow map.
  48994. * @returns the depth scale.
  48995. */
  48996. ShadowLight.prototype.getDepthScale = function () {
  48997. return 50.0;
  48998. };
  48999. /**
  49000. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49001. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49002. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49003. */
  49004. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49005. return this.transformedDirection ? this.transformedDirection : this.direction;
  49006. };
  49007. /**
  49008. * Returns the ShadowLight absolute position in the World.
  49009. * @returns the position vector in world space
  49010. */
  49011. ShadowLight.prototype.getAbsolutePosition = function () {
  49012. return this.transformedPosition ? this.transformedPosition : this.position;
  49013. };
  49014. /**
  49015. * Sets the ShadowLight direction toward the passed target.
  49016. * @param target The point tot target in local space
  49017. * @returns the updated ShadowLight direction
  49018. */
  49019. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49020. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49021. return this.direction;
  49022. };
  49023. /**
  49024. * Returns the light rotation in euler definition.
  49025. * @returns the x y z rotation in local space.
  49026. */
  49027. ShadowLight.prototype.getRotation = function () {
  49028. this.direction.normalize();
  49029. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49030. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49031. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49032. };
  49033. /**
  49034. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49035. * @returns true if a cube texture needs to be use
  49036. */
  49037. ShadowLight.prototype.needCube = function () {
  49038. return false;
  49039. };
  49040. /**
  49041. * Detects if the projection matrix requires to be recomputed this frame.
  49042. * @returns true if it requires to be recomputed otherwise, false.
  49043. */
  49044. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49045. return this._needProjectionMatrixCompute;
  49046. };
  49047. /**
  49048. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49049. */
  49050. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49051. this._needProjectionMatrixCompute = true;
  49052. };
  49053. /**
  49054. * Get the world matrix of the sahdow lights.
  49055. * @ignore Internal Use Only
  49056. */
  49057. ShadowLight.prototype._getWorldMatrix = function () {
  49058. if (!this._worldMatrix) {
  49059. this._worldMatrix = BABYLON.Matrix.Identity();
  49060. }
  49061. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49062. return this._worldMatrix;
  49063. };
  49064. /**
  49065. * Gets the minZ used for shadow according to both the scene and the light.
  49066. * @param activeCamera The camera we are returning the min for
  49067. * @returns the depth min z
  49068. */
  49069. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49070. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49071. };
  49072. /**
  49073. * Gets the maxZ used for shadow according to both the scene and the light.
  49074. * @param activeCamera The camera we are returning the max for
  49075. * @returns the depth max z
  49076. */
  49077. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49078. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49079. };
  49080. /**
  49081. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49082. * @param matrix The materix to updated with the projection information
  49083. * @param viewMatrix The transform matrix of the light
  49084. * @param renderList The list of mesh to render in the map
  49085. * @returns The current light
  49086. */
  49087. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49088. if (this.customProjectionMatrixBuilder) {
  49089. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49090. }
  49091. else {
  49092. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49093. }
  49094. return this;
  49095. };
  49096. __decorate([
  49097. BABYLON.serializeAsVector3()
  49098. ], ShadowLight.prototype, "position", null);
  49099. __decorate([
  49100. BABYLON.serializeAsVector3()
  49101. ], ShadowLight.prototype, "direction", null);
  49102. __decorate([
  49103. BABYLON.serialize()
  49104. ], ShadowLight.prototype, "shadowMinZ", null);
  49105. __decorate([
  49106. BABYLON.serialize()
  49107. ], ShadowLight.prototype, "shadowMaxZ", null);
  49108. return ShadowLight;
  49109. }(BABYLON.Light));
  49110. BABYLON.ShadowLight = ShadowLight;
  49111. })(BABYLON || (BABYLON = {}));
  49112. //# sourceMappingURL=babylon.shadowLight.js.map
  49113. var BABYLON;
  49114. (function (BABYLON) {
  49115. /**
  49116. * A point light is a light defined by an unique point in world space.
  49117. * The light is emitted in every direction from this point.
  49118. * A good example of a point light is a standard light bulb.
  49119. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49120. */
  49121. var PointLight = /** @class */ (function (_super) {
  49122. __extends(PointLight, _super);
  49123. /**
  49124. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49125. * A PointLight emits the light in every direction.
  49126. * It can cast shadows.
  49127. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49128. * ```javascript
  49129. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49130. * ```
  49131. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49132. * @param name The light friendly name
  49133. * @param position The position of the point light in the scene
  49134. * @param scene The scene the lights belongs to
  49135. */
  49136. function PointLight(name, position, scene) {
  49137. var _this = _super.call(this, name, scene) || this;
  49138. _this._shadowAngle = Math.PI / 2;
  49139. _this.position = position;
  49140. return _this;
  49141. }
  49142. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49143. /**
  49144. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49145. * This specifies what angle the shadow will use to be created.
  49146. *
  49147. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49148. */
  49149. get: function () {
  49150. return this._shadowAngle;
  49151. },
  49152. /**
  49153. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49154. * This specifies what angle the shadow will use to be created.
  49155. *
  49156. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49157. */
  49158. set: function (value) {
  49159. this._shadowAngle = value;
  49160. this.forceProjectionMatrixCompute();
  49161. },
  49162. enumerable: true,
  49163. configurable: true
  49164. });
  49165. Object.defineProperty(PointLight.prototype, "direction", {
  49166. /**
  49167. * Gets the direction if it has been set.
  49168. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49169. */
  49170. get: function () {
  49171. return this._direction;
  49172. },
  49173. /**
  49174. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49175. */
  49176. set: function (value) {
  49177. var previousNeedCube = this.needCube();
  49178. this._direction = value;
  49179. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49180. this._shadowGenerator.recreateShadowMap();
  49181. }
  49182. },
  49183. enumerable: true,
  49184. configurable: true
  49185. });
  49186. /**
  49187. * Returns the string "PointLight"
  49188. * @returns the class name
  49189. */
  49190. PointLight.prototype.getClassName = function () {
  49191. return "PointLight";
  49192. };
  49193. /**
  49194. * Returns the integer 0.
  49195. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49196. */
  49197. PointLight.prototype.getTypeID = function () {
  49198. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49199. };
  49200. /**
  49201. * Specifies wether or not the shadowmap should be a cube texture.
  49202. * @returns true if the shadowmap needs to be a cube texture.
  49203. */
  49204. PointLight.prototype.needCube = function () {
  49205. return !this.direction;
  49206. };
  49207. /**
  49208. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49209. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49210. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49211. */
  49212. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49213. if (this.direction) {
  49214. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49215. }
  49216. else {
  49217. switch (faceIndex) {
  49218. case 0:
  49219. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49220. case 1:
  49221. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49222. case 2:
  49223. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49224. case 3:
  49225. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49226. case 4:
  49227. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49228. case 5:
  49229. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49230. }
  49231. }
  49232. return BABYLON.Vector3.Zero();
  49233. };
  49234. /**
  49235. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49236. * - fov = PI / 2
  49237. * - aspect ratio : 1.0
  49238. * - z-near and far equal to the active camera minZ and maxZ.
  49239. * Returns the PointLight.
  49240. */
  49241. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49242. var activeCamera = this.getScene().activeCamera;
  49243. if (!activeCamera) {
  49244. return;
  49245. }
  49246. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49247. };
  49248. PointLight.prototype._buildUniformLayout = function () {
  49249. this._uniformBuffer.addUniform("vLightData", 4);
  49250. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49251. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49252. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49253. this._uniformBuffer.addUniform("depthValues", 2);
  49254. this._uniformBuffer.create();
  49255. };
  49256. /**
  49257. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49258. * @param effect The effect to update
  49259. * @param lightIndex The index of the light in the effect to update
  49260. * @returns The point light
  49261. */
  49262. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49263. if (this.computeTransformedInformation()) {
  49264. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49265. return this;
  49266. }
  49267. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49268. return this;
  49269. };
  49270. __decorate([
  49271. BABYLON.serialize()
  49272. ], PointLight.prototype, "shadowAngle", null);
  49273. return PointLight;
  49274. }(BABYLON.ShadowLight));
  49275. BABYLON.PointLight = PointLight;
  49276. })(BABYLON || (BABYLON = {}));
  49277. //# sourceMappingURL=babylon.pointLight.js.map
  49278. var BABYLON;
  49279. (function (BABYLON) {
  49280. /**
  49281. * A directional light is defined by a direction (what a surprise!).
  49282. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49283. * 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.
  49284. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49285. */
  49286. var DirectionalLight = /** @class */ (function (_super) {
  49287. __extends(DirectionalLight, _super);
  49288. /**
  49289. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49290. * The directional light is emitted from everywhere in the given direction.
  49291. * It can cast shawdows.
  49292. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49293. * @param name The friendly name of the light
  49294. * @param direction The direction of the light
  49295. * @param scene The scene the light belongs to
  49296. */
  49297. function DirectionalLight(name, direction, scene) {
  49298. var _this = _super.call(this, name, scene) || this;
  49299. _this._shadowFrustumSize = 0;
  49300. _this._shadowOrthoScale = 0.1;
  49301. /**
  49302. * Automatically compute the projection matrix to best fit (including all the casters)
  49303. * on each frame.
  49304. */
  49305. _this.autoUpdateExtends = true;
  49306. // Cache
  49307. _this._orthoLeft = Number.MAX_VALUE;
  49308. _this._orthoRight = Number.MIN_VALUE;
  49309. _this._orthoTop = Number.MIN_VALUE;
  49310. _this._orthoBottom = Number.MAX_VALUE;
  49311. _this.position = direction.scale(-1.0);
  49312. _this.direction = direction;
  49313. return _this;
  49314. }
  49315. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49316. /**
  49317. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49318. */
  49319. get: function () {
  49320. return this._shadowFrustumSize;
  49321. },
  49322. /**
  49323. * Specifies a fix frustum size for the shadow generation.
  49324. */
  49325. set: function (value) {
  49326. this._shadowFrustumSize = value;
  49327. this.forceProjectionMatrixCompute();
  49328. },
  49329. enumerable: true,
  49330. configurable: true
  49331. });
  49332. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49333. /**
  49334. * Gets the shadow projection scale against the optimal computed one.
  49335. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49336. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49337. */
  49338. get: function () {
  49339. return this._shadowOrthoScale;
  49340. },
  49341. /**
  49342. * Sets the shadow projection scale against the optimal computed one.
  49343. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49344. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49345. */
  49346. set: function (value) {
  49347. this._shadowOrthoScale = value;
  49348. this.forceProjectionMatrixCompute();
  49349. },
  49350. enumerable: true,
  49351. configurable: true
  49352. });
  49353. /**
  49354. * Returns the string "DirectionalLight".
  49355. * @return The class name
  49356. */
  49357. DirectionalLight.prototype.getClassName = function () {
  49358. return "DirectionalLight";
  49359. };
  49360. /**
  49361. * Returns the integer 1.
  49362. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49363. */
  49364. DirectionalLight.prototype.getTypeID = function () {
  49365. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49366. };
  49367. /**
  49368. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49369. * Returns the DirectionalLight Shadow projection matrix.
  49370. */
  49371. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49372. if (this.shadowFrustumSize > 0) {
  49373. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49374. }
  49375. else {
  49376. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49377. }
  49378. };
  49379. /**
  49380. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49381. * Returns the DirectionalLight Shadow projection matrix.
  49382. */
  49383. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49384. var activeCamera = this.getScene().activeCamera;
  49385. if (!activeCamera) {
  49386. return;
  49387. }
  49388. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49389. };
  49390. /**
  49391. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49392. * Returns the DirectionalLight Shadow projection matrix.
  49393. */
  49394. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49395. var activeCamera = this.getScene().activeCamera;
  49396. if (!activeCamera) {
  49397. return;
  49398. }
  49399. // Check extends
  49400. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49401. var tempVector3 = BABYLON.Vector3.Zero();
  49402. this._orthoLeft = Number.MAX_VALUE;
  49403. this._orthoRight = Number.MIN_VALUE;
  49404. this._orthoTop = Number.MIN_VALUE;
  49405. this._orthoBottom = Number.MAX_VALUE;
  49406. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49407. var mesh = renderList[meshIndex];
  49408. if (!mesh) {
  49409. continue;
  49410. }
  49411. var boundingInfo = mesh.getBoundingInfo();
  49412. var boundingBox = boundingInfo.boundingBox;
  49413. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49414. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49415. if (tempVector3.x < this._orthoLeft)
  49416. this._orthoLeft = tempVector3.x;
  49417. if (tempVector3.y < this._orthoBottom)
  49418. this._orthoBottom = tempVector3.y;
  49419. if (tempVector3.x > this._orthoRight)
  49420. this._orthoRight = tempVector3.x;
  49421. if (tempVector3.y > this._orthoTop)
  49422. this._orthoTop = tempVector3.y;
  49423. }
  49424. }
  49425. }
  49426. var xOffset = this._orthoRight - this._orthoLeft;
  49427. var yOffset = this._orthoTop - this._orthoBottom;
  49428. 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);
  49429. };
  49430. DirectionalLight.prototype._buildUniformLayout = function () {
  49431. this._uniformBuffer.addUniform("vLightData", 4);
  49432. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49433. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49434. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49435. this._uniformBuffer.addUniform("depthValues", 2);
  49436. this._uniformBuffer.create();
  49437. };
  49438. /**
  49439. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49440. * @param effect The effect to update
  49441. * @param lightIndex The index of the light in the effect to update
  49442. * @returns The directional light
  49443. */
  49444. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49445. if (this.computeTransformedInformation()) {
  49446. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49447. return this;
  49448. }
  49449. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49450. return this;
  49451. };
  49452. /**
  49453. * Gets the minZ used for shadow according to both the scene and the light.
  49454. *
  49455. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49456. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49457. * @param activeCamera The camera we are returning the min for
  49458. * @returns the depth min z
  49459. */
  49460. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49461. return 1;
  49462. };
  49463. /**
  49464. * Gets the maxZ used for shadow according to both the scene and the light.
  49465. *
  49466. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49467. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49468. * @param activeCamera The camera we are returning the max for
  49469. * @returns the depth max z
  49470. */
  49471. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49472. return 1;
  49473. };
  49474. __decorate([
  49475. BABYLON.serialize()
  49476. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49477. __decorate([
  49478. BABYLON.serialize()
  49479. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49480. __decorate([
  49481. BABYLON.serialize()
  49482. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49483. return DirectionalLight;
  49484. }(BABYLON.ShadowLight));
  49485. BABYLON.DirectionalLight = DirectionalLight;
  49486. })(BABYLON || (BABYLON = {}));
  49487. //# sourceMappingURL=babylon.directionalLight.js.map
  49488. var BABYLON;
  49489. (function (BABYLON) {
  49490. /**
  49491. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49492. * These values define a cone of light starting from the position, emitting toward the direction.
  49493. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49494. * and the exponent defines the speed of the decay of the light with distance (reach).
  49495. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49496. */
  49497. var SpotLight = /** @class */ (function (_super) {
  49498. __extends(SpotLight, _super);
  49499. /**
  49500. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49501. * It can cast shadows.
  49502. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49503. * @param name The light friendly name
  49504. * @param position The position of the spot light in the scene
  49505. * @param direction The direction of the light in the scene
  49506. * @param angle The cone angle of the light in Radians
  49507. * @param exponent The light decay speed with the distance from the emission spot
  49508. * @param scene The scene the lights belongs to
  49509. */
  49510. function SpotLight(name, position, direction, angle, exponent, scene) {
  49511. var _this = _super.call(this, name, scene) || this;
  49512. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49513. _this._projectionTextureLightNear = 1e-6;
  49514. _this._projectionTextureLightFar = 1000.0;
  49515. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49516. _this._projectionTextureViewLightDirty = true;
  49517. _this._projectionTextureProjectionLightDirty = true;
  49518. _this._projectionTextureDirty = true;
  49519. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49520. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49521. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49522. _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);
  49523. _this.position = position;
  49524. _this.direction = direction;
  49525. _this.angle = angle;
  49526. _this.exponent = exponent;
  49527. return _this;
  49528. }
  49529. Object.defineProperty(SpotLight.prototype, "angle", {
  49530. /**
  49531. * Gets the cone angle of the spot light in Radians.
  49532. */
  49533. get: function () {
  49534. return this._angle;
  49535. },
  49536. /**
  49537. * Sets the cone angle of the spot light in Radians.
  49538. */
  49539. set: function (value) {
  49540. this._angle = value;
  49541. this._projectionTextureProjectionLightDirty = true;
  49542. this.forceProjectionMatrixCompute();
  49543. },
  49544. enumerable: true,
  49545. configurable: true
  49546. });
  49547. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49548. /**
  49549. * Allows scaling the angle of the light for shadow generation only.
  49550. */
  49551. get: function () {
  49552. return this._shadowAngleScale;
  49553. },
  49554. /**
  49555. * Allows scaling the angle of the light for shadow generation only.
  49556. */
  49557. set: function (value) {
  49558. this._shadowAngleScale = value;
  49559. this.forceProjectionMatrixCompute();
  49560. },
  49561. enumerable: true,
  49562. configurable: true
  49563. });
  49564. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49565. /**
  49566. * Allows reading the projecton texture
  49567. */
  49568. get: function () {
  49569. return this._projectionTextureMatrix;
  49570. },
  49571. enumerable: true,
  49572. configurable: true
  49573. });
  49574. ;
  49575. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49576. /**
  49577. * Gets the near clip of the Spotlight for texture projection.
  49578. */
  49579. get: function () {
  49580. return this._projectionTextureLightNear;
  49581. },
  49582. /**
  49583. * Sets the near clip of the Spotlight for texture projection.
  49584. */
  49585. set: function (value) {
  49586. this._projectionTextureLightNear = value;
  49587. this._projectionTextureProjectionLightDirty = true;
  49588. },
  49589. enumerable: true,
  49590. configurable: true
  49591. });
  49592. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49593. /**
  49594. * Gets the far clip of the Spotlight for texture projection.
  49595. */
  49596. get: function () {
  49597. return this._projectionTextureLightFar;
  49598. },
  49599. /**
  49600. * Sets the far clip of the Spotlight for texture projection.
  49601. */
  49602. set: function (value) {
  49603. this._projectionTextureLightFar = value;
  49604. this._projectionTextureProjectionLightDirty = true;
  49605. },
  49606. enumerable: true,
  49607. configurable: true
  49608. });
  49609. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49610. /**
  49611. * Gets the Up vector of the Spotlight for texture projection.
  49612. */
  49613. get: function () {
  49614. return this._projectionTextureUpDirection;
  49615. },
  49616. /**
  49617. * Sets the Up vector of the Spotlight for texture projection.
  49618. */
  49619. set: function (value) {
  49620. this._projectionTextureUpDirection = value;
  49621. this._projectionTextureProjectionLightDirty = true;
  49622. },
  49623. enumerable: true,
  49624. configurable: true
  49625. });
  49626. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49627. /**
  49628. * Gets the projection texture of the light.
  49629. */
  49630. get: function () {
  49631. return this._projectionTexture;
  49632. },
  49633. /**
  49634. * Sets the projection texture of the light.
  49635. */
  49636. set: function (value) {
  49637. this._projectionTexture = value;
  49638. this._projectionTextureDirty = true;
  49639. },
  49640. enumerable: true,
  49641. configurable: true
  49642. });
  49643. /**
  49644. * Returns the string "SpotLight".
  49645. * @returns the class name
  49646. */
  49647. SpotLight.prototype.getClassName = function () {
  49648. return "SpotLight";
  49649. };
  49650. /**
  49651. * Returns the integer 2.
  49652. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49653. */
  49654. SpotLight.prototype.getTypeID = function () {
  49655. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49656. };
  49657. /**
  49658. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49659. */
  49660. SpotLight.prototype._setDirection = function (value) {
  49661. _super.prototype._setDirection.call(this, value);
  49662. this._projectionTextureViewLightDirty = true;
  49663. };
  49664. /**
  49665. * Overrides the position setter to recompute the projection texture view light Matrix.
  49666. */
  49667. SpotLight.prototype._setPosition = function (value) {
  49668. _super.prototype._setPosition.call(this, value);
  49669. this._projectionTextureViewLightDirty = true;
  49670. };
  49671. /**
  49672. * 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.
  49673. * Returns the SpotLight.
  49674. */
  49675. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49676. var activeCamera = this.getScene().activeCamera;
  49677. if (!activeCamera) {
  49678. return;
  49679. }
  49680. this._shadowAngleScale = this._shadowAngleScale || 1;
  49681. var angle = this._shadowAngleScale * this._angle;
  49682. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49683. };
  49684. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49685. this._projectionTextureViewLightDirty = false;
  49686. this._projectionTextureDirty = true;
  49687. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49688. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49689. };
  49690. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49691. this._projectionTextureProjectionLightDirty = false;
  49692. this._projectionTextureDirty = true;
  49693. var light_far = this.projectionTextureLightFar;
  49694. var light_near = this.projectionTextureLightNear;
  49695. var P = light_far / (light_far - light_near);
  49696. var Q = -P * light_near;
  49697. var S = 1.0 / Math.tan(this._angle / 2.0);
  49698. var A = 1.0;
  49699. 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);
  49700. };
  49701. /**
  49702. * Main function for light texture projection matrix computing.
  49703. */
  49704. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49705. this._projectionTextureDirty = false;
  49706. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49707. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49708. };
  49709. SpotLight.prototype._buildUniformLayout = function () {
  49710. this._uniformBuffer.addUniform("vLightData", 4);
  49711. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49712. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49713. this._uniformBuffer.addUniform("vLightDirection", 3);
  49714. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49715. this._uniformBuffer.addUniform("depthValues", 2);
  49716. this._uniformBuffer.create();
  49717. };
  49718. /**
  49719. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49720. * @param effect The effect to update
  49721. * @param lightIndex The index of the light in the effect to update
  49722. * @returns The spot light
  49723. */
  49724. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49725. var normalizeDirection;
  49726. if (this.computeTransformedInformation()) {
  49727. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49728. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49729. }
  49730. else {
  49731. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49732. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49733. }
  49734. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49735. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49736. if (this._projectionTextureViewLightDirty) {
  49737. this._computeProjectionTextureViewLightMatrix();
  49738. }
  49739. if (this._projectionTextureProjectionLightDirty) {
  49740. this._computeProjectionTextureProjectionLightMatrix();
  49741. }
  49742. if (this._projectionTextureDirty) {
  49743. this._computeProjectionTextureMatrix();
  49744. }
  49745. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49746. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49747. }
  49748. return this;
  49749. };
  49750. /**
  49751. * Disposes the light and the associated resources.
  49752. */
  49753. SpotLight.prototype.dispose = function () {
  49754. _super.prototype.dispose.call(this);
  49755. if (this._projectionTexture) {
  49756. this._projectionTexture.dispose();
  49757. }
  49758. };
  49759. __decorate([
  49760. BABYLON.serialize()
  49761. ], SpotLight.prototype, "angle", null);
  49762. __decorate([
  49763. BABYLON.serialize()
  49764. ], SpotLight.prototype, "shadowAngleScale", null);
  49765. __decorate([
  49766. BABYLON.serialize()
  49767. ], SpotLight.prototype, "exponent", void 0);
  49768. __decorate([
  49769. BABYLON.serialize()
  49770. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49771. __decorate([
  49772. BABYLON.serialize()
  49773. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49774. __decorate([
  49775. BABYLON.serialize()
  49776. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49777. __decorate([
  49778. BABYLON.serializeAsTexture("projectedLightTexture")
  49779. ], SpotLight.prototype, "_projectionTexture", void 0);
  49780. return SpotLight;
  49781. }(BABYLON.ShadowLight));
  49782. BABYLON.SpotLight = SpotLight;
  49783. })(BABYLON || (BABYLON = {}));
  49784. //# sourceMappingURL=babylon.spotLight.js.map
  49785. var BABYLON;
  49786. (function (BABYLON) {
  49787. /**
  49788. * Class used to override all child animations of a given target
  49789. */
  49790. var AnimationPropertiesOverride = /** @class */ (function () {
  49791. function AnimationPropertiesOverride() {
  49792. /**
  49793. * Gets or sets a value indicating if animation blending must be used
  49794. */
  49795. this.enableBlending = false;
  49796. /**
  49797. * Gets or sets the blending speed to use when enableBlending is true
  49798. */
  49799. this.blendingSpeed = 0.01;
  49800. /**
  49801. * Gets or sets the default loop mode to use
  49802. */
  49803. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49804. }
  49805. return AnimationPropertiesOverride;
  49806. }());
  49807. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49808. })(BABYLON || (BABYLON = {}));
  49809. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49810. var BABYLON;
  49811. (function (BABYLON) {
  49812. /**
  49813. * Represents the range of an animation
  49814. */
  49815. var AnimationRange = /** @class */ (function () {
  49816. /**
  49817. * Initializes the range of an animation
  49818. * @param name The name of the animation range
  49819. * @param from The starting frame of the animation
  49820. * @param to The ending frame of the animation
  49821. */
  49822. function AnimationRange(
  49823. /**The name of the animation range**/
  49824. name,
  49825. /**The starting frame of the animation */
  49826. from,
  49827. /**The ending frame of the animation*/
  49828. to) {
  49829. this.name = name;
  49830. this.from = from;
  49831. this.to = to;
  49832. }
  49833. /**
  49834. * Makes a copy of the animation range
  49835. * @returns A copy of the animation range
  49836. */
  49837. AnimationRange.prototype.clone = function () {
  49838. return new AnimationRange(this.name, this.from, this.to);
  49839. };
  49840. return AnimationRange;
  49841. }());
  49842. BABYLON.AnimationRange = AnimationRange;
  49843. /**
  49844. * Composed of a frame, and an action function
  49845. */
  49846. var AnimationEvent = /** @class */ (function () {
  49847. /**
  49848. * Initializes the animation event
  49849. * @param frame The frame for which the event is triggered
  49850. * @param action The event to perform when triggered
  49851. * @param onlyOnce Specifies if the event should be triggered only once
  49852. */
  49853. function AnimationEvent(
  49854. /** The frame for which the event is triggered **/
  49855. frame,
  49856. /** The event to perform when triggered **/
  49857. action,
  49858. /** Specifies if the event should be triggered only once**/
  49859. onlyOnce) {
  49860. this.frame = frame;
  49861. this.action = action;
  49862. this.onlyOnce = onlyOnce;
  49863. /**
  49864. * Specifies if the animation event is done
  49865. */
  49866. this.isDone = false;
  49867. }
  49868. return AnimationEvent;
  49869. }());
  49870. BABYLON.AnimationEvent = AnimationEvent;
  49871. /**
  49872. * A cursor which tracks a point on a path
  49873. */
  49874. var PathCursor = /** @class */ (function () {
  49875. /**
  49876. * Initializes the path cursor
  49877. * @param path The path to track
  49878. */
  49879. function PathCursor(path) {
  49880. this.path = path;
  49881. /**
  49882. * Stores path cursor callbacks for when an onchange event is triggered
  49883. */
  49884. this._onchange = new Array();
  49885. /**
  49886. * The value of the path cursor
  49887. */
  49888. this.value = 0;
  49889. /**
  49890. * The animation array of the path cursor
  49891. */
  49892. this.animations = new Array();
  49893. }
  49894. /**
  49895. * Gets the cursor point on the path
  49896. * @returns A point on the path cursor at the cursor location
  49897. */
  49898. PathCursor.prototype.getPoint = function () {
  49899. var point = this.path.getPointAtLengthPosition(this.value);
  49900. return new BABYLON.Vector3(point.x, 0, point.y);
  49901. };
  49902. /**
  49903. * Moves the cursor ahead by the step amount
  49904. * @param step The amount to move the cursor forward
  49905. * @returns This path cursor
  49906. */
  49907. PathCursor.prototype.moveAhead = function (step) {
  49908. if (step === void 0) { step = 0.002; }
  49909. this.move(step);
  49910. return this;
  49911. };
  49912. /**
  49913. * Moves the cursor behind by the step amount
  49914. * @param step The amount to move the cursor back
  49915. * @returns This path cursor
  49916. */
  49917. PathCursor.prototype.moveBack = function (step) {
  49918. if (step === void 0) { step = 0.002; }
  49919. this.move(-step);
  49920. return this;
  49921. };
  49922. /**
  49923. * Moves the cursor by the step amount
  49924. * If the step amount is greater than one, an exception is thrown
  49925. * @param step The amount to move the cursor
  49926. * @returns This path cursor
  49927. */
  49928. PathCursor.prototype.move = function (step) {
  49929. if (Math.abs(step) > 1) {
  49930. throw "step size should be less than 1.";
  49931. }
  49932. this.value += step;
  49933. this.ensureLimits();
  49934. this.raiseOnChange();
  49935. return this;
  49936. };
  49937. /**
  49938. * Ensures that the value is limited between zero and one
  49939. * @returns This path cursor
  49940. */
  49941. PathCursor.prototype.ensureLimits = function () {
  49942. while (this.value > 1) {
  49943. this.value -= 1;
  49944. }
  49945. while (this.value < 0) {
  49946. this.value += 1;
  49947. }
  49948. return this;
  49949. };
  49950. /**
  49951. * Runs onchange callbacks on change (used by the animation engine)
  49952. * @returns This path cursor
  49953. */
  49954. PathCursor.prototype.raiseOnChange = function () {
  49955. var _this = this;
  49956. this._onchange.forEach(function (f) { return f(_this); });
  49957. return this;
  49958. };
  49959. /**
  49960. * Executes a function on change
  49961. * @param f A path cursor onchange callback
  49962. * @returns This path cursor
  49963. */
  49964. PathCursor.prototype.onchange = function (f) {
  49965. this._onchange.push(f);
  49966. return this;
  49967. };
  49968. return PathCursor;
  49969. }());
  49970. BABYLON.PathCursor = PathCursor;
  49971. /**
  49972. * Enum for the animation key frame interpolation type
  49973. */
  49974. var AnimationKeyInterpolation;
  49975. (function (AnimationKeyInterpolation) {
  49976. /**
  49977. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49978. */
  49979. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49980. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49981. /**
  49982. * Class used to store any kind of animation
  49983. */
  49984. var Animation = /** @class */ (function () {
  49985. /**
  49986. * Initializes the animation
  49987. * @param name Name of the animation
  49988. * @param targetProperty Property to animate
  49989. * @param framePerSecond The frames per second of the animation
  49990. * @param dataType The data type of the animation
  49991. * @param loopMode The loop mode of the animation
  49992. * @param enableBlendings Specifies if blending should be enabled
  49993. */
  49994. function Animation(
  49995. /**Name of the animation */
  49996. name,
  49997. /**Property to animate */
  49998. targetProperty,
  49999. /**The frames per second of the animation */
  50000. framePerSecond,
  50001. /**The data type of the animation */
  50002. dataType,
  50003. /**The loop mode of the animation */
  50004. loopMode,
  50005. /**Specifies if blending should be enabled */
  50006. enableBlending) {
  50007. this.name = name;
  50008. this.targetProperty = targetProperty;
  50009. this.framePerSecond = framePerSecond;
  50010. this.dataType = dataType;
  50011. this.loopMode = loopMode;
  50012. this.enableBlending = enableBlending;
  50013. /**
  50014. * @ignore Internal use only
  50015. */
  50016. this._runtimeAnimations = new Array();
  50017. /**
  50018. * The set of event that will be linked to this animation
  50019. */
  50020. this._events = new Array();
  50021. /**
  50022. * Stores the blending speed of the animation
  50023. */
  50024. this.blendingSpeed = 0.01;
  50025. /**
  50026. * Stores the animation ranges for the animation
  50027. */
  50028. this._ranges = {};
  50029. this.targetPropertyPath = targetProperty.split(".");
  50030. this.dataType = dataType;
  50031. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50032. }
  50033. /**
  50034. * @ignore Internal use
  50035. */
  50036. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50037. var dataType = undefined;
  50038. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50039. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50040. }
  50041. else if (from instanceof BABYLON.Quaternion) {
  50042. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50043. }
  50044. else if (from instanceof BABYLON.Vector3) {
  50045. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50046. }
  50047. else if (from instanceof BABYLON.Vector2) {
  50048. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50049. }
  50050. else if (from instanceof BABYLON.Color3) {
  50051. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50052. }
  50053. else if (from instanceof BABYLON.Size) {
  50054. dataType = Animation.ANIMATIONTYPE_SIZE;
  50055. }
  50056. if (dataType == undefined) {
  50057. return null;
  50058. }
  50059. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50060. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50061. animation.setKeys(keys);
  50062. if (easingFunction !== undefined) {
  50063. animation.setEasingFunction(easingFunction);
  50064. }
  50065. return animation;
  50066. };
  50067. /**
  50068. * Sets up an animation
  50069. * @param property The property to animate
  50070. * @param animationType The animation type to apply
  50071. * @param framePerSecond The frames per second of the animation
  50072. * @param easingFunction The easing function used in the animation
  50073. * @returns The created animation
  50074. */
  50075. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50076. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50077. animation.setEasingFunction(easingFunction);
  50078. return animation;
  50079. };
  50080. /**
  50081. * Create and start an animation on a node
  50082. * @param name defines the name of the global animation that will be run on all nodes
  50083. * @param node defines the root node where the animation will take place
  50084. * @param targetProperty defines property to animate
  50085. * @param framePerSecond defines the number of frame per second yo use
  50086. * @param totalFrame defines the number of frames in total
  50087. * @param from defines the initial value
  50088. * @param to defines the final value
  50089. * @param loopMode defines which loop mode you want to use (off by default)
  50090. * @param easingFunction defines the easing function to use (linear by default)
  50091. * @param onAnimationEnd defines the callback to call when animation end
  50092. * @returns the animatable created for this animation
  50093. */
  50094. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50095. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50096. if (!animation) {
  50097. return null;
  50098. }
  50099. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50100. };
  50101. /**
  50102. * Create and start an animation on a node and its descendants
  50103. * @param name defines the name of the global animation that will be run on all nodes
  50104. * @param node defines the root node where the animation will take place
  50105. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  50106. * @param targetProperty defines property to animate
  50107. * @param framePerSecond defines the number of frame per second to use
  50108. * @param totalFrame defines the number of frames in total
  50109. * @param from defines the initial value
  50110. * @param to defines the final value
  50111. * @param loopMode defines which loop mode you want to use (off by default)
  50112. * @param easingFunction defines the easing function to use (linear by default)
  50113. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50114. * @returns the list of animatables created for all nodes
  50115. * @example https://www.babylonjs-playground.com/#MH0VLI
  50116. */
  50117. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50118. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50119. if (!animation) {
  50120. return null;
  50121. }
  50122. var scene = node.getScene();
  50123. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50124. };
  50125. /**
  50126. * Creates a new animation, merges it with the existing animations and starts it
  50127. * @param name Name of the animation
  50128. * @param node Node which contains the scene that begins the animations
  50129. * @param targetProperty Specifies which property to animate
  50130. * @param framePerSecond The frames per second of the animation
  50131. * @param totalFrame The total number of frames
  50132. * @param from The frame at the beginning of the animation
  50133. * @param to The frame at the end of the animation
  50134. * @param loopMode Specifies the loop mode of the animation
  50135. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50136. * @param onAnimationEnd Callback to run once the animation is complete
  50137. * @returns Nullable animation
  50138. */
  50139. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50140. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50141. if (!animation) {
  50142. return null;
  50143. }
  50144. node.animations.push(animation);
  50145. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50146. };
  50147. /**
  50148. * Transition property of the Camera to the target Value
  50149. * @param property The property to transition
  50150. * @param targetValue The target Value of the property
  50151. * @param host The object where the property to animate belongs
  50152. * @param scene Scene used to run the animation
  50153. * @param frameRate Framerate (in frame/s) to use
  50154. * @param transition The transition type we want to use
  50155. * @param duration The duration of the animation, in milliseconds
  50156. * @param onAnimationEnd Callback trigger at the end of the animation
  50157. * @returns Nullable animation
  50158. */
  50159. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50160. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50161. if (duration <= 0) {
  50162. host[property] = targetValue;
  50163. if (onAnimationEnd) {
  50164. onAnimationEnd();
  50165. }
  50166. return null;
  50167. }
  50168. var endFrame = frameRate * (duration / 1000);
  50169. transition.setKeys([{
  50170. frame: 0,
  50171. value: host[property].clone ? host[property].clone() : host[property]
  50172. },
  50173. {
  50174. frame: endFrame,
  50175. value: targetValue
  50176. }]);
  50177. if (!host.animations) {
  50178. host.animations = [];
  50179. }
  50180. host.animations.push(transition);
  50181. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50182. animation.onAnimationEnd = onAnimationEnd;
  50183. return animation;
  50184. };
  50185. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50186. /**
  50187. * Return the array of runtime animations currently using this animation
  50188. */
  50189. get: function () {
  50190. return this._runtimeAnimations;
  50191. },
  50192. enumerable: true,
  50193. configurable: true
  50194. });
  50195. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50196. /**
  50197. * Specifies if any of the runtime animations are currently running
  50198. */
  50199. get: function () {
  50200. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50201. var runtimeAnimation = _a[_i];
  50202. if (!runtimeAnimation.isStopped) {
  50203. return true;
  50204. }
  50205. }
  50206. return false;
  50207. },
  50208. enumerable: true,
  50209. configurable: true
  50210. });
  50211. // Methods
  50212. /**
  50213. * Converts the animation to a string
  50214. * @param fullDetails support for multiple levels of logging within scene loading
  50215. * @returns String form of the animation
  50216. */
  50217. Animation.prototype.toString = function (fullDetails) {
  50218. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50219. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50220. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50221. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50222. if (fullDetails) {
  50223. ret += ", Ranges: {";
  50224. var first = true;
  50225. for (var name in this._ranges) {
  50226. if (first) {
  50227. ret += ", ";
  50228. first = false;
  50229. }
  50230. ret += name;
  50231. }
  50232. ret += "}";
  50233. }
  50234. return ret;
  50235. };
  50236. /**
  50237. * Add an event to this animation
  50238. * @param event Event to add
  50239. */
  50240. Animation.prototype.addEvent = function (event) {
  50241. this._events.push(event);
  50242. };
  50243. /**
  50244. * Remove all events found at the given frame
  50245. * @param frame The frame to remove events from
  50246. */
  50247. Animation.prototype.removeEvents = function (frame) {
  50248. for (var index = 0; index < this._events.length; index++) {
  50249. if (this._events[index].frame === frame) {
  50250. this._events.splice(index, 1);
  50251. index--;
  50252. }
  50253. }
  50254. };
  50255. /**
  50256. * Retrieves all the events from the animation
  50257. * @returns Events from the animation
  50258. */
  50259. Animation.prototype.getEvents = function () {
  50260. return this._events;
  50261. };
  50262. /**
  50263. * Creates an animation range
  50264. * @param name Name of the animation range
  50265. * @param from Starting frame of the animation range
  50266. * @param to Ending frame of the animation
  50267. */
  50268. Animation.prototype.createRange = function (name, from, to) {
  50269. // check name not already in use; could happen for bones after serialized
  50270. if (!this._ranges[name]) {
  50271. this._ranges[name] = new AnimationRange(name, from, to);
  50272. }
  50273. };
  50274. /**
  50275. * Deletes an animation range by name
  50276. * @param name Name of the animation range to delete
  50277. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50278. */
  50279. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50280. if (deleteFrames === void 0) { deleteFrames = true; }
  50281. var range = this._ranges[name];
  50282. if (!range) {
  50283. return;
  50284. }
  50285. if (deleteFrames) {
  50286. var from = range.from;
  50287. var to = range.to;
  50288. // this loop MUST go high to low for multiple splices to work
  50289. for (var key = this._keys.length - 1; key >= 0; key--) {
  50290. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50291. this._keys.splice(key, 1);
  50292. }
  50293. }
  50294. }
  50295. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50296. };
  50297. /**
  50298. * Gets the animation range by name, or null if not defined
  50299. * @param name Name of the animation range
  50300. * @returns Nullable animation range
  50301. */
  50302. Animation.prototype.getRange = function (name) {
  50303. return this._ranges[name];
  50304. };
  50305. /**
  50306. * Gets the key frames from the animation
  50307. * @returns The key frames of the animation
  50308. */
  50309. Animation.prototype.getKeys = function () {
  50310. return this._keys;
  50311. };
  50312. /**
  50313. * Gets the highest frame rate of the animation
  50314. * @returns Highest frame rate of the animation
  50315. */
  50316. Animation.prototype.getHighestFrame = function () {
  50317. var ret = 0;
  50318. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50319. if (ret < this._keys[key].frame) {
  50320. ret = this._keys[key].frame;
  50321. }
  50322. }
  50323. return ret;
  50324. };
  50325. /**
  50326. * Gets the easing function of the animation
  50327. * @returns Easing function of the animation
  50328. */
  50329. Animation.prototype.getEasingFunction = function () {
  50330. return this._easingFunction;
  50331. };
  50332. /**
  50333. * Sets the easing function of the animation
  50334. * @param easingFunction A custom mathematical formula for animation
  50335. */
  50336. Animation.prototype.setEasingFunction = function (easingFunction) {
  50337. this._easingFunction = easingFunction;
  50338. };
  50339. /**
  50340. * Interpolates a scalar linearly
  50341. * @param startValue Start value of the animation curve
  50342. * @param endValue End value of the animation curve
  50343. * @param gradient Scalar amount to interpolate
  50344. * @returns Interpolated scalar value
  50345. */
  50346. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50347. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50348. };
  50349. /**
  50350. * Interpolates a scalar cubically
  50351. * @param startValue Start value of the animation curve
  50352. * @param outTangent End tangent of the animation
  50353. * @param endValue End value of the animation curve
  50354. * @param inTangent Start tangent of the animation curve
  50355. * @param gradient Scalar amount to interpolate
  50356. * @returns Interpolated scalar value
  50357. */
  50358. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50359. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50360. };
  50361. /**
  50362. * Interpolates a quaternion using a spherical linear interpolation
  50363. * @param startValue Start value of the animation curve
  50364. * @param endValue End value of the animation curve
  50365. * @param gradient Scalar amount to interpolate
  50366. * @returns Interpolated quaternion value
  50367. */
  50368. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50369. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50370. };
  50371. /**
  50372. * Interpolates a quaternion cubically
  50373. * @param startValue Start value of the animation curve
  50374. * @param outTangent End tangent of the animation curve
  50375. * @param endValue End value of the animation curve
  50376. * @param inTangent Start tangent of the animation curve
  50377. * @param gradient Scalar amount to interpolate
  50378. * @returns Interpolated quaternion value
  50379. */
  50380. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50381. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50382. };
  50383. /**
  50384. * Interpolates a Vector3 linearl
  50385. * @param startValue Start value of the animation curve
  50386. * @param endValue End value of the animation curve
  50387. * @param gradient Scalar amount to interpolate
  50388. * @returns Interpolated scalar value
  50389. */
  50390. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50391. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50392. };
  50393. /**
  50394. * Interpolates a Vector3 cubically
  50395. * @param startValue Start value of the animation curve
  50396. * @param outTangent End tangent of the animation
  50397. * @param endValue End value of the animation curve
  50398. * @param inTangent Start tangent of the animation curve
  50399. * @param gradient Scalar amount to interpolate
  50400. * @returns InterpolatedVector3 value
  50401. */
  50402. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50403. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50404. };
  50405. /**
  50406. * Interpolates a Vector2 linearly
  50407. * @param startValue Start value of the animation curve
  50408. * @param endValue End value of the animation curve
  50409. * @param gradient Scalar amount to interpolate
  50410. * @returns Interpolated Vector2 value
  50411. */
  50412. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50413. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50414. };
  50415. /**
  50416. * Interpolates a Vector2 cubically
  50417. * @param startValue Start value of the animation curve
  50418. * @param outTangent End tangent of the animation
  50419. * @param endValue End value of the animation curve
  50420. * @param inTangent Start tangent of the animation curve
  50421. * @param gradient Scalar amount to interpolate
  50422. * @returns Interpolated Vector2 value
  50423. */
  50424. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50425. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50426. };
  50427. /**
  50428. * Interpolates a size linearly
  50429. * @param startValue Start value of the animation curve
  50430. * @param endValue End value of the animation curve
  50431. * @param gradient Scalar amount to interpolate
  50432. * @returns Interpolated Size value
  50433. */
  50434. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50435. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50436. };
  50437. /**
  50438. * Interpolates a Color3 linearly
  50439. * @param startValue Start value of the animation curve
  50440. * @param endValue End value of the animation curve
  50441. * @param gradient Scalar amount to interpolate
  50442. * @returns Interpolated Color3 value
  50443. */
  50444. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50445. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50446. };
  50447. /**
  50448. * @ignore Internal use only
  50449. */
  50450. Animation.prototype._getKeyValue = function (value) {
  50451. if (typeof value === "function") {
  50452. return value();
  50453. }
  50454. return value;
  50455. };
  50456. /**
  50457. * @ignore Internal use only
  50458. */
  50459. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50460. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50461. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50462. }
  50463. var keys = this.getKeys();
  50464. // Try to get a hash to find the right key
  50465. 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));
  50466. if (keys[startKeyIndex].frame >= currentFrame) {
  50467. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50468. startKeyIndex--;
  50469. }
  50470. }
  50471. for (var key = startKeyIndex; key < keys.length; key++) {
  50472. var endKey = keys[key + 1];
  50473. if (endKey.frame >= currentFrame) {
  50474. var startKey = keys[key];
  50475. var startValue = this._getKeyValue(startKey.value);
  50476. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50477. return startValue;
  50478. }
  50479. var endValue = this._getKeyValue(endKey.value);
  50480. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50481. var frameDelta = endKey.frame - startKey.frame;
  50482. // gradient : percent of currentFrame between the frame inf and the frame sup
  50483. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50484. // check for easingFunction and correction of gradient
  50485. var easingFunction = this.getEasingFunction();
  50486. if (easingFunction != null) {
  50487. gradient = easingFunction.ease(gradient);
  50488. }
  50489. switch (this.dataType) {
  50490. // Float
  50491. case Animation.ANIMATIONTYPE_FLOAT:
  50492. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50493. switch (loopMode) {
  50494. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50495. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50496. return floatValue;
  50497. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50498. return offsetValue * repeatCount + floatValue;
  50499. }
  50500. break;
  50501. // Quaternion
  50502. case Animation.ANIMATIONTYPE_QUATERNION:
  50503. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50504. switch (loopMode) {
  50505. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50506. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50507. return quatValue;
  50508. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50509. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50510. }
  50511. return quatValue;
  50512. // Vector3
  50513. case Animation.ANIMATIONTYPE_VECTOR3:
  50514. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50515. switch (loopMode) {
  50516. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50517. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50518. return vec3Value;
  50519. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50520. return vec3Value.add(offsetValue.scale(repeatCount));
  50521. }
  50522. // Vector2
  50523. case Animation.ANIMATIONTYPE_VECTOR2:
  50524. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50525. switch (loopMode) {
  50526. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50527. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50528. return vec2Value;
  50529. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50530. return vec2Value.add(offsetValue.scale(repeatCount));
  50531. }
  50532. // Size
  50533. case Animation.ANIMATIONTYPE_SIZE:
  50534. switch (loopMode) {
  50535. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50536. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50537. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50538. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50539. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50540. }
  50541. // Color3
  50542. case Animation.ANIMATIONTYPE_COLOR3:
  50543. switch (loopMode) {
  50544. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50545. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50546. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50547. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50548. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50549. }
  50550. // Matrix
  50551. case Animation.ANIMATIONTYPE_MATRIX:
  50552. switch (loopMode) {
  50553. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50554. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50555. if (Animation.AllowMatricesInterpolation) {
  50556. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50557. }
  50558. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50559. return startValue;
  50560. }
  50561. default:
  50562. break;
  50563. }
  50564. break;
  50565. }
  50566. }
  50567. return this._getKeyValue(keys[keys.length - 1].value);
  50568. };
  50569. /**
  50570. * Defines the function to use to interpolate matrices
  50571. * @param startValue defines the start matrix
  50572. * @param endValue defines the end matrix
  50573. * @param gradient defines the gradient between both matrices
  50574. * @param result defines an optional target matrix where to store the interpolation
  50575. * @returns the interpolated matrix
  50576. */
  50577. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50578. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50579. if (result) {
  50580. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50581. return result;
  50582. }
  50583. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50584. }
  50585. if (result) {
  50586. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50587. return result;
  50588. }
  50589. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50590. };
  50591. /**
  50592. * Makes a copy of the animation
  50593. * @returns Cloned animation
  50594. */
  50595. Animation.prototype.clone = function () {
  50596. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50597. clone.enableBlending = this.enableBlending;
  50598. clone.blendingSpeed = this.blendingSpeed;
  50599. if (this._keys) {
  50600. clone.setKeys(this._keys);
  50601. }
  50602. if (this._ranges) {
  50603. clone._ranges = {};
  50604. for (var name in this._ranges) {
  50605. var range = this._ranges[name];
  50606. if (!range) {
  50607. continue;
  50608. }
  50609. clone._ranges[name] = range.clone();
  50610. }
  50611. }
  50612. return clone;
  50613. };
  50614. /**
  50615. * Sets the key frames of the animation
  50616. * @param values The animation key frames to set
  50617. */
  50618. Animation.prototype.setKeys = function (values) {
  50619. this._keys = values.slice(0);
  50620. };
  50621. /**
  50622. * Serializes the animation to an object
  50623. * @returns Serialized object
  50624. */
  50625. Animation.prototype.serialize = function () {
  50626. var serializationObject = {};
  50627. serializationObject.name = this.name;
  50628. serializationObject.property = this.targetProperty;
  50629. serializationObject.framePerSecond = this.framePerSecond;
  50630. serializationObject.dataType = this.dataType;
  50631. serializationObject.loopBehavior = this.loopMode;
  50632. serializationObject.enableBlending = this.enableBlending;
  50633. serializationObject.blendingSpeed = this.blendingSpeed;
  50634. var dataType = this.dataType;
  50635. serializationObject.keys = [];
  50636. var keys = this.getKeys();
  50637. for (var index = 0; index < keys.length; index++) {
  50638. var animationKey = keys[index];
  50639. var key = {};
  50640. key.frame = animationKey.frame;
  50641. switch (dataType) {
  50642. case Animation.ANIMATIONTYPE_FLOAT:
  50643. key.values = [animationKey.value];
  50644. break;
  50645. case Animation.ANIMATIONTYPE_QUATERNION:
  50646. case Animation.ANIMATIONTYPE_MATRIX:
  50647. case Animation.ANIMATIONTYPE_VECTOR3:
  50648. case Animation.ANIMATIONTYPE_COLOR3:
  50649. key.values = animationKey.value.asArray();
  50650. break;
  50651. }
  50652. serializationObject.keys.push(key);
  50653. }
  50654. serializationObject.ranges = [];
  50655. for (var name in this._ranges) {
  50656. var source = this._ranges[name];
  50657. if (!source) {
  50658. continue;
  50659. }
  50660. var range = {};
  50661. range.name = name;
  50662. range.from = source.from;
  50663. range.to = source.to;
  50664. serializationObject.ranges.push(range);
  50665. }
  50666. return serializationObject;
  50667. };
  50668. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50669. /**
  50670. * Get the float animation type
  50671. */
  50672. get: function () {
  50673. return Animation._ANIMATIONTYPE_FLOAT;
  50674. },
  50675. enumerable: true,
  50676. configurable: true
  50677. });
  50678. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50679. /**
  50680. * Get the Vector3 animation type
  50681. */
  50682. get: function () {
  50683. return Animation._ANIMATIONTYPE_VECTOR3;
  50684. },
  50685. enumerable: true,
  50686. configurable: true
  50687. });
  50688. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50689. /**
  50690. * Get the Vectpr2 animation type
  50691. */
  50692. get: function () {
  50693. return Animation._ANIMATIONTYPE_VECTOR2;
  50694. },
  50695. enumerable: true,
  50696. configurable: true
  50697. });
  50698. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50699. /**
  50700. * Get the Size animation type
  50701. */
  50702. get: function () {
  50703. return Animation._ANIMATIONTYPE_SIZE;
  50704. },
  50705. enumerable: true,
  50706. configurable: true
  50707. });
  50708. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50709. /**
  50710. * Get the Quaternion animation type
  50711. */
  50712. get: function () {
  50713. return Animation._ANIMATIONTYPE_QUATERNION;
  50714. },
  50715. enumerable: true,
  50716. configurable: true
  50717. });
  50718. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50719. /**
  50720. * Get the Matrix animation type
  50721. */
  50722. get: function () {
  50723. return Animation._ANIMATIONTYPE_MATRIX;
  50724. },
  50725. enumerable: true,
  50726. configurable: true
  50727. });
  50728. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50729. /**
  50730. * Get the Color3 animation type
  50731. */
  50732. get: function () {
  50733. return Animation._ANIMATIONTYPE_COLOR3;
  50734. },
  50735. enumerable: true,
  50736. configurable: true
  50737. });
  50738. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50739. /**
  50740. * Get the Relative Loop Mode
  50741. */
  50742. get: function () {
  50743. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50744. },
  50745. enumerable: true,
  50746. configurable: true
  50747. });
  50748. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50749. /**
  50750. * Get the Cycle Loop Mode
  50751. */
  50752. get: function () {
  50753. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50754. },
  50755. enumerable: true,
  50756. configurable: true
  50757. });
  50758. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50759. /**
  50760. * Get the Constant Loop Mode
  50761. */
  50762. get: function () {
  50763. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50764. },
  50765. enumerable: true,
  50766. configurable: true
  50767. });
  50768. /**
  50769. * Parses an animation object and creates an animation
  50770. * @param parsedAnimation Parsed animation object
  50771. * @returns Animation object
  50772. */
  50773. Animation.Parse = function (parsedAnimation) {
  50774. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50775. var dataType = parsedAnimation.dataType;
  50776. var keys = [];
  50777. var data;
  50778. var index;
  50779. if (parsedAnimation.enableBlending) {
  50780. animation.enableBlending = parsedAnimation.enableBlending;
  50781. }
  50782. if (parsedAnimation.blendingSpeed) {
  50783. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50784. }
  50785. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50786. var key = parsedAnimation.keys[index];
  50787. var inTangent;
  50788. var outTangent;
  50789. switch (dataType) {
  50790. case Animation.ANIMATIONTYPE_FLOAT:
  50791. data = key.values[0];
  50792. if (key.values.length >= 1) {
  50793. inTangent = key.values[1];
  50794. }
  50795. if (key.values.length >= 2) {
  50796. outTangent = key.values[2];
  50797. }
  50798. break;
  50799. case Animation.ANIMATIONTYPE_QUATERNION:
  50800. data = BABYLON.Quaternion.FromArray(key.values);
  50801. if (key.values.length >= 8) {
  50802. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50803. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50804. inTangent = _inTangent;
  50805. }
  50806. }
  50807. if (key.values.length >= 12) {
  50808. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50809. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50810. outTangent = _outTangent;
  50811. }
  50812. }
  50813. break;
  50814. case Animation.ANIMATIONTYPE_MATRIX:
  50815. data = BABYLON.Matrix.FromArray(key.values);
  50816. break;
  50817. case Animation.ANIMATIONTYPE_COLOR3:
  50818. data = BABYLON.Color3.FromArray(key.values);
  50819. break;
  50820. case Animation.ANIMATIONTYPE_VECTOR3:
  50821. default:
  50822. data = BABYLON.Vector3.FromArray(key.values);
  50823. break;
  50824. }
  50825. var keyData = {};
  50826. keyData.frame = key.frame;
  50827. keyData.value = data;
  50828. if (inTangent != undefined) {
  50829. keyData.inTangent = inTangent;
  50830. }
  50831. if (outTangent != undefined) {
  50832. keyData.outTangent = outTangent;
  50833. }
  50834. keys.push(keyData);
  50835. }
  50836. animation.setKeys(keys);
  50837. if (parsedAnimation.ranges) {
  50838. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50839. data = parsedAnimation.ranges[index];
  50840. animation.createRange(data.name, data.from, data.to);
  50841. }
  50842. }
  50843. return animation;
  50844. };
  50845. /**
  50846. * Appends the serialized animations from the source animations
  50847. * @param source Source containing the animations
  50848. * @param destination Target to store the animations
  50849. */
  50850. Animation.AppendSerializedAnimations = function (source, destination) {
  50851. if (source.animations) {
  50852. destination.animations = [];
  50853. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50854. var animation = source.animations[animationIndex];
  50855. destination.animations.push(animation.serialize());
  50856. }
  50857. }
  50858. };
  50859. /**
  50860. * Use matrix interpolation instead of using direct key value when animating matrices
  50861. */
  50862. Animation.AllowMatricesInterpolation = false;
  50863. /**
  50864. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50865. */
  50866. Animation.AllowMatrixDecomposeForInterpolation = true;
  50867. // Statics
  50868. /**
  50869. * Float animation type
  50870. */
  50871. Animation._ANIMATIONTYPE_FLOAT = 0;
  50872. /**
  50873. * Vector3 animation type
  50874. */
  50875. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50876. /**
  50877. * Quaternion animation type
  50878. */
  50879. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50880. /**
  50881. * Matrix animation type
  50882. */
  50883. Animation._ANIMATIONTYPE_MATRIX = 3;
  50884. /**
  50885. * Color3 animation type
  50886. */
  50887. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50888. /**
  50889. * Vector2 animation type
  50890. */
  50891. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50892. /**
  50893. * Size animation type
  50894. */
  50895. Animation._ANIMATIONTYPE_SIZE = 6;
  50896. /**
  50897. * Relative Loop Mode
  50898. */
  50899. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50900. /**
  50901. * Cycle Loop Mode
  50902. */
  50903. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50904. /**
  50905. * Constant Loop Mode
  50906. */
  50907. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50908. return Animation;
  50909. }());
  50910. BABYLON.Animation = Animation;
  50911. })(BABYLON || (BABYLON = {}));
  50912. //# sourceMappingURL=babylon.animation.js.map
  50913. var BABYLON;
  50914. (function (BABYLON) {
  50915. /**
  50916. * This class defines the direct association between an animation and a target
  50917. */
  50918. var TargetedAnimation = /** @class */ (function () {
  50919. function TargetedAnimation() {
  50920. }
  50921. return TargetedAnimation;
  50922. }());
  50923. BABYLON.TargetedAnimation = TargetedAnimation;
  50924. /**
  50925. * Use this class to create coordinated animations on multiple targets
  50926. */
  50927. var AnimationGroup = /** @class */ (function () {
  50928. function AnimationGroup(name, scene) {
  50929. if (scene === void 0) { scene = null; }
  50930. this.name = name;
  50931. this._targetedAnimations = new Array();
  50932. this._animatables = new Array();
  50933. this._from = Number.MAX_VALUE;
  50934. this._to = -Number.MAX_VALUE;
  50935. this._speedRatio = 1;
  50936. this.onAnimationEndObservable = new BABYLON.Observable();
  50937. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50938. this._scene.animationGroups.push(this);
  50939. }
  50940. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50941. /**
  50942. * Define if the animations are started
  50943. */
  50944. get: function () {
  50945. return this._isStarted;
  50946. },
  50947. enumerable: true,
  50948. configurable: true
  50949. });
  50950. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50951. /**
  50952. * Gets or sets the speed ratio to use for all animations
  50953. */
  50954. get: function () {
  50955. return this._speedRatio;
  50956. },
  50957. /**
  50958. * Gets or sets the speed ratio to use for all animations
  50959. */
  50960. set: function (value) {
  50961. if (this._speedRatio === value) {
  50962. return;
  50963. }
  50964. this._speedRatio = value;
  50965. for (var index = 0; index < this._animatables.length; index++) {
  50966. var animatable = this._animatables[index];
  50967. animatable.speedRatio = this._speedRatio;
  50968. }
  50969. },
  50970. enumerable: true,
  50971. configurable: true
  50972. });
  50973. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50974. /**
  50975. * Gets the targeted animations for this animation group
  50976. */
  50977. get: function () {
  50978. return this._targetedAnimations;
  50979. },
  50980. enumerable: true,
  50981. configurable: true
  50982. });
  50983. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50984. /**
  50985. * returning the list of animatables controlled by this animation group.
  50986. */
  50987. get: function () {
  50988. return this._animatables;
  50989. },
  50990. enumerable: true,
  50991. configurable: true
  50992. });
  50993. /**
  50994. * Add an animation (with its target) in the group
  50995. * @param animation defines the animation we want to add
  50996. * @param target defines the target of the animation
  50997. * @returns the {BABYLON.TargetedAnimation} object
  50998. */
  50999. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51000. var targetedAnimation = {
  51001. animation: animation,
  51002. target: target
  51003. };
  51004. var keys = animation.getKeys();
  51005. if (this._from > keys[0].frame) {
  51006. this._from = keys[0].frame;
  51007. }
  51008. if (this._to < keys[keys.length - 1].frame) {
  51009. this._to = keys[keys.length - 1].frame;
  51010. }
  51011. this._targetedAnimations.push(targetedAnimation);
  51012. return targetedAnimation;
  51013. };
  51014. /**
  51015. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51016. * It can add constant keys at begin or end
  51017. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  51018. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  51019. */
  51020. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51021. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  51022. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  51023. beginFrame = Math.max(beginFrame, this._from);
  51024. endFrame = Math.min(endFrame, this._to);
  51025. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51026. var targetedAnimation = this._targetedAnimations[index];
  51027. var keys = targetedAnimation.animation.getKeys();
  51028. var startKey = keys[0];
  51029. var endKey = keys[keys.length - 1];
  51030. if (startKey.frame > beginFrame) {
  51031. var newKey = {
  51032. frame: beginFrame,
  51033. value: startKey.value,
  51034. inTangent: startKey.inTangent,
  51035. outTangent: startKey.outTangent,
  51036. interpolation: startKey.interpolation
  51037. };
  51038. keys.splice(0, 0, newKey);
  51039. }
  51040. if (endKey.frame < endFrame) {
  51041. var newKey = {
  51042. frame: endFrame,
  51043. value: endKey.value,
  51044. inTangent: endKey.outTangent,
  51045. outTangent: endKey.outTangent,
  51046. interpolation: endKey.interpolation
  51047. };
  51048. keys.push(newKey);
  51049. }
  51050. }
  51051. return this;
  51052. };
  51053. /**
  51054. * Start all animations on given targets
  51055. * @param loop defines if animations must loop
  51056. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51057. * @param from defines the from key (optional)
  51058. * @param to defines the to key (optional)
  51059. * @returns the current animation group
  51060. */
  51061. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51062. var _this = this;
  51063. if (loop === void 0) { loop = false; }
  51064. if (speedRatio === void 0) { speedRatio = 1; }
  51065. if (this._isStarted || this._targetedAnimations.length === 0) {
  51066. return this;
  51067. }
  51068. var _loop_1 = function (targetedAnimation) {
  51069. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51070. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51071. }));
  51072. };
  51073. var this_1 = this;
  51074. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51075. var targetedAnimation = _a[_i];
  51076. _loop_1(targetedAnimation);
  51077. }
  51078. this._speedRatio = speedRatio;
  51079. this._isStarted = true;
  51080. return this;
  51081. };
  51082. /**
  51083. * Pause all animations
  51084. */
  51085. AnimationGroup.prototype.pause = function () {
  51086. if (!this._isStarted) {
  51087. return this;
  51088. }
  51089. for (var index = 0; index < this._animatables.length; index++) {
  51090. var animatable = this._animatables[index];
  51091. animatable.pause();
  51092. }
  51093. return this;
  51094. };
  51095. /**
  51096. * Play all animations to initial state
  51097. * This function will start() the animations if they were not started or will restart() them if they were paused
  51098. * @param loop defines if animations must loop
  51099. */
  51100. AnimationGroup.prototype.play = function (loop) {
  51101. if (this.isStarted) {
  51102. if (loop !== undefined) {
  51103. for (var index = 0; index < this._animatables.length; index++) {
  51104. var animatable = this._animatables[index];
  51105. animatable.loopAnimation = loop;
  51106. }
  51107. }
  51108. this.restart();
  51109. }
  51110. else {
  51111. this.start(loop, this._speedRatio);
  51112. }
  51113. return this;
  51114. };
  51115. /**
  51116. * Reset all animations to initial state
  51117. */
  51118. AnimationGroup.prototype.reset = function () {
  51119. if (!this._isStarted) {
  51120. return this;
  51121. }
  51122. for (var index = 0; index < this._animatables.length; index++) {
  51123. var animatable = this._animatables[index];
  51124. animatable.reset();
  51125. }
  51126. return this;
  51127. };
  51128. /**
  51129. * Restart animations from key 0
  51130. */
  51131. AnimationGroup.prototype.restart = function () {
  51132. if (!this._isStarted) {
  51133. return this;
  51134. }
  51135. for (var index = 0; index < this._animatables.length; index++) {
  51136. var animatable = this._animatables[index];
  51137. animatable.restart();
  51138. }
  51139. return this;
  51140. };
  51141. /**
  51142. * Stop all animations
  51143. */
  51144. AnimationGroup.prototype.stop = function () {
  51145. if (!this._isStarted) {
  51146. return this;
  51147. }
  51148. for (var index = 0; index < this._animatables.length; index++) {
  51149. var animatable = this._animatables[index];
  51150. animatable.stop();
  51151. }
  51152. this._isStarted = false;
  51153. return this;
  51154. };
  51155. /**
  51156. * Set animation weight for all animatables
  51157. * @param weight defines the weight to use
  51158. * @return the animationGroup
  51159. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51160. */
  51161. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51162. for (var index = 0; index < this._animatables.length; index++) {
  51163. var animatable = this._animatables[index];
  51164. animatable.weight = weight;
  51165. }
  51166. return this;
  51167. };
  51168. /**
  51169. * Synchronize and normalize all animatables with a source animatable
  51170. * @param root defines the root animatable to synchronize with
  51171. * @return the animationGroup
  51172. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51173. */
  51174. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51175. for (var index = 0; index < this._animatables.length; index++) {
  51176. var animatable = this._animatables[index];
  51177. animatable.syncWith(root);
  51178. }
  51179. return this;
  51180. };
  51181. /**
  51182. * Goes to a specific frame in this animation group
  51183. * @param frame the frame number to go to
  51184. * @return the animationGroup
  51185. */
  51186. AnimationGroup.prototype.goToFrame = function (frame) {
  51187. if (!this._isStarted) {
  51188. return this;
  51189. }
  51190. for (var index = 0; index < this._animatables.length; index++) {
  51191. var animatable = this._animatables[index];
  51192. animatable.goToFrame(frame);
  51193. }
  51194. return this;
  51195. };
  51196. /**
  51197. * Dispose all associated resources
  51198. */
  51199. AnimationGroup.prototype.dispose = function () {
  51200. this._targetedAnimations = [];
  51201. this._animatables = [];
  51202. var index = this._scene.animationGroups.indexOf(this);
  51203. if (index > -1) {
  51204. this._scene.animationGroups.splice(index, 1);
  51205. }
  51206. };
  51207. return AnimationGroup;
  51208. }());
  51209. BABYLON.AnimationGroup = AnimationGroup;
  51210. })(BABYLON || (BABYLON = {}));
  51211. //# sourceMappingURL=babylon.animationGroup.js.map
  51212. var BABYLON;
  51213. (function (BABYLON) {
  51214. /**
  51215. * Defines a runtime animation
  51216. */
  51217. var RuntimeAnimation = /** @class */ (function () {
  51218. /**
  51219. * Create a new RuntimeAnimation object
  51220. * @param target defines the target of the animation
  51221. * @param animation defines the source animation object
  51222. * @param scene defines the hosting scene
  51223. * @param host defines the initiating Animatable
  51224. */
  51225. function RuntimeAnimation(target, animation, scene, host) {
  51226. /**
  51227. * The current frame of the runtime animation
  51228. */
  51229. this._currentFrame = 0;
  51230. /**
  51231. * The offsets cache of the runtime animation
  51232. */
  51233. this._offsetsCache = {};
  51234. /**
  51235. * The high limits cache of the runtime animation
  51236. */
  51237. this._highLimitsCache = {};
  51238. /**
  51239. * Specifies if the runtime animation has been stopped
  51240. */
  51241. this._stopped = false;
  51242. /**
  51243. * The blending factor of the runtime animation
  51244. */
  51245. this._blendingFactor = 0;
  51246. /**
  51247. * The target path of the runtime animation
  51248. */
  51249. this._targetPath = "";
  51250. /**
  51251. * The weight of the runtime animation
  51252. */
  51253. this._weight = 1.0;
  51254. /**
  51255. * The ratio offset of the runtime animation
  51256. */
  51257. this._ratioOffset = 0;
  51258. /**
  51259. * The previous delay of the runtime animation
  51260. */
  51261. this._previousDelay = 0;
  51262. /**
  51263. * The previous ratio of the runtime animation
  51264. */
  51265. this._previousRatio = 0;
  51266. this._animation = animation;
  51267. this._target = target;
  51268. this._scene = scene;
  51269. this._host = host;
  51270. animation._runtimeAnimations.push(this);
  51271. }
  51272. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51273. /**
  51274. * Gets the current frame of the runtime animation
  51275. */
  51276. get: function () {
  51277. return this._currentFrame;
  51278. },
  51279. enumerable: true,
  51280. configurable: true
  51281. });
  51282. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51283. /**
  51284. * Gets the weight of the runtime animation
  51285. */
  51286. get: function () {
  51287. return this._weight;
  51288. },
  51289. enumerable: true,
  51290. configurable: true
  51291. });
  51292. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51293. /**
  51294. * Gets the original value of the runtime animation
  51295. */
  51296. get: function () {
  51297. return this._originalValue;
  51298. },
  51299. enumerable: true,
  51300. configurable: true
  51301. });
  51302. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51303. /**
  51304. * Gets the current value of the runtime animation
  51305. */
  51306. get: function () {
  51307. return this._currentValue;
  51308. },
  51309. enumerable: true,
  51310. configurable: true
  51311. });
  51312. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51313. /**
  51314. * Gets the target path of the runtime animation
  51315. */
  51316. get: function () {
  51317. return this._targetPath;
  51318. },
  51319. enumerable: true,
  51320. configurable: true
  51321. });
  51322. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51323. /**
  51324. * Gets the actual target of the runtime animation
  51325. */
  51326. get: function () {
  51327. return this._activeTarget;
  51328. },
  51329. enumerable: true,
  51330. configurable: true
  51331. });
  51332. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51333. /**
  51334. * Gets the animation from the runtime animation
  51335. */
  51336. get: function () {
  51337. return this._animation;
  51338. },
  51339. enumerable: true,
  51340. configurable: true
  51341. });
  51342. /**
  51343. * Resets the runtime animation to the beginning
  51344. */
  51345. RuntimeAnimation.prototype.reset = function () {
  51346. this._offsetsCache = {};
  51347. this._highLimitsCache = {};
  51348. this._currentFrame = 0;
  51349. this._blendingFactor = 0;
  51350. this._originalValue = null;
  51351. };
  51352. /**
  51353. * Specifies if the runtime animation is stopped
  51354. * @returns Boolean specifying if the runtime animation is stopped
  51355. */
  51356. RuntimeAnimation.prototype.isStopped = function () {
  51357. return this._stopped;
  51358. };
  51359. /**
  51360. * Disposes of the runtime animation
  51361. */
  51362. RuntimeAnimation.prototype.dispose = function () {
  51363. var index = this._animation.runtimeAnimations.indexOf(this);
  51364. if (index > -1) {
  51365. this._animation.runtimeAnimations.splice(index, 1);
  51366. }
  51367. };
  51368. /**
  51369. * Interpolates the animation from the current frame
  51370. * @param currentFrame The frame to interpolate the animation to
  51371. * @param repeatCount The number of times that the animation should loop
  51372. * @param loopMode The type of looping mode to use
  51373. * @param offsetValue Animation offset value
  51374. * @param highLimitValue The high limit value
  51375. * @returns The interpolated value
  51376. */
  51377. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51378. this._currentFrame = currentFrame;
  51379. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51380. this._workValue = BABYLON.Matrix.Zero();
  51381. }
  51382. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51383. };
  51384. /**
  51385. * Affect the interpolated value to the target
  51386. * @param currentValue defines the value computed by the animation
  51387. * @param weight defines the weight to apply to this value
  51388. */
  51389. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51390. if (weight === void 0) { weight = 1.0; }
  51391. if (this._target instanceof Array) {
  51392. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51393. var target = _a[_i];
  51394. this._setValue(target, currentValue, weight);
  51395. }
  51396. }
  51397. else {
  51398. this._setValue(this._target, currentValue, weight);
  51399. }
  51400. };
  51401. /**
  51402. * Sets the value of the runtime animation
  51403. * @param target The target property of the runtime animation
  51404. * @param currentValue The current value to use for the runtime animation
  51405. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51406. */
  51407. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51408. if (weight === void 0) { weight = 1.0; }
  51409. // Set value
  51410. var path;
  51411. var destination;
  51412. var targetPropertyPath = this._animation.targetPropertyPath;
  51413. if (targetPropertyPath.length > 1) {
  51414. var property = target[targetPropertyPath[0]];
  51415. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51416. property = property[targetPropertyPath[index]];
  51417. }
  51418. path = targetPropertyPath[targetPropertyPath.length - 1];
  51419. destination = property;
  51420. }
  51421. else {
  51422. path = targetPropertyPath[0];
  51423. destination = target;
  51424. }
  51425. this._targetPath = path;
  51426. this._activeTarget = destination;
  51427. this._weight = weight;
  51428. // Blending
  51429. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51430. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51431. if (enableBlending && this._blendingFactor <= 1.0) {
  51432. if (!this._originalBlendValue) {
  51433. var originalValue = destination[path];
  51434. if (originalValue.clone) {
  51435. this._originalBlendValue = originalValue.clone();
  51436. }
  51437. else {
  51438. this._originalBlendValue = originalValue;
  51439. }
  51440. }
  51441. }
  51442. if (weight !== -1.0) {
  51443. if (!this._originalValue) {
  51444. var originalValue = void 0;
  51445. if (destination.getRestPose) { // For bones
  51446. originalValue = destination.getRestPose();
  51447. }
  51448. else {
  51449. originalValue = destination[path];
  51450. }
  51451. if (originalValue.clone) {
  51452. this._originalValue = originalValue.clone();
  51453. }
  51454. else {
  51455. this._originalValue = originalValue;
  51456. }
  51457. }
  51458. }
  51459. if (enableBlending && this._blendingFactor <= 1.0) {
  51460. if (this._originalBlendValue.m) { // Matrix
  51461. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51462. if (this._currentValue) {
  51463. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51464. }
  51465. else {
  51466. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51467. }
  51468. }
  51469. else {
  51470. if (this._currentValue) {
  51471. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51472. }
  51473. else {
  51474. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51475. }
  51476. }
  51477. }
  51478. else {
  51479. var constructor = this._originalBlendValue.constructor;
  51480. if (constructor.Lerp) { // Lerp supported
  51481. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51482. }
  51483. else if (constructor.Slerp) { // Slerp supported
  51484. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51485. }
  51486. else if (this._originalBlendValue.toFixed) { // Number
  51487. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51488. }
  51489. else { // Blending not supported
  51490. this._currentValue = currentValue;
  51491. }
  51492. }
  51493. this._blendingFactor += blendingSpeed;
  51494. }
  51495. else {
  51496. this._currentValue = currentValue;
  51497. }
  51498. if (weight !== -1.0) {
  51499. this._scene._registerTargetForLateAnimationBinding(this);
  51500. }
  51501. else {
  51502. destination[path] = this._currentValue;
  51503. }
  51504. if (target.markAsDirty) {
  51505. target.markAsDirty(this._animation.targetProperty);
  51506. }
  51507. };
  51508. /**
  51509. * Gets the loop pmode of the runtime animation
  51510. * @returns Loop Mode
  51511. */
  51512. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51513. if (this._target && this._target.animationPropertiesOverride) {
  51514. return this._target.animationPropertiesOverride.loopMode;
  51515. }
  51516. return this._animation.loopMode;
  51517. };
  51518. /**
  51519. * Move the current animation to a given frame
  51520. * @param frame defines the frame to move to
  51521. */
  51522. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51523. var keys = this._animation.getKeys();
  51524. if (frame < keys[0].frame) {
  51525. frame = keys[0].frame;
  51526. }
  51527. else if (frame > keys[keys.length - 1].frame) {
  51528. frame = keys[keys.length - 1].frame;
  51529. }
  51530. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51531. this.setValue(currentValue, -1);
  51532. };
  51533. /**
  51534. * @ignore Internal use only
  51535. */
  51536. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51537. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51538. this._ratioOffset = this._previousRatio - newRatio;
  51539. };
  51540. /**
  51541. * Execute the current animation
  51542. * @param delay defines the delay to add to the current frame
  51543. * @param from defines the lower bound of the animation range
  51544. * @param to defines the upper bound of the animation range
  51545. * @param loop defines if the current animation must loop
  51546. * @param speedRatio defines the current speed ratio
  51547. * @param weight defines the weight of the animation (default is -1 so no weight)
  51548. * @returns a boolean indicating if the animation has ended
  51549. */
  51550. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51551. if (weight === void 0) { weight = -1.0; }
  51552. var targetPropertyPath = this._animation.targetPropertyPath;
  51553. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51554. this._stopped = true;
  51555. return false;
  51556. }
  51557. var returnValue = true;
  51558. var keys = this._animation.getKeys();
  51559. // Adding a start key at frame 0 if missing
  51560. if (keys[0].frame !== 0) {
  51561. var newKey = { frame: 0, value: keys[0].value };
  51562. keys.splice(0, 0, newKey);
  51563. }
  51564. // Check limits
  51565. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51566. from = keys[0].frame;
  51567. }
  51568. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51569. to = keys[keys.length - 1].frame;
  51570. }
  51571. //to and from cannot be the same key
  51572. if (from === to) {
  51573. if (from > keys[0].frame) {
  51574. from--;
  51575. }
  51576. else if (to < keys[keys.length - 1].frame) {
  51577. to++;
  51578. }
  51579. }
  51580. // Compute ratio
  51581. var range = to - from;
  51582. var offsetValue;
  51583. // ratio represents the frame delta between from and to
  51584. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51585. var highLimitValue = 0;
  51586. this._previousDelay = delay;
  51587. this._previousRatio = ratio;
  51588. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51589. returnValue = false;
  51590. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51591. }
  51592. else {
  51593. // Get max value if required
  51594. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51595. var keyOffset = to.toString() + from.toString();
  51596. if (!this._offsetsCache[keyOffset]) {
  51597. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51598. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51599. switch (this._animation.dataType) {
  51600. // Float
  51601. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51602. this._offsetsCache[keyOffset] = toValue - fromValue;
  51603. break;
  51604. // Quaternion
  51605. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51606. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51607. break;
  51608. // Vector3
  51609. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51610. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51611. // Vector2
  51612. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51613. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51614. // Size
  51615. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51616. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51617. // Color3
  51618. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51619. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51620. default:
  51621. break;
  51622. }
  51623. this._highLimitsCache[keyOffset] = toValue;
  51624. }
  51625. highLimitValue = this._highLimitsCache[keyOffset];
  51626. offsetValue = this._offsetsCache[keyOffset];
  51627. }
  51628. }
  51629. if (offsetValue === undefined) {
  51630. switch (this._animation.dataType) {
  51631. // Float
  51632. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51633. offsetValue = 0;
  51634. break;
  51635. // Quaternion
  51636. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51637. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51638. break;
  51639. // Vector3
  51640. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51641. offsetValue = BABYLON.Vector3.Zero();
  51642. break;
  51643. // Vector2
  51644. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51645. offsetValue = BABYLON.Vector2.Zero();
  51646. break;
  51647. // Size
  51648. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51649. offsetValue = BABYLON.Size.Zero();
  51650. break;
  51651. // Color3
  51652. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51653. offsetValue = BABYLON.Color3.Black();
  51654. }
  51655. }
  51656. // Compute value
  51657. var repeatCount = (ratio / range) >> 0;
  51658. var currentFrame = returnValue ? from + ratio % range : to;
  51659. // Need to normalize?
  51660. if (this._host && this._host.syncRoot) {
  51661. var syncRoot = this._host.syncRoot;
  51662. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51663. currentFrame = from + (to - from) * hostNormalizedFrame;
  51664. }
  51665. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51666. // Set value
  51667. this.setValue(currentValue, weight);
  51668. // Check events
  51669. var events = this._animation.getEvents();
  51670. for (var index = 0; index < events.length; index++) {
  51671. // Make sure current frame has passed event frame and that event frame is within the current range
  51672. // Also, handle both forward and reverse animations
  51673. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51674. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51675. var event = events[index];
  51676. if (!event.isDone) {
  51677. // If event should be done only once, remove it.
  51678. if (event.onlyOnce) {
  51679. events.splice(index, 1);
  51680. index--;
  51681. }
  51682. event.isDone = true;
  51683. event.action();
  51684. } // Don't do anything if the event has already be done.
  51685. }
  51686. else if (events[index].isDone && !events[index].onlyOnce) {
  51687. // reset event, the animation is looping
  51688. events[index].isDone = false;
  51689. }
  51690. }
  51691. if (!returnValue) {
  51692. this._stopped = true;
  51693. }
  51694. return returnValue;
  51695. };
  51696. return RuntimeAnimation;
  51697. }());
  51698. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51699. })(BABYLON || (BABYLON = {}));
  51700. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51701. var BABYLON;
  51702. (function (BABYLON) {
  51703. var Animatable = /** @class */ (function () {
  51704. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51705. if (fromFrame === void 0) { fromFrame = 0; }
  51706. if (toFrame === void 0) { toFrame = 100; }
  51707. if (loopAnimation === void 0) { loopAnimation = false; }
  51708. if (speedRatio === void 0) { speedRatio = 1.0; }
  51709. this.target = target;
  51710. this.fromFrame = fromFrame;
  51711. this.toFrame = toFrame;
  51712. this.loopAnimation = loopAnimation;
  51713. this.onAnimationEnd = onAnimationEnd;
  51714. this._localDelayOffset = null;
  51715. this._pausedDelay = null;
  51716. this._runtimeAnimations = new Array();
  51717. this._paused = false;
  51718. this._speedRatio = 1;
  51719. this._weight = -1.0;
  51720. this.animationStarted = false;
  51721. this._scene = scene;
  51722. if (animations) {
  51723. this.appendAnimations(target, animations);
  51724. }
  51725. this._speedRatio = speedRatio;
  51726. scene._activeAnimatables.push(this);
  51727. }
  51728. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51729. /**
  51730. * Gets the root Animatable used to synchronize and normalize animations
  51731. */
  51732. get: function () {
  51733. return this._syncRoot;
  51734. },
  51735. enumerable: true,
  51736. configurable: true
  51737. });
  51738. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51739. /**
  51740. * Gets the current frame of the first RuntimeAnimation
  51741. * Used to synchronize Animatables
  51742. */
  51743. get: function () {
  51744. if (this._runtimeAnimations.length === 0) {
  51745. return 0;
  51746. }
  51747. return this._runtimeAnimations[0].currentFrame;
  51748. },
  51749. enumerable: true,
  51750. configurable: true
  51751. });
  51752. Object.defineProperty(Animatable.prototype, "weight", {
  51753. /**
  51754. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51755. */
  51756. get: function () {
  51757. return this._weight;
  51758. },
  51759. set: function (value) {
  51760. if (value === -1) { // -1 is ok and means no weight
  51761. this._weight = -1;
  51762. return;
  51763. }
  51764. // Else weight must be in [0, 1] range
  51765. this._weight = Math.min(Math.max(value, 0), 1.0);
  51766. },
  51767. enumerable: true,
  51768. configurable: true
  51769. });
  51770. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51771. /**
  51772. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51773. */
  51774. get: function () {
  51775. return this._speedRatio;
  51776. },
  51777. set: function (value) {
  51778. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51779. var animation = this._runtimeAnimations[index];
  51780. animation._prepareForSpeedRatioChange(value);
  51781. }
  51782. this._speedRatio = value;
  51783. },
  51784. enumerable: true,
  51785. configurable: true
  51786. });
  51787. // Methods
  51788. /**
  51789. * Synchronize and normalize current Animatable with a source Animatable
  51790. * This is useful when using animation weights and when animations are not of the same length
  51791. * @param root defines the root Animatable to synchronize with
  51792. * @returns the current Animatable
  51793. */
  51794. Animatable.prototype.syncWith = function (root) {
  51795. this._syncRoot = root;
  51796. if (root) {
  51797. // Make sure this animatable will animate after the root
  51798. var index = this._scene._activeAnimatables.indexOf(this);
  51799. if (index > -1) {
  51800. this._scene._activeAnimatables.splice(index, 1);
  51801. this._scene._activeAnimatables.push(this);
  51802. }
  51803. }
  51804. return this;
  51805. };
  51806. Animatable.prototype.getAnimations = function () {
  51807. return this._runtimeAnimations;
  51808. };
  51809. Animatable.prototype.appendAnimations = function (target, animations) {
  51810. for (var index = 0; index < animations.length; index++) {
  51811. var animation = animations[index];
  51812. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51813. }
  51814. };
  51815. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51816. var runtimeAnimations = this._runtimeAnimations;
  51817. for (var index = 0; index < runtimeAnimations.length; index++) {
  51818. if (runtimeAnimations[index].animation.targetProperty === property) {
  51819. return runtimeAnimations[index].animation;
  51820. }
  51821. }
  51822. return null;
  51823. };
  51824. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51825. var runtimeAnimations = this._runtimeAnimations;
  51826. for (var index = 0; index < runtimeAnimations.length; index++) {
  51827. if (runtimeAnimations[index].animation.targetProperty === property) {
  51828. return runtimeAnimations[index];
  51829. }
  51830. }
  51831. return null;
  51832. };
  51833. Animatable.prototype.reset = function () {
  51834. var runtimeAnimations = this._runtimeAnimations;
  51835. for (var index = 0; index < runtimeAnimations.length; index++) {
  51836. runtimeAnimations[index].reset();
  51837. }
  51838. // Reset to original value
  51839. for (index = 0; index < runtimeAnimations.length; index++) {
  51840. var animation = runtimeAnimations[index];
  51841. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  51842. }
  51843. this._localDelayOffset = null;
  51844. this._pausedDelay = null;
  51845. };
  51846. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51847. var runtimeAnimations = this._runtimeAnimations;
  51848. for (var index = 0; index < runtimeAnimations.length; index++) {
  51849. runtimeAnimations[index].animation.enableBlending = true;
  51850. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51851. }
  51852. };
  51853. Animatable.prototype.disableBlending = function () {
  51854. var runtimeAnimations = this._runtimeAnimations;
  51855. for (var index = 0; index < runtimeAnimations.length; index++) {
  51856. runtimeAnimations[index].animation.enableBlending = false;
  51857. }
  51858. };
  51859. Animatable.prototype.goToFrame = function (frame) {
  51860. var runtimeAnimations = this._runtimeAnimations;
  51861. if (runtimeAnimations[0]) {
  51862. var fps = runtimeAnimations[0].animation.framePerSecond;
  51863. var currentFrame = runtimeAnimations[0].currentFrame;
  51864. var adjustTime = frame - currentFrame;
  51865. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51866. if (this._localDelayOffset === null) {
  51867. this._localDelayOffset = 0;
  51868. }
  51869. this._localDelayOffset -= delay;
  51870. }
  51871. for (var index = 0; index < runtimeAnimations.length; index++) {
  51872. runtimeAnimations[index].goToFrame(frame);
  51873. }
  51874. };
  51875. Animatable.prototype.pause = function () {
  51876. if (this._paused) {
  51877. return;
  51878. }
  51879. this._paused = true;
  51880. };
  51881. Animatable.prototype.restart = function () {
  51882. this._paused = false;
  51883. };
  51884. Animatable.prototype.stop = function (animationName) {
  51885. if (animationName) {
  51886. var idx = this._scene._activeAnimatables.indexOf(this);
  51887. if (idx > -1) {
  51888. var runtimeAnimations = this._runtimeAnimations;
  51889. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51890. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51891. continue;
  51892. }
  51893. runtimeAnimations[index].dispose();
  51894. runtimeAnimations.splice(index, 1);
  51895. }
  51896. if (runtimeAnimations.length == 0) {
  51897. this._scene._activeAnimatables.splice(idx, 1);
  51898. if (this.onAnimationEnd) {
  51899. this.onAnimationEnd();
  51900. }
  51901. }
  51902. }
  51903. }
  51904. else {
  51905. var index = this._scene._activeAnimatables.indexOf(this);
  51906. if (index > -1) {
  51907. this._scene._activeAnimatables.splice(index, 1);
  51908. var runtimeAnimations = this._runtimeAnimations;
  51909. for (var index = 0; index < runtimeAnimations.length; index++) {
  51910. runtimeAnimations[index].dispose();
  51911. }
  51912. if (this.onAnimationEnd) {
  51913. this.onAnimationEnd();
  51914. }
  51915. }
  51916. }
  51917. };
  51918. Animatable.prototype._animate = function (delay) {
  51919. if (this._paused) {
  51920. this.animationStarted = false;
  51921. if (this._pausedDelay === null) {
  51922. this._pausedDelay = delay;
  51923. }
  51924. return true;
  51925. }
  51926. if (this._localDelayOffset === null) {
  51927. this._localDelayOffset = delay;
  51928. this._pausedDelay = null;
  51929. }
  51930. else if (this._pausedDelay !== null) {
  51931. this._localDelayOffset += delay - this._pausedDelay;
  51932. this._pausedDelay = null;
  51933. }
  51934. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51935. return true;
  51936. }
  51937. // Animating
  51938. var running = false;
  51939. var runtimeAnimations = this._runtimeAnimations;
  51940. var index;
  51941. for (index = 0; index < runtimeAnimations.length; index++) {
  51942. var animation = runtimeAnimations[index];
  51943. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51944. running = running || isRunning;
  51945. }
  51946. this.animationStarted = running;
  51947. if (!running) {
  51948. // Remove from active animatables
  51949. index = this._scene._activeAnimatables.indexOf(this);
  51950. this._scene._activeAnimatables.splice(index, 1);
  51951. // Dispose all runtime animations
  51952. for (index = 0; index < runtimeAnimations.length; index++) {
  51953. runtimeAnimations[index].dispose();
  51954. }
  51955. }
  51956. if (!running && this.onAnimationEnd) {
  51957. this.onAnimationEnd();
  51958. this.onAnimationEnd = null;
  51959. }
  51960. return running;
  51961. };
  51962. return Animatable;
  51963. }());
  51964. BABYLON.Animatable = Animatable;
  51965. })(BABYLON || (BABYLON = {}));
  51966. //# sourceMappingURL=babylon.animatable.js.map
  51967. var BABYLON;
  51968. (function (BABYLON) {
  51969. var EasingFunction = /** @class */ (function () {
  51970. function EasingFunction() {
  51971. // Properties
  51972. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51973. }
  51974. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51975. get: function () {
  51976. return EasingFunction._EASINGMODE_EASEIN;
  51977. },
  51978. enumerable: true,
  51979. configurable: true
  51980. });
  51981. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51982. get: function () {
  51983. return EasingFunction._EASINGMODE_EASEOUT;
  51984. },
  51985. enumerable: true,
  51986. configurable: true
  51987. });
  51988. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51989. get: function () {
  51990. return EasingFunction._EASINGMODE_EASEINOUT;
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51996. var n = Math.min(Math.max(easingMode, 0), 2);
  51997. this._easingMode = n;
  51998. };
  51999. EasingFunction.prototype.getEasingMode = function () {
  52000. return this._easingMode;
  52001. };
  52002. EasingFunction.prototype.easeInCore = function (gradient) {
  52003. throw new Error('You must implement this method');
  52004. };
  52005. EasingFunction.prototype.ease = function (gradient) {
  52006. switch (this._easingMode) {
  52007. case EasingFunction.EASINGMODE_EASEIN:
  52008. return this.easeInCore(gradient);
  52009. case EasingFunction.EASINGMODE_EASEOUT:
  52010. return (1 - this.easeInCore(1 - gradient));
  52011. }
  52012. if (gradient >= 0.5) {
  52013. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52014. }
  52015. return (this.easeInCore(gradient * 2) * 0.5);
  52016. };
  52017. //Statics
  52018. EasingFunction._EASINGMODE_EASEIN = 0;
  52019. EasingFunction._EASINGMODE_EASEOUT = 1;
  52020. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52021. return EasingFunction;
  52022. }());
  52023. BABYLON.EasingFunction = EasingFunction;
  52024. var CircleEase = /** @class */ (function (_super) {
  52025. __extends(CircleEase, _super);
  52026. function CircleEase() {
  52027. return _super !== null && _super.apply(this, arguments) || this;
  52028. }
  52029. CircleEase.prototype.easeInCore = function (gradient) {
  52030. gradient = Math.max(0, Math.min(1, gradient));
  52031. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52032. };
  52033. return CircleEase;
  52034. }(EasingFunction));
  52035. BABYLON.CircleEase = CircleEase;
  52036. var BackEase = /** @class */ (function (_super) {
  52037. __extends(BackEase, _super);
  52038. function BackEase(amplitude) {
  52039. if (amplitude === void 0) { amplitude = 1; }
  52040. var _this = _super.call(this) || this;
  52041. _this.amplitude = amplitude;
  52042. return _this;
  52043. }
  52044. BackEase.prototype.easeInCore = function (gradient) {
  52045. var num = Math.max(0, this.amplitude);
  52046. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52047. };
  52048. return BackEase;
  52049. }(EasingFunction));
  52050. BABYLON.BackEase = BackEase;
  52051. var BounceEase = /** @class */ (function (_super) {
  52052. __extends(BounceEase, _super);
  52053. function BounceEase(bounces, bounciness) {
  52054. if (bounces === void 0) { bounces = 3; }
  52055. if (bounciness === void 0) { bounciness = 2; }
  52056. var _this = _super.call(this) || this;
  52057. _this.bounces = bounces;
  52058. _this.bounciness = bounciness;
  52059. return _this;
  52060. }
  52061. BounceEase.prototype.easeInCore = function (gradient) {
  52062. var y = Math.max(0.0, this.bounces);
  52063. var bounciness = this.bounciness;
  52064. if (bounciness <= 1.0) {
  52065. bounciness = 1.001;
  52066. }
  52067. var num9 = Math.pow(bounciness, y);
  52068. var num5 = 1.0 - bounciness;
  52069. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52070. var num15 = gradient * num4;
  52071. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52072. var num3 = Math.floor(num65);
  52073. var num13 = num3 + 1.0;
  52074. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52075. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52076. var num7 = (num8 + num12) * 0.5;
  52077. var num6 = gradient - num7;
  52078. var num2 = num7 - num8;
  52079. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52080. };
  52081. return BounceEase;
  52082. }(EasingFunction));
  52083. BABYLON.BounceEase = BounceEase;
  52084. var CubicEase = /** @class */ (function (_super) {
  52085. __extends(CubicEase, _super);
  52086. function CubicEase() {
  52087. return _super !== null && _super.apply(this, arguments) || this;
  52088. }
  52089. CubicEase.prototype.easeInCore = function (gradient) {
  52090. return (gradient * gradient * gradient);
  52091. };
  52092. return CubicEase;
  52093. }(EasingFunction));
  52094. BABYLON.CubicEase = CubicEase;
  52095. var ElasticEase = /** @class */ (function (_super) {
  52096. __extends(ElasticEase, _super);
  52097. function ElasticEase(oscillations, springiness) {
  52098. if (oscillations === void 0) { oscillations = 3; }
  52099. if (springiness === void 0) { springiness = 3; }
  52100. var _this = _super.call(this) || this;
  52101. _this.oscillations = oscillations;
  52102. _this.springiness = springiness;
  52103. return _this;
  52104. }
  52105. ElasticEase.prototype.easeInCore = function (gradient) {
  52106. var num2;
  52107. var num3 = Math.max(0.0, this.oscillations);
  52108. var num = Math.max(0.0, this.springiness);
  52109. if (num == 0) {
  52110. num2 = gradient;
  52111. }
  52112. else {
  52113. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52114. }
  52115. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52116. };
  52117. return ElasticEase;
  52118. }(EasingFunction));
  52119. BABYLON.ElasticEase = ElasticEase;
  52120. var ExponentialEase = /** @class */ (function (_super) {
  52121. __extends(ExponentialEase, _super);
  52122. function ExponentialEase(exponent) {
  52123. if (exponent === void 0) { exponent = 2; }
  52124. var _this = _super.call(this) || this;
  52125. _this.exponent = exponent;
  52126. return _this;
  52127. }
  52128. ExponentialEase.prototype.easeInCore = function (gradient) {
  52129. if (this.exponent <= 0) {
  52130. return gradient;
  52131. }
  52132. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52133. };
  52134. return ExponentialEase;
  52135. }(EasingFunction));
  52136. BABYLON.ExponentialEase = ExponentialEase;
  52137. var PowerEase = /** @class */ (function (_super) {
  52138. __extends(PowerEase, _super);
  52139. function PowerEase(power) {
  52140. if (power === void 0) { power = 2; }
  52141. var _this = _super.call(this) || this;
  52142. _this.power = power;
  52143. return _this;
  52144. }
  52145. PowerEase.prototype.easeInCore = function (gradient) {
  52146. var y = Math.max(0.0, this.power);
  52147. return Math.pow(gradient, y);
  52148. };
  52149. return PowerEase;
  52150. }(EasingFunction));
  52151. BABYLON.PowerEase = PowerEase;
  52152. var QuadraticEase = /** @class */ (function (_super) {
  52153. __extends(QuadraticEase, _super);
  52154. function QuadraticEase() {
  52155. return _super !== null && _super.apply(this, arguments) || this;
  52156. }
  52157. QuadraticEase.prototype.easeInCore = function (gradient) {
  52158. return (gradient * gradient);
  52159. };
  52160. return QuadraticEase;
  52161. }(EasingFunction));
  52162. BABYLON.QuadraticEase = QuadraticEase;
  52163. var QuarticEase = /** @class */ (function (_super) {
  52164. __extends(QuarticEase, _super);
  52165. function QuarticEase() {
  52166. return _super !== null && _super.apply(this, arguments) || this;
  52167. }
  52168. QuarticEase.prototype.easeInCore = function (gradient) {
  52169. return (gradient * gradient * gradient * gradient);
  52170. };
  52171. return QuarticEase;
  52172. }(EasingFunction));
  52173. BABYLON.QuarticEase = QuarticEase;
  52174. var QuinticEase = /** @class */ (function (_super) {
  52175. __extends(QuinticEase, _super);
  52176. function QuinticEase() {
  52177. return _super !== null && _super.apply(this, arguments) || this;
  52178. }
  52179. QuinticEase.prototype.easeInCore = function (gradient) {
  52180. return (gradient * gradient * gradient * gradient * gradient);
  52181. };
  52182. return QuinticEase;
  52183. }(EasingFunction));
  52184. BABYLON.QuinticEase = QuinticEase;
  52185. var SineEase = /** @class */ (function (_super) {
  52186. __extends(SineEase, _super);
  52187. function SineEase() {
  52188. return _super !== null && _super.apply(this, arguments) || this;
  52189. }
  52190. SineEase.prototype.easeInCore = function (gradient) {
  52191. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52192. };
  52193. return SineEase;
  52194. }(EasingFunction));
  52195. BABYLON.SineEase = SineEase;
  52196. var BezierCurveEase = /** @class */ (function (_super) {
  52197. __extends(BezierCurveEase, _super);
  52198. function BezierCurveEase(x1, y1, x2, y2) {
  52199. if (x1 === void 0) { x1 = 0; }
  52200. if (y1 === void 0) { y1 = 0; }
  52201. if (x2 === void 0) { x2 = 1; }
  52202. if (y2 === void 0) { y2 = 1; }
  52203. var _this = _super.call(this) || this;
  52204. _this.x1 = x1;
  52205. _this.y1 = y1;
  52206. _this.x2 = x2;
  52207. _this.y2 = y2;
  52208. return _this;
  52209. }
  52210. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52211. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52212. };
  52213. return BezierCurveEase;
  52214. }(EasingFunction));
  52215. BABYLON.BezierCurveEase = BezierCurveEase;
  52216. })(BABYLON || (BABYLON = {}));
  52217. //# sourceMappingURL=babylon.easing.js.map
  52218. var BABYLON;
  52219. (function (BABYLON) {
  52220. /**
  52221. * A Condition applied to an Action
  52222. */
  52223. var Condition = /** @class */ (function () {
  52224. /**
  52225. * Creates a new Condition
  52226. * @param actionManager the manager of the action the condition is applied to
  52227. */
  52228. function Condition(actionManager) {
  52229. this._actionManager = actionManager;
  52230. }
  52231. /**
  52232. * Check if the current condition is valid
  52233. * @returns a boolean
  52234. */
  52235. Condition.prototype.isValid = function () {
  52236. return true;
  52237. };
  52238. /**
  52239. * Internal only
  52240. * @ignore
  52241. */
  52242. Condition.prototype._getProperty = function (propertyPath) {
  52243. return this._actionManager._getProperty(propertyPath);
  52244. };
  52245. /**
  52246. * Internal only
  52247. * @ignore
  52248. */
  52249. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52250. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52251. };
  52252. /**
  52253. * Serialize placeholder for child classes
  52254. * @returns the serialized object
  52255. */
  52256. Condition.prototype.serialize = function () {
  52257. };
  52258. /**
  52259. * Internal only
  52260. * @ignore
  52261. */
  52262. Condition.prototype._serialize = function (serializedCondition) {
  52263. return {
  52264. type: 2,
  52265. children: [],
  52266. name: serializedCondition.name,
  52267. properties: serializedCondition.properties
  52268. };
  52269. };
  52270. return Condition;
  52271. }());
  52272. BABYLON.Condition = Condition;
  52273. /**
  52274. * Defines specific conditional operators as extensions of Condition
  52275. */
  52276. var ValueCondition = /** @class */ (function (_super) {
  52277. __extends(ValueCondition, _super);
  52278. /**
  52279. * Creates a new ValueCondition
  52280. * @param actionManager manager for the action the condition applies to
  52281. * @param target for the action
  52282. * @param propertyPath path to specify the property of the target the conditional operator uses
  52283. * @param value the value compared by the conditional operator against the current value of the property
  52284. * @param operator the conditional operator, default ValueCondition.IsEqual
  52285. */
  52286. function ValueCondition(actionManager, target,
  52287. /** path to specify the property of the target the conditional operator uses */
  52288. propertyPath,
  52289. /** the value compared by the conditional operator against the current value of the property */
  52290. value,
  52291. /** the conditional operator, default ValueCondition.IsEqual */
  52292. operator) {
  52293. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52294. var _this = _super.call(this, actionManager) || this;
  52295. _this.propertyPath = propertyPath;
  52296. _this.value = value;
  52297. _this.operator = operator;
  52298. _this._target = target;
  52299. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52300. _this._property = _this._getProperty(_this.propertyPath);
  52301. return _this;
  52302. }
  52303. Object.defineProperty(ValueCondition, "IsEqual", {
  52304. /**
  52305. * returns the number for IsEqual
  52306. */
  52307. get: function () {
  52308. return ValueCondition._IsEqual;
  52309. },
  52310. enumerable: true,
  52311. configurable: true
  52312. });
  52313. Object.defineProperty(ValueCondition, "IsDifferent", {
  52314. /**
  52315. * Returns the number for IsDifferent
  52316. */
  52317. get: function () {
  52318. return ValueCondition._IsDifferent;
  52319. },
  52320. enumerable: true,
  52321. configurable: true
  52322. });
  52323. Object.defineProperty(ValueCondition, "IsGreater", {
  52324. /**
  52325. * Returns the number for IsGreater
  52326. */
  52327. get: function () {
  52328. return ValueCondition._IsGreater;
  52329. },
  52330. enumerable: true,
  52331. configurable: true
  52332. });
  52333. Object.defineProperty(ValueCondition, "IsLesser", {
  52334. /**
  52335. * Returns the number for IsLesser
  52336. */
  52337. get: function () {
  52338. return ValueCondition._IsLesser;
  52339. },
  52340. enumerable: true,
  52341. configurable: true
  52342. });
  52343. /**
  52344. * Compares the given value with the property value for the specified conditional operator
  52345. * @returns the result of the comparison
  52346. */
  52347. ValueCondition.prototype.isValid = function () {
  52348. switch (this.operator) {
  52349. case ValueCondition.IsGreater:
  52350. return this._effectiveTarget[this._property] > this.value;
  52351. case ValueCondition.IsLesser:
  52352. return this._effectiveTarget[this._property] < this.value;
  52353. case ValueCondition.IsEqual:
  52354. case ValueCondition.IsDifferent:
  52355. var check;
  52356. if (this.value.equals) {
  52357. check = this.value.equals(this._effectiveTarget[this._property]);
  52358. }
  52359. else {
  52360. check = this.value === this._effectiveTarget[this._property];
  52361. }
  52362. return this.operator === ValueCondition.IsEqual ? check : !check;
  52363. }
  52364. return false;
  52365. };
  52366. /**
  52367. * Serialize the ValueCondition into a JSON compatible object
  52368. * @returns serialization object
  52369. */
  52370. ValueCondition.prototype.serialize = function () {
  52371. return this._serialize({
  52372. name: "ValueCondition",
  52373. properties: [
  52374. BABYLON.Action._GetTargetProperty(this._target),
  52375. { name: "propertyPath", value: this.propertyPath },
  52376. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52377. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52378. ]
  52379. });
  52380. };
  52381. /**
  52382. * Gets the name of the conditional operator for the ValueCondition
  52383. * @param operator the conditional operator
  52384. * @returns the name
  52385. */
  52386. ValueCondition.GetOperatorName = function (operator) {
  52387. switch (operator) {
  52388. case ValueCondition._IsEqual: return "IsEqual";
  52389. case ValueCondition._IsDifferent: return "IsDifferent";
  52390. case ValueCondition._IsGreater: return "IsGreater";
  52391. case ValueCondition._IsLesser: return "IsLesser";
  52392. default: return "";
  52393. }
  52394. };
  52395. /**
  52396. * Internal only
  52397. * @ignore
  52398. */
  52399. ValueCondition._IsEqual = 0;
  52400. /**
  52401. * Internal only
  52402. * @ignore
  52403. */
  52404. ValueCondition._IsDifferent = 1;
  52405. /**
  52406. * Internal only
  52407. * @ignore
  52408. */
  52409. ValueCondition._IsGreater = 2;
  52410. /**
  52411. * Internal only
  52412. * @ignore
  52413. */
  52414. ValueCondition._IsLesser = 3;
  52415. return ValueCondition;
  52416. }(Condition));
  52417. BABYLON.ValueCondition = ValueCondition;
  52418. /**
  52419. * Defines a predicate condition as an extension of Condition
  52420. */
  52421. var PredicateCondition = /** @class */ (function (_super) {
  52422. __extends(PredicateCondition, _super);
  52423. /**
  52424. * Creates a new PredicateCondition
  52425. * @param actionManager manager for the action the condition applies to
  52426. * @param predicate defines the predicate function used to validate the condition
  52427. */
  52428. function PredicateCondition(actionManager,
  52429. /** defines the predicate function used to validate the condition */
  52430. predicate) {
  52431. var _this = _super.call(this, actionManager) || this;
  52432. _this.predicate = predicate;
  52433. return _this;
  52434. }
  52435. /**
  52436. * @returns the validity of the predicate condition
  52437. */
  52438. PredicateCondition.prototype.isValid = function () {
  52439. return this.predicate();
  52440. };
  52441. return PredicateCondition;
  52442. }(Condition));
  52443. BABYLON.PredicateCondition = PredicateCondition;
  52444. /**
  52445. * Defines a state condition as an extension of Condition
  52446. */
  52447. var StateCondition = /** @class */ (function (_super) {
  52448. __extends(StateCondition, _super);
  52449. /**
  52450. * Creates a new StateCondition
  52451. * @param actionManager manager for the action the condition applies to
  52452. * @param target of the condition
  52453. * @param value to compare with target state
  52454. */
  52455. function StateCondition(actionManager, target, value) {
  52456. var _this = _super.call(this, actionManager) || this;
  52457. _this.value = value;
  52458. _this._target = target;
  52459. return _this;
  52460. }
  52461. /**
  52462. * @returns the validity of the state
  52463. */
  52464. StateCondition.prototype.isValid = function () {
  52465. return this._target.state === this.value;
  52466. };
  52467. /**
  52468. * Serialize the StateCondition into a JSON compatible object
  52469. * @returns serialization object
  52470. */
  52471. StateCondition.prototype.serialize = function () {
  52472. return this._serialize({
  52473. name: "StateCondition",
  52474. properties: [
  52475. BABYLON.Action._GetTargetProperty(this._target),
  52476. { name: "value", value: this.value }
  52477. ]
  52478. });
  52479. };
  52480. return StateCondition;
  52481. }(Condition));
  52482. BABYLON.StateCondition = StateCondition;
  52483. })(BABYLON || (BABYLON = {}));
  52484. //# sourceMappingURL=babylon.condition.js.map
  52485. var BABYLON;
  52486. (function (BABYLON) {
  52487. /**
  52488. * The action to be carried out following a trigger
  52489. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52490. */
  52491. var Action = /** @class */ (function () {
  52492. /**
  52493. * Creates a new Action
  52494. * @param triggerOptions the trigger, with or without parameters, for the action
  52495. * @param condition an optional determinant of action
  52496. */
  52497. function Action(triggerOptions, condition) {
  52498. this.triggerOptions = triggerOptions;
  52499. /**
  52500. * An event triggered prior to action being executed.
  52501. */
  52502. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52503. if (triggerOptions.parameter) {
  52504. this.trigger = triggerOptions.trigger;
  52505. this._triggerParameter = triggerOptions.parameter;
  52506. }
  52507. else {
  52508. this.trigger = triggerOptions;
  52509. }
  52510. this._nextActiveAction = this;
  52511. this._condition = condition;
  52512. }
  52513. /**
  52514. * Internal only
  52515. * @ignore
  52516. */
  52517. Action.prototype._prepare = function () {
  52518. };
  52519. /**
  52520. * Gets the trigger parameters
  52521. * @returns the trigger parameters
  52522. */
  52523. Action.prototype.getTriggerParameter = function () {
  52524. return this._triggerParameter;
  52525. };
  52526. /**
  52527. * Internal only - executes current action event
  52528. * @ignore
  52529. */
  52530. Action.prototype._executeCurrent = function (evt) {
  52531. if (this._nextActiveAction._condition) {
  52532. var condition = this._nextActiveAction._condition;
  52533. var currentRenderId = this._actionManager.getScene().getRenderId();
  52534. // We cache the current evaluation for the current frame
  52535. if (condition._evaluationId === currentRenderId) {
  52536. if (!condition._currentResult) {
  52537. return;
  52538. }
  52539. }
  52540. else {
  52541. condition._evaluationId = currentRenderId;
  52542. if (!condition.isValid()) {
  52543. condition._currentResult = false;
  52544. return;
  52545. }
  52546. condition._currentResult = true;
  52547. }
  52548. }
  52549. this.onBeforeExecuteObservable.notifyObservers(this);
  52550. this._nextActiveAction.execute(evt);
  52551. this.skipToNextActiveAction();
  52552. };
  52553. /**
  52554. * Execute placeholder for child classes
  52555. * @param evt optional action event
  52556. */
  52557. Action.prototype.execute = function (evt) {
  52558. };
  52559. /**
  52560. * Skips to next active action
  52561. */
  52562. Action.prototype.skipToNextActiveAction = function () {
  52563. if (this._nextActiveAction._child) {
  52564. if (!this._nextActiveAction._child._actionManager) {
  52565. this._nextActiveAction._child._actionManager = this._actionManager;
  52566. }
  52567. this._nextActiveAction = this._nextActiveAction._child;
  52568. }
  52569. else {
  52570. this._nextActiveAction = this;
  52571. }
  52572. };
  52573. /**
  52574. * Adds action to chain of actions, may be a DoNothingAction
  52575. * @param index The index of the attribute.
  52576. * @returns The action passed in
  52577. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52578. */
  52579. Action.prototype.then = function (action) {
  52580. this._child = action;
  52581. action._actionManager = this._actionManager;
  52582. action._prepare();
  52583. return action;
  52584. };
  52585. /**
  52586. * Internal only
  52587. * @ignore
  52588. */
  52589. Action.prototype._getProperty = function (propertyPath) {
  52590. return this._actionManager._getProperty(propertyPath);
  52591. };
  52592. /**
  52593. * Internal only
  52594. * @ignore
  52595. */
  52596. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52597. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52598. };
  52599. /**
  52600. * Serialize placeholder for child classes
  52601. * @param parent of child
  52602. * @returns the serialized object
  52603. */
  52604. Action.prototype.serialize = function (parent) {
  52605. };
  52606. /**
  52607. * Internal only called by serialize
  52608. * @ignore
  52609. */
  52610. Action.prototype._serialize = function (serializedAction, parent) {
  52611. var serializationObject = {
  52612. type: 1,
  52613. children: [],
  52614. name: serializedAction.name,
  52615. properties: serializedAction.properties || []
  52616. };
  52617. // Serialize child
  52618. if (this._child) {
  52619. this._child.serialize(serializationObject);
  52620. }
  52621. // Check if "this" has a condition
  52622. if (this._condition) {
  52623. var serializedCondition = this._condition.serialize();
  52624. serializedCondition.children.push(serializationObject);
  52625. if (parent) {
  52626. parent.children.push(serializedCondition);
  52627. }
  52628. return serializedCondition;
  52629. }
  52630. if (parent) {
  52631. parent.children.push(serializationObject);
  52632. }
  52633. return serializationObject;
  52634. };
  52635. /**
  52636. * Internal only
  52637. * @ignore
  52638. */
  52639. Action._SerializeValueAsString = function (value) {
  52640. if (typeof value === "number") {
  52641. return value.toString();
  52642. }
  52643. if (typeof value === "boolean") {
  52644. return value ? "true" : "false";
  52645. }
  52646. if (value instanceof BABYLON.Vector2) {
  52647. return value.x + ", " + value.y;
  52648. }
  52649. if (value instanceof BABYLON.Vector3) {
  52650. return value.x + ", " + value.y + ", " + value.z;
  52651. }
  52652. if (value instanceof BABYLON.Color3) {
  52653. return value.r + ", " + value.g + ", " + value.b;
  52654. }
  52655. if (value instanceof BABYLON.Color4) {
  52656. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52657. }
  52658. return value; // string
  52659. };
  52660. /**
  52661. * Internal only
  52662. * @ignore
  52663. */
  52664. Action._GetTargetProperty = function (target) {
  52665. return {
  52666. name: "target",
  52667. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52668. : target instanceof BABYLON.Light ? "LightProperties"
  52669. : target instanceof BABYLON.Camera ? "CameraProperties"
  52670. : "SceneProperties",
  52671. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52672. };
  52673. };
  52674. return Action;
  52675. }());
  52676. BABYLON.Action = Action;
  52677. })(BABYLON || (BABYLON = {}));
  52678. //# sourceMappingURL=babylon.action.js.map
  52679. var BABYLON;
  52680. (function (BABYLON) {
  52681. /**
  52682. * ActionEvent is the event being sent when an action is triggered.
  52683. */
  52684. var ActionEvent = /** @class */ (function () {
  52685. /**
  52686. * @param source The mesh or sprite that triggered the action.
  52687. * @param pointerX The X mouse cursor position at the time of the event
  52688. * @param pointerY The Y mouse cursor position at the time of the event
  52689. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52690. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52691. */
  52692. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  52693. this.source = source;
  52694. this.pointerX = pointerX;
  52695. this.pointerY = pointerY;
  52696. this.meshUnderPointer = meshUnderPointer;
  52697. this.sourceEvent = sourceEvent;
  52698. this.additionalData = additionalData;
  52699. }
  52700. /**
  52701. * Helper function to auto-create an ActionEvent from a source mesh.
  52702. * @param source The source mesh that triggered the event
  52703. * @param evt {Event} The original (browser) event
  52704. */
  52705. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52706. var scene = source.getScene();
  52707. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52708. };
  52709. /**
  52710. * Helper function to auto-create an ActionEvent from a source mesh.
  52711. * @param source The source sprite that triggered the event
  52712. * @param scene Scene associated with the sprite
  52713. * @param evt {Event} The original (browser) event
  52714. */
  52715. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52716. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52717. };
  52718. /**
  52719. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52720. * @param scene the scene where the event occurred
  52721. * @param evt {Event} The original (browser) event
  52722. */
  52723. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52724. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52725. };
  52726. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52727. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52728. };
  52729. return ActionEvent;
  52730. }());
  52731. BABYLON.ActionEvent = ActionEvent;
  52732. /**
  52733. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52734. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52735. */
  52736. var ActionManager = /** @class */ (function () {
  52737. function ActionManager(scene) {
  52738. // Members
  52739. this.actions = new Array();
  52740. this.hoverCursor = '';
  52741. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52742. scene._actionManagers.push(this);
  52743. }
  52744. Object.defineProperty(ActionManager, "NothingTrigger", {
  52745. get: function () {
  52746. return ActionManager._NothingTrigger;
  52747. },
  52748. enumerable: true,
  52749. configurable: true
  52750. });
  52751. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52752. get: function () {
  52753. return ActionManager._OnPickTrigger;
  52754. },
  52755. enumerable: true,
  52756. configurable: true
  52757. });
  52758. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52759. get: function () {
  52760. return ActionManager._OnLeftPickTrigger;
  52761. },
  52762. enumerable: true,
  52763. configurable: true
  52764. });
  52765. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52766. get: function () {
  52767. return ActionManager._OnRightPickTrigger;
  52768. },
  52769. enumerable: true,
  52770. configurable: true
  52771. });
  52772. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52773. get: function () {
  52774. return ActionManager._OnCenterPickTrigger;
  52775. },
  52776. enumerable: true,
  52777. configurable: true
  52778. });
  52779. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52780. get: function () {
  52781. return ActionManager._OnPickDownTrigger;
  52782. },
  52783. enumerable: true,
  52784. configurable: true
  52785. });
  52786. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52787. get: function () {
  52788. return ActionManager._OnDoublePickTrigger;
  52789. },
  52790. enumerable: true,
  52791. configurable: true
  52792. });
  52793. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52794. get: function () {
  52795. return ActionManager._OnPickUpTrigger;
  52796. },
  52797. enumerable: true,
  52798. configurable: true
  52799. });
  52800. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52801. /// This trigger will only be raised if you also declared a OnPickDown
  52802. get: function () {
  52803. return ActionManager._OnPickOutTrigger;
  52804. },
  52805. enumerable: true,
  52806. configurable: true
  52807. });
  52808. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52809. get: function () {
  52810. return ActionManager._OnLongPressTrigger;
  52811. },
  52812. enumerable: true,
  52813. configurable: true
  52814. });
  52815. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52816. get: function () {
  52817. return ActionManager._OnPointerOverTrigger;
  52818. },
  52819. enumerable: true,
  52820. configurable: true
  52821. });
  52822. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52823. get: function () {
  52824. return ActionManager._OnPointerOutTrigger;
  52825. },
  52826. enumerable: true,
  52827. configurable: true
  52828. });
  52829. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52830. get: function () {
  52831. return ActionManager._OnEveryFrameTrigger;
  52832. },
  52833. enumerable: true,
  52834. configurable: true
  52835. });
  52836. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52837. get: function () {
  52838. return ActionManager._OnIntersectionEnterTrigger;
  52839. },
  52840. enumerable: true,
  52841. configurable: true
  52842. });
  52843. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52844. get: function () {
  52845. return ActionManager._OnIntersectionExitTrigger;
  52846. },
  52847. enumerable: true,
  52848. configurable: true
  52849. });
  52850. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52851. get: function () {
  52852. return ActionManager._OnKeyDownTrigger;
  52853. },
  52854. enumerable: true,
  52855. configurable: true
  52856. });
  52857. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52858. get: function () {
  52859. return ActionManager._OnKeyUpTrigger;
  52860. },
  52861. enumerable: true,
  52862. configurable: true
  52863. });
  52864. // Methods
  52865. ActionManager.prototype.dispose = function () {
  52866. var index = this._scene._actionManagers.indexOf(this);
  52867. for (var i = 0; i < this.actions.length; i++) {
  52868. var action = this.actions[i];
  52869. ActionManager.Triggers[action.trigger]--;
  52870. if (ActionManager.Triggers[action.trigger] === 0) {
  52871. delete ActionManager.Triggers[action.trigger];
  52872. }
  52873. }
  52874. if (index > -1) {
  52875. this._scene._actionManagers.splice(index, 1);
  52876. }
  52877. };
  52878. ActionManager.prototype.getScene = function () {
  52879. return this._scene;
  52880. };
  52881. /**
  52882. * Does this action manager handles actions of any of the given triggers
  52883. * @param {number[]} triggers - the triggers to be tested
  52884. * @return {boolean} whether one (or more) of the triggers is handeled
  52885. */
  52886. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52887. for (var index = 0; index < this.actions.length; index++) {
  52888. var action = this.actions[index];
  52889. if (triggers.indexOf(action.trigger) > -1) {
  52890. return true;
  52891. }
  52892. }
  52893. return false;
  52894. };
  52895. /**
  52896. * Does this action manager handles actions of a given trigger
  52897. * @param trigger defines the trigger to be tested
  52898. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52899. * @return whether the trigger is handled
  52900. */
  52901. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52902. for (var index = 0; index < this.actions.length; index++) {
  52903. var action = this.actions[index];
  52904. if (action.trigger === trigger) {
  52905. if (parameterPredicate) {
  52906. if (parameterPredicate(action.getTriggerParameter())) {
  52907. return true;
  52908. }
  52909. }
  52910. else {
  52911. return true;
  52912. }
  52913. }
  52914. }
  52915. return false;
  52916. };
  52917. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52918. /**
  52919. * Does this action manager has pointer triggers
  52920. * @return {boolean} whether or not it has pointer triggers
  52921. */
  52922. get: function () {
  52923. for (var index = 0; index < this.actions.length; index++) {
  52924. var action = this.actions[index];
  52925. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52926. return true;
  52927. }
  52928. }
  52929. return false;
  52930. },
  52931. enumerable: true,
  52932. configurable: true
  52933. });
  52934. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52935. /**
  52936. * Does this action manager has pick triggers
  52937. * @return {boolean} whether or not it has pick triggers
  52938. */
  52939. get: function () {
  52940. for (var index = 0; index < this.actions.length; index++) {
  52941. var action = this.actions[index];
  52942. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52943. return true;
  52944. }
  52945. }
  52946. return false;
  52947. },
  52948. enumerable: true,
  52949. configurable: true
  52950. });
  52951. Object.defineProperty(ActionManager, "HasTriggers", {
  52952. /**
  52953. * Does exist one action manager with at least one trigger
  52954. * @return {boolean} whether or not it exists one action manager with one trigger
  52955. **/
  52956. get: function () {
  52957. for (var t in ActionManager.Triggers) {
  52958. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52959. return true;
  52960. }
  52961. }
  52962. return false;
  52963. },
  52964. enumerable: true,
  52965. configurable: true
  52966. });
  52967. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52968. /**
  52969. * Does exist one action manager with at least one pick trigger
  52970. * @return {boolean} whether or not it exists one action manager with one pick trigger
  52971. **/
  52972. get: function () {
  52973. for (var t in ActionManager.Triggers) {
  52974. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52975. var t_int = parseInt(t);
  52976. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52977. return true;
  52978. }
  52979. }
  52980. }
  52981. return false;
  52982. },
  52983. enumerable: true,
  52984. configurable: true
  52985. });
  52986. /**
  52987. * Does exist one action manager that handles actions of a given trigger
  52988. * @param {number} trigger - the trigger to be tested
  52989. * @return {boolean} whether the trigger is handeled by at least one action manager
  52990. **/
  52991. ActionManager.HasSpecificTrigger = function (trigger) {
  52992. for (var t in ActionManager.Triggers) {
  52993. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52994. var t_int = parseInt(t);
  52995. if (t_int === trigger) {
  52996. return true;
  52997. }
  52998. }
  52999. }
  53000. return false;
  53001. };
  53002. /**
  53003. * Registers an action to this action manager
  53004. * @param {BABYLON.Action} action - the action to be registered
  53005. * @return {BABYLON.Action} the action amended (prepared) after registration
  53006. */
  53007. ActionManager.prototype.registerAction = function (action) {
  53008. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53009. if (this.getScene().actionManager !== this) {
  53010. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53011. return null;
  53012. }
  53013. }
  53014. this.actions.push(action);
  53015. if (ActionManager.Triggers[action.trigger]) {
  53016. ActionManager.Triggers[action.trigger]++;
  53017. }
  53018. else {
  53019. ActionManager.Triggers[action.trigger] = 1;
  53020. }
  53021. action._actionManager = this;
  53022. action._prepare();
  53023. return action;
  53024. };
  53025. /**
  53026. * Unregisters an action to this action manager
  53027. * @param action The action to be unregistered
  53028. * @return whether the action has been unregistered
  53029. */
  53030. ActionManager.prototype.unregisterAction = function (action) {
  53031. var index = this.actions.indexOf(action);
  53032. if (index !== -1) {
  53033. this.actions.splice(index, 1);
  53034. ActionManager.Triggers[action.trigger] -= 1;
  53035. if (ActionManager.Triggers[action.trigger] === 0) {
  53036. delete ActionManager.Triggers[action.trigger];
  53037. }
  53038. delete action._actionManager;
  53039. return true;
  53040. }
  53041. return false;
  53042. };
  53043. /**
  53044. * Process a specific trigger
  53045. * @param {number} trigger - the trigger to process
  53046. * @param evt {BABYLON.ActionEvent} the event details to be processed
  53047. */
  53048. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53049. for (var index = 0; index < this.actions.length; index++) {
  53050. var action = this.actions[index];
  53051. if (action.trigger === trigger) {
  53052. if (evt) {
  53053. if (trigger === ActionManager.OnKeyUpTrigger
  53054. || trigger === ActionManager.OnKeyDownTrigger) {
  53055. var parameter = action.getTriggerParameter();
  53056. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53057. if (!parameter.toLowerCase) {
  53058. continue;
  53059. }
  53060. var lowerCase = parameter.toLowerCase();
  53061. if (lowerCase !== evt.sourceEvent.key) {
  53062. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53063. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53064. if (actualkey !== lowerCase) {
  53065. continue;
  53066. }
  53067. }
  53068. }
  53069. }
  53070. }
  53071. action._executeCurrent(evt);
  53072. }
  53073. }
  53074. };
  53075. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53076. var properties = propertyPath.split(".");
  53077. for (var index = 0; index < properties.length - 1; index++) {
  53078. target = target[properties[index]];
  53079. }
  53080. return target;
  53081. };
  53082. ActionManager.prototype._getProperty = function (propertyPath) {
  53083. var properties = propertyPath.split(".");
  53084. return properties[properties.length - 1];
  53085. };
  53086. ActionManager.prototype.serialize = function (name) {
  53087. var root = {
  53088. children: new Array(),
  53089. name: name,
  53090. type: 3,
  53091. properties: new Array() // Empty for root but required
  53092. };
  53093. for (var i = 0; i < this.actions.length; i++) {
  53094. var triggerObject = {
  53095. type: 0,
  53096. children: new Array(),
  53097. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53098. properties: new Array()
  53099. };
  53100. var triggerOptions = this.actions[i].triggerOptions;
  53101. if (triggerOptions && typeof triggerOptions !== "number") {
  53102. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53103. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53104. }
  53105. else {
  53106. var parameter = {};
  53107. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53108. if (triggerOptions.parameter.mesh) {
  53109. parameter._meshId = triggerOptions.parameter.mesh.id;
  53110. }
  53111. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53112. }
  53113. }
  53114. // Serialize child action, recursively
  53115. this.actions[i].serialize(triggerObject);
  53116. // Add serialized trigger
  53117. root.children.push(triggerObject);
  53118. }
  53119. return root;
  53120. };
  53121. ActionManager.Parse = function (parsedActions, object, scene) {
  53122. var actionManager = new ActionManager(scene);
  53123. if (object === null)
  53124. scene.actionManager = actionManager;
  53125. else
  53126. object.actionManager = actionManager;
  53127. // instanciate a new object
  53128. var instanciate = function (name, params) {
  53129. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53130. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53131. newInstance.constructor.apply(newInstance, params);
  53132. return newInstance;
  53133. };
  53134. var parseParameter = function (name, value, target, propertyPath) {
  53135. if (propertyPath === null) {
  53136. // String, boolean or float
  53137. var floatValue = parseFloat(value);
  53138. if (value === "true" || value === "false")
  53139. return value === "true";
  53140. else
  53141. return isNaN(floatValue) ? value : floatValue;
  53142. }
  53143. var effectiveTarget = propertyPath.split(".");
  53144. var values = value.split(",");
  53145. // Get effective Target
  53146. for (var i = 0; i < effectiveTarget.length; i++) {
  53147. target = target[effectiveTarget[i]];
  53148. }
  53149. // Return appropriate value with its type
  53150. if (typeof (target) === "boolean")
  53151. return values[0] === "true";
  53152. if (typeof (target) === "string")
  53153. return values[0];
  53154. // Parameters with multiple values such as Vector3 etc.
  53155. var split = new Array();
  53156. for (var i = 0; i < values.length; i++)
  53157. split.push(parseFloat(values[i]));
  53158. if (target instanceof BABYLON.Vector3)
  53159. return BABYLON.Vector3.FromArray(split);
  53160. if (target instanceof BABYLON.Vector4)
  53161. return BABYLON.Vector4.FromArray(split);
  53162. if (target instanceof BABYLON.Color3)
  53163. return BABYLON.Color3.FromArray(split);
  53164. if (target instanceof BABYLON.Color4)
  53165. return BABYLON.Color4.FromArray(split);
  53166. return parseFloat(values[0]);
  53167. };
  53168. // traverse graph per trigger
  53169. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53170. if (combineArray === void 0) { combineArray = null; }
  53171. if (parsedAction.detached)
  53172. return;
  53173. var parameters = new Array();
  53174. var target = null;
  53175. var propertyPath = null;
  53176. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53177. // Parameters
  53178. if (parsedAction.type === 2)
  53179. parameters.push(actionManager);
  53180. else
  53181. parameters.push(trigger);
  53182. if (combine) {
  53183. var actions = new Array();
  53184. for (var j = 0; j < parsedAction.combine.length; j++) {
  53185. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53186. }
  53187. parameters.push(actions);
  53188. }
  53189. else {
  53190. for (var i = 0; i < parsedAction.properties.length; i++) {
  53191. var value = parsedAction.properties[i].value;
  53192. var name = parsedAction.properties[i].name;
  53193. var targetType = parsedAction.properties[i].targetType;
  53194. if (name === "target")
  53195. if (targetType !== null && targetType === "SceneProperties")
  53196. value = target = scene;
  53197. else
  53198. value = target = scene.getNodeByName(value);
  53199. else if (name === "parent")
  53200. value = scene.getNodeByName(value);
  53201. else if (name === "sound")
  53202. value = scene.getSoundByName(value);
  53203. else if (name !== "propertyPath") {
  53204. if (parsedAction.type === 2 && name === "operator")
  53205. value = BABYLON.ValueCondition[value];
  53206. else
  53207. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53208. }
  53209. else {
  53210. propertyPath = value;
  53211. }
  53212. parameters.push(value);
  53213. }
  53214. }
  53215. if (combineArray === null) {
  53216. parameters.push(condition);
  53217. }
  53218. else {
  53219. parameters.push(null);
  53220. }
  53221. // If interpolate value action
  53222. if (parsedAction.name === "InterpolateValueAction") {
  53223. var param = parameters[parameters.length - 2];
  53224. parameters[parameters.length - 1] = param;
  53225. parameters[parameters.length - 2] = condition;
  53226. }
  53227. // Action or condition(s) and not CombineAction
  53228. var newAction = instanciate(parsedAction.name, parameters);
  53229. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53230. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53231. if (action)
  53232. action.then(nothing);
  53233. else
  53234. actionManager.registerAction(nothing);
  53235. action = nothing;
  53236. }
  53237. if (combineArray === null) {
  53238. if (newAction instanceof BABYLON.Condition) {
  53239. condition = newAction;
  53240. newAction = action;
  53241. }
  53242. else {
  53243. condition = null;
  53244. if (action)
  53245. action.then(newAction);
  53246. else
  53247. actionManager.registerAction(newAction);
  53248. }
  53249. }
  53250. else {
  53251. combineArray.push(newAction);
  53252. }
  53253. for (var i = 0; i < parsedAction.children.length; i++)
  53254. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53255. };
  53256. // triggers
  53257. for (var i = 0; i < parsedActions.children.length; i++) {
  53258. var triggerParams;
  53259. var trigger = parsedActions.children[i];
  53260. if (trigger.properties.length > 0) {
  53261. var param = trigger.properties[0].value;
  53262. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53263. if (value._meshId) {
  53264. value.mesh = scene.getMeshByID(value._meshId);
  53265. }
  53266. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53267. }
  53268. else
  53269. triggerParams = ActionManager[trigger.name];
  53270. for (var j = 0; j < trigger.children.length; j++) {
  53271. if (!trigger.detached)
  53272. traverse(trigger.children[j], triggerParams, null, null);
  53273. }
  53274. }
  53275. };
  53276. ActionManager.GetTriggerName = function (trigger) {
  53277. switch (trigger) {
  53278. case 0: return "NothingTrigger";
  53279. case 1: return "OnPickTrigger";
  53280. case 2: return "OnLeftPickTrigger";
  53281. case 3: return "OnRightPickTrigger";
  53282. case 4: return "OnCenterPickTrigger";
  53283. case 5: return "OnPickDownTrigger";
  53284. case 6: return "OnPickUpTrigger";
  53285. case 7: return "OnLongPressTrigger";
  53286. case 8: return "OnPointerOverTrigger";
  53287. case 9: return "OnPointerOutTrigger";
  53288. case 10: return "OnEveryFrameTrigger";
  53289. case 11: return "OnIntersectionEnterTrigger";
  53290. case 12: return "OnIntersectionExitTrigger";
  53291. case 13: return "OnKeyDownTrigger";
  53292. case 14: return "OnKeyUpTrigger";
  53293. case 15: return "OnPickOutTrigger";
  53294. default: return "";
  53295. }
  53296. };
  53297. // Statics
  53298. ActionManager._NothingTrigger = 0;
  53299. ActionManager._OnPickTrigger = 1;
  53300. ActionManager._OnLeftPickTrigger = 2;
  53301. ActionManager._OnRightPickTrigger = 3;
  53302. ActionManager._OnCenterPickTrigger = 4;
  53303. ActionManager._OnPickDownTrigger = 5;
  53304. ActionManager._OnDoublePickTrigger = 6;
  53305. ActionManager._OnPickUpTrigger = 7;
  53306. ActionManager._OnLongPressTrigger = 8;
  53307. ActionManager._OnPointerOverTrigger = 9;
  53308. ActionManager._OnPointerOutTrigger = 10;
  53309. ActionManager._OnEveryFrameTrigger = 11;
  53310. ActionManager._OnIntersectionEnterTrigger = 12;
  53311. ActionManager._OnIntersectionExitTrigger = 13;
  53312. ActionManager._OnKeyDownTrigger = 14;
  53313. ActionManager._OnKeyUpTrigger = 15;
  53314. ActionManager._OnPickOutTrigger = 16;
  53315. ActionManager.Triggers = {};
  53316. return ActionManager;
  53317. }());
  53318. BABYLON.ActionManager = ActionManager;
  53319. })(BABYLON || (BABYLON = {}));
  53320. //# sourceMappingURL=babylon.actionManager.js.map
  53321. var BABYLON;
  53322. (function (BABYLON) {
  53323. var InterpolateValueAction = /** @class */ (function (_super) {
  53324. __extends(InterpolateValueAction, _super);
  53325. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53326. if (duration === void 0) { duration = 1000; }
  53327. var _this = _super.call(this, triggerOptions, condition) || this;
  53328. _this.propertyPath = propertyPath;
  53329. _this.value = value;
  53330. _this.duration = duration;
  53331. _this.stopOtherAnimations = stopOtherAnimations;
  53332. _this.onInterpolationDone = onInterpolationDone;
  53333. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53334. _this._target = _this._effectiveTarget = target;
  53335. return _this;
  53336. }
  53337. InterpolateValueAction.prototype._prepare = function () {
  53338. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53339. this._property = this._getProperty(this.propertyPath);
  53340. };
  53341. InterpolateValueAction.prototype.execute = function () {
  53342. var _this = this;
  53343. var scene = this._actionManager.getScene();
  53344. var keys = [
  53345. {
  53346. frame: 0,
  53347. value: this._effectiveTarget[this._property]
  53348. }, {
  53349. frame: 100,
  53350. value: this.value
  53351. }
  53352. ];
  53353. var dataType;
  53354. if (typeof this.value === "number") {
  53355. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53356. }
  53357. else if (this.value instanceof BABYLON.Color3) {
  53358. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53359. }
  53360. else if (this.value instanceof BABYLON.Vector3) {
  53361. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53362. }
  53363. else if (this.value instanceof BABYLON.Matrix) {
  53364. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53365. }
  53366. else if (this.value instanceof BABYLON.Quaternion) {
  53367. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53368. }
  53369. else {
  53370. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53371. return;
  53372. }
  53373. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53374. animation.setKeys(keys);
  53375. if (this.stopOtherAnimations) {
  53376. scene.stopAnimation(this._effectiveTarget);
  53377. }
  53378. var wrapper = function () {
  53379. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53380. if (_this.onInterpolationDone) {
  53381. _this.onInterpolationDone();
  53382. }
  53383. };
  53384. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53385. };
  53386. InterpolateValueAction.prototype.serialize = function (parent) {
  53387. return _super.prototype._serialize.call(this, {
  53388. name: "InterpolateValueAction",
  53389. properties: [
  53390. BABYLON.Action._GetTargetProperty(this._target),
  53391. { name: "propertyPath", value: this.propertyPath },
  53392. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53393. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53394. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53395. ]
  53396. }, parent);
  53397. };
  53398. return InterpolateValueAction;
  53399. }(BABYLON.Action));
  53400. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53401. })(BABYLON || (BABYLON = {}));
  53402. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53403. var BABYLON;
  53404. (function (BABYLON) {
  53405. var SwitchBooleanAction = /** @class */ (function (_super) {
  53406. __extends(SwitchBooleanAction, _super);
  53407. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53408. var _this = _super.call(this, triggerOptions, condition) || this;
  53409. _this.propertyPath = propertyPath;
  53410. _this._target = _this._effectiveTarget = target;
  53411. return _this;
  53412. }
  53413. SwitchBooleanAction.prototype._prepare = function () {
  53414. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53415. this._property = this._getProperty(this.propertyPath);
  53416. };
  53417. SwitchBooleanAction.prototype.execute = function () {
  53418. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53419. };
  53420. SwitchBooleanAction.prototype.serialize = function (parent) {
  53421. return _super.prototype._serialize.call(this, {
  53422. name: "SwitchBooleanAction",
  53423. properties: [
  53424. BABYLON.Action._GetTargetProperty(this._target),
  53425. { name: "propertyPath", value: this.propertyPath }
  53426. ]
  53427. }, parent);
  53428. };
  53429. return SwitchBooleanAction;
  53430. }(BABYLON.Action));
  53431. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53432. var SetStateAction = /** @class */ (function (_super) {
  53433. __extends(SetStateAction, _super);
  53434. function SetStateAction(triggerOptions, target, value, condition) {
  53435. var _this = _super.call(this, triggerOptions, condition) || this;
  53436. _this.value = value;
  53437. _this._target = target;
  53438. return _this;
  53439. }
  53440. SetStateAction.prototype.execute = function () {
  53441. this._target.state = this.value;
  53442. };
  53443. SetStateAction.prototype.serialize = function (parent) {
  53444. return _super.prototype._serialize.call(this, {
  53445. name: "SetStateAction",
  53446. properties: [
  53447. BABYLON.Action._GetTargetProperty(this._target),
  53448. { name: "value", value: this.value }
  53449. ]
  53450. }, parent);
  53451. };
  53452. return SetStateAction;
  53453. }(BABYLON.Action));
  53454. BABYLON.SetStateAction = SetStateAction;
  53455. var SetValueAction = /** @class */ (function (_super) {
  53456. __extends(SetValueAction, _super);
  53457. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53458. var _this = _super.call(this, triggerOptions, condition) || this;
  53459. _this.propertyPath = propertyPath;
  53460. _this.value = value;
  53461. _this._target = _this._effectiveTarget = target;
  53462. return _this;
  53463. }
  53464. SetValueAction.prototype._prepare = function () {
  53465. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53466. this._property = this._getProperty(this.propertyPath);
  53467. };
  53468. SetValueAction.prototype.execute = function () {
  53469. this._effectiveTarget[this._property] = this.value;
  53470. if (this._target.markAsDirty) {
  53471. this._target.markAsDirty(this._property);
  53472. }
  53473. };
  53474. SetValueAction.prototype.serialize = function (parent) {
  53475. return _super.prototype._serialize.call(this, {
  53476. name: "SetValueAction",
  53477. properties: [
  53478. BABYLON.Action._GetTargetProperty(this._target),
  53479. { name: "propertyPath", value: this.propertyPath },
  53480. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53481. ]
  53482. }, parent);
  53483. };
  53484. return SetValueAction;
  53485. }(BABYLON.Action));
  53486. BABYLON.SetValueAction = SetValueAction;
  53487. var IncrementValueAction = /** @class */ (function (_super) {
  53488. __extends(IncrementValueAction, _super);
  53489. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53490. var _this = _super.call(this, triggerOptions, condition) || this;
  53491. _this.propertyPath = propertyPath;
  53492. _this.value = value;
  53493. _this._target = _this._effectiveTarget = target;
  53494. return _this;
  53495. }
  53496. IncrementValueAction.prototype._prepare = function () {
  53497. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53498. this._property = this._getProperty(this.propertyPath);
  53499. if (typeof this._effectiveTarget[this._property] !== "number") {
  53500. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53501. }
  53502. };
  53503. IncrementValueAction.prototype.execute = function () {
  53504. this._effectiveTarget[this._property] += this.value;
  53505. if (this._target.markAsDirty) {
  53506. this._target.markAsDirty(this._property);
  53507. }
  53508. };
  53509. IncrementValueAction.prototype.serialize = function (parent) {
  53510. return _super.prototype._serialize.call(this, {
  53511. name: "IncrementValueAction",
  53512. properties: [
  53513. BABYLON.Action._GetTargetProperty(this._target),
  53514. { name: "propertyPath", value: this.propertyPath },
  53515. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53516. ]
  53517. }, parent);
  53518. };
  53519. return IncrementValueAction;
  53520. }(BABYLON.Action));
  53521. BABYLON.IncrementValueAction = IncrementValueAction;
  53522. var PlayAnimationAction = /** @class */ (function (_super) {
  53523. __extends(PlayAnimationAction, _super);
  53524. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53525. var _this = _super.call(this, triggerOptions, condition) || this;
  53526. _this.from = from;
  53527. _this.to = to;
  53528. _this.loop = loop;
  53529. _this._target = target;
  53530. return _this;
  53531. }
  53532. PlayAnimationAction.prototype._prepare = function () {
  53533. };
  53534. PlayAnimationAction.prototype.execute = function () {
  53535. var scene = this._actionManager.getScene();
  53536. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53537. };
  53538. PlayAnimationAction.prototype.serialize = function (parent) {
  53539. return _super.prototype._serialize.call(this, {
  53540. name: "PlayAnimationAction",
  53541. properties: [
  53542. BABYLON.Action._GetTargetProperty(this._target),
  53543. { name: "from", value: String(this.from) },
  53544. { name: "to", value: String(this.to) },
  53545. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53546. ]
  53547. }, parent);
  53548. };
  53549. return PlayAnimationAction;
  53550. }(BABYLON.Action));
  53551. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53552. var StopAnimationAction = /** @class */ (function (_super) {
  53553. __extends(StopAnimationAction, _super);
  53554. function StopAnimationAction(triggerOptions, target, condition) {
  53555. var _this = _super.call(this, triggerOptions, condition) || this;
  53556. _this._target = target;
  53557. return _this;
  53558. }
  53559. StopAnimationAction.prototype._prepare = function () {
  53560. };
  53561. StopAnimationAction.prototype.execute = function () {
  53562. var scene = this._actionManager.getScene();
  53563. scene.stopAnimation(this._target);
  53564. };
  53565. StopAnimationAction.prototype.serialize = function (parent) {
  53566. return _super.prototype._serialize.call(this, {
  53567. name: "StopAnimationAction",
  53568. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53569. }, parent);
  53570. };
  53571. return StopAnimationAction;
  53572. }(BABYLON.Action));
  53573. BABYLON.StopAnimationAction = StopAnimationAction;
  53574. var DoNothingAction = /** @class */ (function (_super) {
  53575. __extends(DoNothingAction, _super);
  53576. function DoNothingAction(triggerOptions, condition) {
  53577. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53578. return _super.call(this, triggerOptions, condition) || this;
  53579. }
  53580. DoNothingAction.prototype.execute = function () {
  53581. };
  53582. DoNothingAction.prototype.serialize = function (parent) {
  53583. return _super.prototype._serialize.call(this, {
  53584. name: "DoNothingAction",
  53585. properties: []
  53586. }, parent);
  53587. };
  53588. return DoNothingAction;
  53589. }(BABYLON.Action));
  53590. BABYLON.DoNothingAction = DoNothingAction;
  53591. var CombineAction = /** @class */ (function (_super) {
  53592. __extends(CombineAction, _super);
  53593. function CombineAction(triggerOptions, children, condition) {
  53594. var _this = _super.call(this, triggerOptions, condition) || this;
  53595. _this.children = children;
  53596. return _this;
  53597. }
  53598. CombineAction.prototype._prepare = function () {
  53599. for (var index = 0; index < this.children.length; index++) {
  53600. this.children[index]._actionManager = this._actionManager;
  53601. this.children[index]._prepare();
  53602. }
  53603. };
  53604. CombineAction.prototype.execute = function (evt) {
  53605. for (var index = 0; index < this.children.length; index++) {
  53606. this.children[index].execute(evt);
  53607. }
  53608. };
  53609. CombineAction.prototype.serialize = function (parent) {
  53610. var serializationObject = _super.prototype._serialize.call(this, {
  53611. name: "CombineAction",
  53612. properties: [],
  53613. combine: []
  53614. }, parent);
  53615. for (var i = 0; i < this.children.length; i++) {
  53616. serializationObject.combine.push(this.children[i].serialize(null));
  53617. }
  53618. return serializationObject;
  53619. };
  53620. return CombineAction;
  53621. }(BABYLON.Action));
  53622. BABYLON.CombineAction = CombineAction;
  53623. var ExecuteCodeAction = /** @class */ (function (_super) {
  53624. __extends(ExecuteCodeAction, _super);
  53625. function ExecuteCodeAction(triggerOptions, func, condition) {
  53626. var _this = _super.call(this, triggerOptions, condition) || this;
  53627. _this.func = func;
  53628. return _this;
  53629. }
  53630. ExecuteCodeAction.prototype.execute = function (evt) {
  53631. this.func(evt);
  53632. };
  53633. return ExecuteCodeAction;
  53634. }(BABYLON.Action));
  53635. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53636. var SetParentAction = /** @class */ (function (_super) {
  53637. __extends(SetParentAction, _super);
  53638. function SetParentAction(triggerOptions, target, parent, condition) {
  53639. var _this = _super.call(this, triggerOptions, condition) || this;
  53640. _this._target = target;
  53641. _this._parent = parent;
  53642. return _this;
  53643. }
  53644. SetParentAction.prototype._prepare = function () {
  53645. };
  53646. SetParentAction.prototype.execute = function () {
  53647. if (this._target.parent === this._parent) {
  53648. return;
  53649. }
  53650. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53651. invertParentWorldMatrix.invert();
  53652. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53653. this._target.parent = this._parent;
  53654. };
  53655. SetParentAction.prototype.serialize = function (parent) {
  53656. return _super.prototype._serialize.call(this, {
  53657. name: "SetParentAction",
  53658. properties: [
  53659. BABYLON.Action._GetTargetProperty(this._target),
  53660. BABYLON.Action._GetTargetProperty(this._parent),
  53661. ]
  53662. }, parent);
  53663. };
  53664. return SetParentAction;
  53665. }(BABYLON.Action));
  53666. BABYLON.SetParentAction = SetParentAction;
  53667. var PlaySoundAction = /** @class */ (function (_super) {
  53668. __extends(PlaySoundAction, _super);
  53669. function PlaySoundAction(triggerOptions, sound, condition) {
  53670. var _this = _super.call(this, triggerOptions, condition) || this;
  53671. _this._sound = sound;
  53672. return _this;
  53673. }
  53674. PlaySoundAction.prototype._prepare = function () {
  53675. };
  53676. PlaySoundAction.prototype.execute = function () {
  53677. if (this._sound !== undefined)
  53678. this._sound.play();
  53679. };
  53680. PlaySoundAction.prototype.serialize = function (parent) {
  53681. return _super.prototype._serialize.call(this, {
  53682. name: "PlaySoundAction",
  53683. properties: [{ name: "sound", value: this._sound.name }]
  53684. }, parent);
  53685. };
  53686. return PlaySoundAction;
  53687. }(BABYLON.Action));
  53688. BABYLON.PlaySoundAction = PlaySoundAction;
  53689. var StopSoundAction = /** @class */ (function (_super) {
  53690. __extends(StopSoundAction, _super);
  53691. function StopSoundAction(triggerOptions, sound, condition) {
  53692. var _this = _super.call(this, triggerOptions, condition) || this;
  53693. _this._sound = sound;
  53694. return _this;
  53695. }
  53696. StopSoundAction.prototype._prepare = function () {
  53697. };
  53698. StopSoundAction.prototype.execute = function () {
  53699. if (this._sound !== undefined)
  53700. this._sound.stop();
  53701. };
  53702. StopSoundAction.prototype.serialize = function (parent) {
  53703. return _super.prototype._serialize.call(this, {
  53704. name: "StopSoundAction",
  53705. properties: [{ name: "sound", value: this._sound.name }]
  53706. }, parent);
  53707. };
  53708. return StopSoundAction;
  53709. }(BABYLON.Action));
  53710. BABYLON.StopSoundAction = StopSoundAction;
  53711. })(BABYLON || (BABYLON = {}));
  53712. //# sourceMappingURL=babylon.directActions.js.map
  53713. var BABYLON;
  53714. (function (BABYLON) {
  53715. var SpriteManager = /** @class */ (function () {
  53716. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53717. if (epsilon === void 0) { epsilon = 0.01; }
  53718. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53719. this.name = name;
  53720. this.sprites = new Array();
  53721. this.renderingGroupId = 0;
  53722. this.layerMask = 0x0FFFFFFF;
  53723. this.fogEnabled = true;
  53724. this.isPickable = false;
  53725. /**
  53726. * An event triggered when the manager is disposed.
  53727. */
  53728. this.onDisposeObservable = new BABYLON.Observable();
  53729. this._vertexBuffers = {};
  53730. this._capacity = capacity;
  53731. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53732. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53733. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53734. if (cellSize.width && cellSize.height) {
  53735. this.cellWidth = cellSize.width;
  53736. this.cellHeight = cellSize.height;
  53737. }
  53738. else if (cellSize !== undefined) {
  53739. this.cellWidth = cellSize;
  53740. this.cellHeight = cellSize;
  53741. }
  53742. else {
  53743. return;
  53744. }
  53745. this._epsilon = epsilon;
  53746. this._scene = scene;
  53747. this._scene.spriteManagers.push(this);
  53748. var indices = [];
  53749. var index = 0;
  53750. for (var count = 0; count < capacity; count++) {
  53751. indices.push(index);
  53752. indices.push(index + 1);
  53753. indices.push(index + 2);
  53754. indices.push(index);
  53755. indices.push(index + 2);
  53756. indices.push(index + 3);
  53757. index += 4;
  53758. }
  53759. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53760. // VBO
  53761. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53762. this._vertexData = new Float32Array(capacity * 16 * 4);
  53763. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53764. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53765. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53766. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53767. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53768. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53769. this._vertexBuffers["options"] = options;
  53770. this._vertexBuffers["cellInfo"] = cellInfo;
  53771. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53772. // Effects
  53773. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53774. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53775. }
  53776. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53777. set: function (callback) {
  53778. if (this._onDisposeObserver) {
  53779. this.onDisposeObservable.remove(this._onDisposeObserver);
  53780. }
  53781. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53782. },
  53783. enumerable: true,
  53784. configurable: true
  53785. });
  53786. Object.defineProperty(SpriteManager.prototype, "texture", {
  53787. get: function () {
  53788. return this._spriteTexture;
  53789. },
  53790. set: function (value) {
  53791. this._spriteTexture = value;
  53792. },
  53793. enumerable: true,
  53794. configurable: true
  53795. });
  53796. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53797. var arrayOffset = index * 16;
  53798. if (offsetX === 0)
  53799. offsetX = this._epsilon;
  53800. else if (offsetX === 1)
  53801. offsetX = 1 - this._epsilon;
  53802. if (offsetY === 0)
  53803. offsetY = this._epsilon;
  53804. else if (offsetY === 1)
  53805. offsetY = 1 - this._epsilon;
  53806. this._vertexData[arrayOffset] = sprite.position.x;
  53807. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53808. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53809. this._vertexData[arrayOffset + 3] = sprite.angle;
  53810. this._vertexData[arrayOffset + 4] = sprite.width;
  53811. this._vertexData[arrayOffset + 5] = sprite.height;
  53812. this._vertexData[arrayOffset + 6] = offsetX;
  53813. this._vertexData[arrayOffset + 7] = offsetY;
  53814. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53815. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53816. var offset = (sprite.cellIndex / rowSize) >> 0;
  53817. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53818. this._vertexData[arrayOffset + 11] = offset;
  53819. // Color
  53820. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53821. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53822. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53823. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53824. };
  53825. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53826. var count = Math.min(this._capacity, this.sprites.length);
  53827. var min = BABYLON.Vector3.Zero();
  53828. var max = BABYLON.Vector3.Zero();
  53829. var distance = Number.MAX_VALUE;
  53830. var currentSprite = null;
  53831. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53832. var cameraView = camera.getViewMatrix();
  53833. for (var index = 0; index < count; index++) {
  53834. var sprite = this.sprites[index];
  53835. if (!sprite) {
  53836. continue;
  53837. }
  53838. if (predicate) {
  53839. if (!predicate(sprite)) {
  53840. continue;
  53841. }
  53842. }
  53843. else if (!sprite.isPickable) {
  53844. continue;
  53845. }
  53846. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53847. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53848. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53849. if (ray.intersectsBoxMinMax(min, max)) {
  53850. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53851. if (distance > currentDistance) {
  53852. distance = currentDistance;
  53853. currentSprite = sprite;
  53854. if (fastCheck) {
  53855. break;
  53856. }
  53857. }
  53858. }
  53859. }
  53860. if (currentSprite) {
  53861. var result = new BABYLON.PickingInfo();
  53862. result.hit = true;
  53863. result.pickedSprite = currentSprite;
  53864. result.distance = distance;
  53865. return result;
  53866. }
  53867. return null;
  53868. };
  53869. SpriteManager.prototype.render = function () {
  53870. // Check
  53871. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53872. return;
  53873. var engine = this._scene.getEngine();
  53874. var baseSize = this._spriteTexture.getBaseSize();
  53875. // Sprites
  53876. var deltaTime = engine.getDeltaTime();
  53877. var max = Math.min(this._capacity, this.sprites.length);
  53878. var rowSize = baseSize.width / this.cellWidth;
  53879. var offset = 0;
  53880. for (var index = 0; index < max; index++) {
  53881. var sprite = this.sprites[index];
  53882. if (!sprite) {
  53883. continue;
  53884. }
  53885. sprite._animate(deltaTime);
  53886. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53887. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53888. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53889. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53890. }
  53891. this._buffer.update(this._vertexData);
  53892. // Render
  53893. var effect = this._effectBase;
  53894. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53895. effect = this._effectFog;
  53896. }
  53897. engine.enableEffect(effect);
  53898. var viewMatrix = this._scene.getViewMatrix();
  53899. effect.setTexture("diffuseSampler", this._spriteTexture);
  53900. effect.setMatrix("view", viewMatrix);
  53901. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53902. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53903. // Fog
  53904. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53905. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53906. effect.setColor3("vFogColor", this._scene.fogColor);
  53907. }
  53908. // VBOs
  53909. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53910. // Draw order
  53911. engine.setDepthFunctionToLessOrEqual();
  53912. effect.setBool("alphaTest", true);
  53913. engine.setColorWrite(false);
  53914. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53915. engine.setColorWrite(true);
  53916. effect.setBool("alphaTest", false);
  53917. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53918. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53919. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53920. };
  53921. SpriteManager.prototype.dispose = function () {
  53922. if (this._buffer) {
  53923. this._buffer.dispose();
  53924. this._buffer = null;
  53925. }
  53926. if (this._indexBuffer) {
  53927. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53928. this._indexBuffer = null;
  53929. }
  53930. if (this._spriteTexture) {
  53931. this._spriteTexture.dispose();
  53932. this._spriteTexture = null;
  53933. }
  53934. // Remove from scene
  53935. var index = this._scene.spriteManagers.indexOf(this);
  53936. this._scene.spriteManagers.splice(index, 1);
  53937. // Callback
  53938. this.onDisposeObservable.notifyObservers(this);
  53939. this.onDisposeObservable.clear();
  53940. };
  53941. return SpriteManager;
  53942. }());
  53943. BABYLON.SpriteManager = SpriteManager;
  53944. })(BABYLON || (BABYLON = {}));
  53945. //# sourceMappingURL=babylon.spriteManager.js.map
  53946. var BABYLON;
  53947. (function (BABYLON) {
  53948. var Sprite = /** @class */ (function () {
  53949. function Sprite(name, manager) {
  53950. this.name = name;
  53951. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53952. this.width = 1.0;
  53953. this.height = 1.0;
  53954. this.angle = 0;
  53955. this.cellIndex = 0;
  53956. this.invertU = 0;
  53957. this.invertV = 0;
  53958. this.animations = new Array();
  53959. this.isPickable = false;
  53960. this._animationStarted = false;
  53961. this._loopAnimation = false;
  53962. this._fromIndex = 0;
  53963. this._toIndex = 0;
  53964. this._delay = 0;
  53965. this._direction = 1;
  53966. this._time = 0;
  53967. this._manager = manager;
  53968. this._manager.sprites.push(this);
  53969. this.position = BABYLON.Vector3.Zero();
  53970. }
  53971. Object.defineProperty(Sprite.prototype, "size", {
  53972. get: function () {
  53973. return this.width;
  53974. },
  53975. set: function (value) {
  53976. this.width = value;
  53977. this.height = value;
  53978. },
  53979. enumerable: true,
  53980. configurable: true
  53981. });
  53982. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53983. this._fromIndex = from;
  53984. this._toIndex = to;
  53985. this._loopAnimation = loop;
  53986. this._delay = delay;
  53987. this._animationStarted = true;
  53988. this._direction = from < to ? 1 : -1;
  53989. this.cellIndex = from;
  53990. this._time = 0;
  53991. this._onAnimationEnd = onAnimationEnd;
  53992. };
  53993. Sprite.prototype.stopAnimation = function () {
  53994. this._animationStarted = false;
  53995. };
  53996. Sprite.prototype._animate = function (deltaTime) {
  53997. if (!this._animationStarted)
  53998. return;
  53999. this._time += deltaTime;
  54000. if (this._time > this._delay) {
  54001. this._time = this._time % this._delay;
  54002. this.cellIndex += this._direction;
  54003. if (this.cellIndex > this._toIndex) {
  54004. if (this._loopAnimation) {
  54005. this.cellIndex = this._fromIndex;
  54006. }
  54007. else {
  54008. this.cellIndex = this._toIndex;
  54009. this._animationStarted = false;
  54010. if (this._onAnimationEnd) {
  54011. this._onAnimationEnd();
  54012. }
  54013. if (this.disposeWhenFinishedAnimating) {
  54014. this.dispose();
  54015. }
  54016. }
  54017. }
  54018. }
  54019. };
  54020. Sprite.prototype.dispose = function () {
  54021. for (var i = 0; i < this._manager.sprites.length; i++) {
  54022. if (this._manager.sprites[i] == this) {
  54023. this._manager.sprites.splice(i, 1);
  54024. }
  54025. }
  54026. };
  54027. return Sprite;
  54028. }());
  54029. BABYLON.Sprite = Sprite;
  54030. })(BABYLON || (BABYLON = {}));
  54031. //# sourceMappingURL=babylon.sprite.js.map
  54032. var BABYLON;
  54033. (function (BABYLON) {
  54034. var IntersectionInfo = /** @class */ (function () {
  54035. function IntersectionInfo(bu, bv, distance) {
  54036. this.bu = bu;
  54037. this.bv = bv;
  54038. this.distance = distance;
  54039. this.faceId = 0;
  54040. this.subMeshId = 0;
  54041. }
  54042. return IntersectionInfo;
  54043. }());
  54044. BABYLON.IntersectionInfo = IntersectionInfo;
  54045. var PickingInfo = /** @class */ (function () {
  54046. function PickingInfo() {
  54047. this.hit = false;
  54048. this.distance = 0;
  54049. this.pickedPoint = null;
  54050. this.pickedMesh = null;
  54051. this.bu = 0;
  54052. this.bv = 0;
  54053. this.faceId = -1;
  54054. this.subMeshId = 0;
  54055. this.pickedSprite = null;
  54056. }
  54057. // Methods
  54058. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54059. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54060. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54061. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54062. return null;
  54063. }
  54064. var indices = this.pickedMesh.getIndices();
  54065. if (!indices) {
  54066. return null;
  54067. }
  54068. var result;
  54069. if (useVerticesNormals) {
  54070. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54071. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54072. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54073. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54074. normal0 = normal0.scale(this.bu);
  54075. normal1 = normal1.scale(this.bv);
  54076. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54077. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54078. }
  54079. else {
  54080. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54081. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54082. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54083. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54084. var p1p2 = vertex1.subtract(vertex2);
  54085. var p3p2 = vertex3.subtract(vertex2);
  54086. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54087. }
  54088. if (useWorldCoordinates) {
  54089. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54090. }
  54091. return BABYLON.Vector3.Normalize(result);
  54092. };
  54093. PickingInfo.prototype.getTextureCoordinates = function () {
  54094. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54095. return null;
  54096. }
  54097. var indices = this.pickedMesh.getIndices();
  54098. if (!indices) {
  54099. return null;
  54100. }
  54101. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54102. if (!uvs) {
  54103. return null;
  54104. }
  54105. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54106. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54107. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54108. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54109. uv1 = uv1.scale(this.bu);
  54110. uv2 = uv2.scale(this.bv);
  54111. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54112. };
  54113. return PickingInfo;
  54114. }());
  54115. BABYLON.PickingInfo = PickingInfo;
  54116. })(BABYLON || (BABYLON = {}));
  54117. //# sourceMappingURL=babylon.pickingInfo.js.map
  54118. var BABYLON;
  54119. (function (BABYLON) {
  54120. var Ray = /** @class */ (function () {
  54121. function Ray(origin, direction, length) {
  54122. if (length === void 0) { length = Number.MAX_VALUE; }
  54123. this.origin = origin;
  54124. this.direction = direction;
  54125. this.length = length;
  54126. }
  54127. // Methods
  54128. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54129. var d = 0.0;
  54130. var maxValue = Number.MAX_VALUE;
  54131. var inv;
  54132. var min;
  54133. var max;
  54134. var temp;
  54135. if (Math.abs(this.direction.x) < 0.0000001) {
  54136. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54137. return false;
  54138. }
  54139. }
  54140. else {
  54141. inv = 1.0 / this.direction.x;
  54142. min = (minimum.x - this.origin.x) * inv;
  54143. max = (maximum.x - this.origin.x) * inv;
  54144. if (max === -Infinity) {
  54145. max = Infinity;
  54146. }
  54147. if (min > max) {
  54148. temp = min;
  54149. min = max;
  54150. max = temp;
  54151. }
  54152. d = Math.max(min, d);
  54153. maxValue = Math.min(max, maxValue);
  54154. if (d > maxValue) {
  54155. return false;
  54156. }
  54157. }
  54158. if (Math.abs(this.direction.y) < 0.0000001) {
  54159. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54160. return false;
  54161. }
  54162. }
  54163. else {
  54164. inv = 1.0 / this.direction.y;
  54165. min = (minimum.y - this.origin.y) * inv;
  54166. max = (maximum.y - this.origin.y) * inv;
  54167. if (max === -Infinity) {
  54168. max = Infinity;
  54169. }
  54170. if (min > max) {
  54171. temp = min;
  54172. min = max;
  54173. max = temp;
  54174. }
  54175. d = Math.max(min, d);
  54176. maxValue = Math.min(max, maxValue);
  54177. if (d > maxValue) {
  54178. return false;
  54179. }
  54180. }
  54181. if (Math.abs(this.direction.z) < 0.0000001) {
  54182. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54183. return false;
  54184. }
  54185. }
  54186. else {
  54187. inv = 1.0 / this.direction.z;
  54188. min = (minimum.z - this.origin.z) * inv;
  54189. max = (maximum.z - this.origin.z) * inv;
  54190. if (max === -Infinity) {
  54191. max = Infinity;
  54192. }
  54193. if (min > max) {
  54194. temp = min;
  54195. min = max;
  54196. max = temp;
  54197. }
  54198. d = Math.max(min, d);
  54199. maxValue = Math.min(max, maxValue);
  54200. if (d > maxValue) {
  54201. return false;
  54202. }
  54203. }
  54204. return true;
  54205. };
  54206. Ray.prototype.intersectsBox = function (box) {
  54207. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54208. };
  54209. Ray.prototype.intersectsSphere = function (sphere) {
  54210. var x = sphere.center.x - this.origin.x;
  54211. var y = sphere.center.y - this.origin.y;
  54212. var z = sphere.center.z - this.origin.z;
  54213. var pyth = (x * x) + (y * y) + (z * z);
  54214. var rr = sphere.radius * sphere.radius;
  54215. if (pyth <= rr) {
  54216. return true;
  54217. }
  54218. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54219. if (dot < 0.0) {
  54220. return false;
  54221. }
  54222. var temp = pyth - (dot * dot);
  54223. return temp <= rr;
  54224. };
  54225. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54226. if (!this._edge1) {
  54227. this._edge1 = BABYLON.Vector3.Zero();
  54228. this._edge2 = BABYLON.Vector3.Zero();
  54229. this._pvec = BABYLON.Vector3.Zero();
  54230. this._tvec = BABYLON.Vector3.Zero();
  54231. this._qvec = BABYLON.Vector3.Zero();
  54232. }
  54233. vertex1.subtractToRef(vertex0, this._edge1);
  54234. vertex2.subtractToRef(vertex0, this._edge2);
  54235. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54236. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54237. if (det === 0) {
  54238. return null;
  54239. }
  54240. var invdet = 1 / det;
  54241. this.origin.subtractToRef(vertex0, this._tvec);
  54242. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54243. if (bu < 0 || bu > 1.0) {
  54244. return null;
  54245. }
  54246. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54247. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54248. if (bv < 0 || bu + bv > 1.0) {
  54249. return null;
  54250. }
  54251. //check if the distance is longer than the predefined length.
  54252. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54253. if (distance > this.length) {
  54254. return null;
  54255. }
  54256. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54257. };
  54258. Ray.prototype.intersectsPlane = function (plane) {
  54259. var distance;
  54260. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54261. if (Math.abs(result1) < 9.99999997475243E-07) {
  54262. return null;
  54263. }
  54264. else {
  54265. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54266. distance = (-plane.d - result2) / result1;
  54267. if (distance < 0.0) {
  54268. if (distance < -9.99999997475243E-07) {
  54269. return null;
  54270. }
  54271. else {
  54272. return 0;
  54273. }
  54274. }
  54275. return distance;
  54276. }
  54277. };
  54278. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54279. var tm = BABYLON.Tmp.Matrix[0];
  54280. mesh.getWorldMatrix().invertToRef(tm);
  54281. if (this._tmpRay) {
  54282. Ray.TransformToRef(this, tm, this._tmpRay);
  54283. }
  54284. else {
  54285. this._tmpRay = Ray.Transform(this, tm);
  54286. }
  54287. return mesh.intersects(this._tmpRay, fastCheck);
  54288. };
  54289. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54290. if (results) {
  54291. results.length = 0;
  54292. }
  54293. else {
  54294. results = [];
  54295. }
  54296. for (var i = 0; i < meshes.length; i++) {
  54297. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54298. if (pickInfo.hit) {
  54299. results.push(pickInfo);
  54300. }
  54301. }
  54302. results.sort(this._comparePickingInfo);
  54303. return results;
  54304. };
  54305. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54306. if (pickingInfoA.distance < pickingInfoB.distance) {
  54307. return -1;
  54308. }
  54309. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54310. return 1;
  54311. }
  54312. else {
  54313. return 0;
  54314. }
  54315. };
  54316. /**
  54317. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54318. * @param sega the first point of the segment to test the intersection against
  54319. * @param segb the second point of the segment to test the intersection against
  54320. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54321. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54322. */
  54323. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54324. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54325. var u = segb.subtract(sega);
  54326. var v = rsegb.subtract(this.origin);
  54327. var w = sega.subtract(this.origin);
  54328. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54329. var b = BABYLON.Vector3.Dot(u, v);
  54330. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54331. var d = BABYLON.Vector3.Dot(u, w);
  54332. var e = BABYLON.Vector3.Dot(v, w);
  54333. var D = a * c - b * b; // always >= 0
  54334. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54335. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54336. // compute the line parameters of the two closest points
  54337. if (D < Ray.smallnum) { // the lines are almost parallel
  54338. sN = 0.0; // force using point P0 on segment S1
  54339. sD = 1.0; // to prevent possible division by 0.0 later
  54340. tN = e;
  54341. tD = c;
  54342. }
  54343. else { // get the closest points on the infinite lines
  54344. sN = (b * e - c * d);
  54345. tN = (a * e - b * d);
  54346. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54347. sN = 0.0;
  54348. tN = e;
  54349. tD = c;
  54350. }
  54351. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54352. sN = sD;
  54353. tN = e + b;
  54354. tD = c;
  54355. }
  54356. }
  54357. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54358. tN = 0.0;
  54359. // recompute sc for this edge
  54360. if (-d < 0.0) {
  54361. sN = 0.0;
  54362. }
  54363. else if (-d > a)
  54364. sN = sD;
  54365. else {
  54366. sN = -d;
  54367. sD = a;
  54368. }
  54369. }
  54370. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54371. tN = tD;
  54372. // recompute sc for this edge
  54373. if ((-d + b) < 0.0) {
  54374. sN = 0;
  54375. }
  54376. else if ((-d + b) > a) {
  54377. sN = sD;
  54378. }
  54379. else {
  54380. sN = (-d + b);
  54381. sD = a;
  54382. }
  54383. }
  54384. // finally do the division to get sc and tc
  54385. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54386. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54387. // get the difference of the two closest points
  54388. var qtc = v.multiplyByFloats(tc, tc, tc);
  54389. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54390. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54391. if (isIntersected) {
  54392. return qtc.length();
  54393. }
  54394. return -1;
  54395. };
  54396. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54397. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54398. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54399. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54400. this.direction.normalize();
  54401. return this;
  54402. };
  54403. // Statics
  54404. Ray.Zero = function () {
  54405. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54406. };
  54407. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54408. var result = Ray.Zero();
  54409. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54410. };
  54411. /**
  54412. * 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
  54413. * transformed to the given world matrix.
  54414. * @param origin The origin point
  54415. * @param end The end point
  54416. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54417. */
  54418. Ray.CreateNewFromTo = function (origin, end, world) {
  54419. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54420. var direction = end.subtract(origin);
  54421. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54422. direction.normalize();
  54423. return Ray.Transform(new Ray(origin, direction, length), world);
  54424. };
  54425. Ray.Transform = function (ray, matrix) {
  54426. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54427. Ray.TransformToRef(ray, matrix, result);
  54428. return result;
  54429. };
  54430. Ray.TransformToRef = function (ray, matrix, result) {
  54431. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54432. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54433. result.length = ray.length;
  54434. var dir = result.direction;
  54435. var len = dir.length();
  54436. if (!(len === 0 || len === 1)) {
  54437. var num = 1.0 / len;
  54438. dir.x *= num;
  54439. dir.y *= num;
  54440. dir.z *= num;
  54441. result.length *= len;
  54442. }
  54443. };
  54444. Ray.smallnum = 0.00000001;
  54445. Ray.rayl = 10e8;
  54446. return Ray;
  54447. }());
  54448. BABYLON.Ray = Ray;
  54449. })(BABYLON || (BABYLON = {}));
  54450. //# sourceMappingURL=babylon.ray.js.map
  54451. var BABYLON;
  54452. (function (BABYLON) {
  54453. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54454. if (boxMin.x > sphereCenter.x + sphereRadius)
  54455. return false;
  54456. if (sphereCenter.x - sphereRadius > boxMax.x)
  54457. return false;
  54458. if (boxMin.y > sphereCenter.y + sphereRadius)
  54459. return false;
  54460. if (sphereCenter.y - sphereRadius > boxMax.y)
  54461. return false;
  54462. if (boxMin.z > sphereCenter.z + sphereRadius)
  54463. return false;
  54464. if (sphereCenter.z - sphereRadius > boxMax.z)
  54465. return false;
  54466. return true;
  54467. };
  54468. var getLowestRoot = (function () {
  54469. var result = { root: 0, found: false };
  54470. return function (a, b, c, maxR) {
  54471. result.root = 0;
  54472. result.found = false;
  54473. var determinant = b * b - 4.0 * a * c;
  54474. if (determinant < 0)
  54475. return result;
  54476. var sqrtD = Math.sqrt(determinant);
  54477. var r1 = (-b - sqrtD) / (2.0 * a);
  54478. var r2 = (-b + sqrtD) / (2.0 * a);
  54479. if (r1 > r2) {
  54480. var temp = r2;
  54481. r2 = r1;
  54482. r1 = temp;
  54483. }
  54484. if (r1 > 0 && r1 < maxR) {
  54485. result.root = r1;
  54486. result.found = true;
  54487. return result;
  54488. }
  54489. if (r2 > 0 && r2 < maxR) {
  54490. result.root = r2;
  54491. result.found = true;
  54492. return result;
  54493. }
  54494. return result;
  54495. };
  54496. })();
  54497. var Collider = /** @class */ (function () {
  54498. function Collider() {
  54499. this._collisionPoint = BABYLON.Vector3.Zero();
  54500. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54501. this._tempVector = BABYLON.Vector3.Zero();
  54502. this._tempVector2 = BABYLON.Vector3.Zero();
  54503. this._tempVector3 = BABYLON.Vector3.Zero();
  54504. this._tempVector4 = BABYLON.Vector3.Zero();
  54505. this._edge = BABYLON.Vector3.Zero();
  54506. this._baseToVertex = BABYLON.Vector3.Zero();
  54507. this._destinationPoint = BABYLON.Vector3.Zero();
  54508. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54509. this._displacementVector = BABYLON.Vector3.Zero();
  54510. this._radius = BABYLON.Vector3.One();
  54511. this._retry = 0;
  54512. this._basePointWorld = BABYLON.Vector3.Zero();
  54513. this._velocityWorld = BABYLON.Vector3.Zero();
  54514. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54515. this._collisionMask = -1;
  54516. }
  54517. Object.defineProperty(Collider.prototype, "collisionMask", {
  54518. get: function () {
  54519. return this._collisionMask;
  54520. },
  54521. set: function (mask) {
  54522. this._collisionMask = !isNaN(mask) ? mask : -1;
  54523. },
  54524. enumerable: true,
  54525. configurable: true
  54526. });
  54527. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54528. /**
  54529. * Gets the plane normal used to compute the sliding response (in local space)
  54530. */
  54531. get: function () {
  54532. return this._slidePlaneNormal;
  54533. },
  54534. enumerable: true,
  54535. configurable: true
  54536. });
  54537. // Methods
  54538. Collider.prototype._initialize = function (source, dir, e) {
  54539. this._velocity = dir;
  54540. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54541. this._basePoint = source;
  54542. source.multiplyToRef(this._radius, this._basePointWorld);
  54543. dir.multiplyToRef(this._radius, this._velocityWorld);
  54544. this._velocityWorldLength = this._velocityWorld.length();
  54545. this._epsilon = e;
  54546. this.collisionFound = false;
  54547. };
  54548. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54549. pa.subtractToRef(point, this._tempVector);
  54550. pb.subtractToRef(point, this._tempVector2);
  54551. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54552. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54553. if (d < 0)
  54554. return false;
  54555. pc.subtractToRef(point, this._tempVector3);
  54556. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54557. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54558. if (d < 0)
  54559. return false;
  54560. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54561. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54562. return d >= 0;
  54563. };
  54564. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54565. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54566. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54567. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54568. return false;
  54569. }
  54570. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54571. return false;
  54572. return true;
  54573. };
  54574. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54575. var t0;
  54576. var embeddedInPlane = false;
  54577. //defensive programming, actually not needed.
  54578. if (!trianglePlaneArray) {
  54579. trianglePlaneArray = [];
  54580. }
  54581. if (!trianglePlaneArray[faceIndex]) {
  54582. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54583. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54584. }
  54585. var trianglePlane = trianglePlaneArray[faceIndex];
  54586. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54587. return;
  54588. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54589. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54590. if (normalDotVelocity == 0) {
  54591. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54592. return;
  54593. embeddedInPlane = true;
  54594. t0 = 0;
  54595. }
  54596. else {
  54597. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54598. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54599. if (t0 > t1) {
  54600. var temp = t1;
  54601. t1 = t0;
  54602. t0 = temp;
  54603. }
  54604. if (t0 > 1.0 || t1 < 0.0)
  54605. return;
  54606. if (t0 < 0)
  54607. t0 = 0;
  54608. if (t0 > 1.0)
  54609. t0 = 1.0;
  54610. }
  54611. this._collisionPoint.copyFromFloats(0, 0, 0);
  54612. var found = false;
  54613. var t = 1.0;
  54614. if (!embeddedInPlane) {
  54615. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54616. this._velocity.scaleToRef(t0, this._tempVector);
  54617. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54618. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54619. found = true;
  54620. t = t0;
  54621. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54622. }
  54623. }
  54624. if (!found) {
  54625. var velocitySquaredLength = this._velocity.lengthSquared();
  54626. var a = velocitySquaredLength;
  54627. this._basePoint.subtractToRef(p1, this._tempVector);
  54628. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54629. var c = this._tempVector.lengthSquared() - 1.0;
  54630. var lowestRoot = getLowestRoot(a, b, c, t);
  54631. if (lowestRoot.found) {
  54632. t = lowestRoot.root;
  54633. found = true;
  54634. this._collisionPoint.copyFrom(p1);
  54635. }
  54636. this._basePoint.subtractToRef(p2, this._tempVector);
  54637. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54638. c = this._tempVector.lengthSquared() - 1.0;
  54639. lowestRoot = getLowestRoot(a, b, c, t);
  54640. if (lowestRoot.found) {
  54641. t = lowestRoot.root;
  54642. found = true;
  54643. this._collisionPoint.copyFrom(p2);
  54644. }
  54645. this._basePoint.subtractToRef(p3, this._tempVector);
  54646. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54647. c = this._tempVector.lengthSquared() - 1.0;
  54648. lowestRoot = getLowestRoot(a, b, c, t);
  54649. if (lowestRoot.found) {
  54650. t = lowestRoot.root;
  54651. found = true;
  54652. this._collisionPoint.copyFrom(p3);
  54653. }
  54654. p2.subtractToRef(p1, this._edge);
  54655. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54656. var edgeSquaredLength = this._edge.lengthSquared();
  54657. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54658. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54659. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54660. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54661. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54662. lowestRoot = getLowestRoot(a, b, c, t);
  54663. if (lowestRoot.found) {
  54664. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54665. if (f >= 0.0 && f <= 1.0) {
  54666. t = lowestRoot.root;
  54667. found = true;
  54668. this._edge.scaleInPlace(f);
  54669. p1.addToRef(this._edge, this._collisionPoint);
  54670. }
  54671. }
  54672. p3.subtractToRef(p2, this._edge);
  54673. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54674. edgeSquaredLength = this._edge.lengthSquared();
  54675. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54676. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54677. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54678. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54679. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54680. lowestRoot = getLowestRoot(a, b, c, t);
  54681. if (lowestRoot.found) {
  54682. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54683. if (f >= 0.0 && f <= 1.0) {
  54684. t = lowestRoot.root;
  54685. found = true;
  54686. this._edge.scaleInPlace(f);
  54687. p2.addToRef(this._edge, this._collisionPoint);
  54688. }
  54689. }
  54690. p1.subtractToRef(p3, this._edge);
  54691. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54692. edgeSquaredLength = this._edge.lengthSquared();
  54693. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54694. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54695. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54696. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54697. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54698. lowestRoot = getLowestRoot(a, b, c, t);
  54699. if (lowestRoot.found) {
  54700. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54701. if (f >= 0.0 && f <= 1.0) {
  54702. t = lowestRoot.root;
  54703. found = true;
  54704. this._edge.scaleInPlace(f);
  54705. p3.addToRef(this._edge, this._collisionPoint);
  54706. }
  54707. }
  54708. }
  54709. if (found) {
  54710. var distToCollision = t * this._velocity.length();
  54711. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54712. if (!this.intersectionPoint) {
  54713. this.intersectionPoint = this._collisionPoint.clone();
  54714. }
  54715. else {
  54716. this.intersectionPoint.copyFrom(this._collisionPoint);
  54717. }
  54718. this._nearestDistance = distToCollision;
  54719. this.collisionFound = true;
  54720. }
  54721. }
  54722. };
  54723. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54724. for (var i = indexStart; i < indexEnd; i += 3) {
  54725. var p1 = pts[indices[i] - decal];
  54726. var p2 = pts[indices[i + 1] - decal];
  54727. var p3 = pts[indices[i + 2] - decal];
  54728. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54729. }
  54730. };
  54731. Collider.prototype._getResponse = function (pos, vel) {
  54732. pos.addToRef(vel, this._destinationPoint);
  54733. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54734. this._basePoint.addToRef(vel, pos);
  54735. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54736. this._slidePlaneNormal.normalize();
  54737. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54738. pos.addInPlace(this._displacementVector);
  54739. this.intersectionPoint.addInPlace(this._displacementVector);
  54740. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54741. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54742. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54743. };
  54744. return Collider;
  54745. }());
  54746. BABYLON.Collider = Collider;
  54747. })(BABYLON || (BABYLON = {}));
  54748. //# sourceMappingURL=babylon.collider.js.map
  54749. var BABYLON;
  54750. (function (BABYLON) {
  54751. //WebWorker code will be inserted to this variable.
  54752. BABYLON.CollisionWorker = "";
  54753. /** Defines supported task for worker process */
  54754. var WorkerTaskType;
  54755. (function (WorkerTaskType) {
  54756. /** Initialization */
  54757. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54758. /** Update of geometry */
  54759. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54760. /** Evaluate collision */
  54761. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54762. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54763. /** Defines kind of replies returned by worker */
  54764. var WorkerReplyType;
  54765. (function (WorkerReplyType) {
  54766. /** Success */
  54767. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54768. /** Unkown error */
  54769. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54770. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54771. var CollisionCoordinatorWorker = /** @class */ (function () {
  54772. function CollisionCoordinatorWorker() {
  54773. var _this = this;
  54774. this._scaledPosition = BABYLON.Vector3.Zero();
  54775. this._scaledVelocity = BABYLON.Vector3.Zero();
  54776. this.onMeshUpdated = function (transformNode) {
  54777. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54778. };
  54779. this.onGeometryUpdated = function (geometry) {
  54780. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54781. };
  54782. this._afterRender = function () {
  54783. if (!_this._init)
  54784. return;
  54785. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54786. return;
  54787. }
  54788. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54789. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54790. if (_this._runningUpdated > 4) {
  54791. return;
  54792. }
  54793. ++_this._runningUpdated;
  54794. var payload = {
  54795. updatedMeshes: _this._addUpdateMeshesList,
  54796. updatedGeometries: _this._addUpdateGeometriesList,
  54797. removedGeometries: _this._toRemoveGeometryArray,
  54798. removedMeshes: _this._toRemoveMeshesArray
  54799. };
  54800. var message = {
  54801. payload: payload,
  54802. taskType: WorkerTaskType.UPDATE
  54803. };
  54804. var serializable = [];
  54805. for (var id in payload.updatedGeometries) {
  54806. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54807. //prepare transferables
  54808. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54809. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54810. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54811. }
  54812. }
  54813. _this._worker.postMessage(message, serializable);
  54814. _this._addUpdateMeshesList = {};
  54815. _this._addUpdateGeometriesList = {};
  54816. _this._toRemoveGeometryArray = [];
  54817. _this._toRemoveMeshesArray = [];
  54818. };
  54819. this._onMessageFromWorker = function (e) {
  54820. var returnData = e.data;
  54821. if (returnData.error != WorkerReplyType.SUCCESS) {
  54822. //TODO what errors can be returned from the worker?
  54823. BABYLON.Tools.Warn("error returned from worker!");
  54824. return;
  54825. }
  54826. switch (returnData.taskType) {
  54827. case WorkerTaskType.INIT:
  54828. _this._init = true;
  54829. //Update the worked with ALL of the scene's current state
  54830. _this._scene.meshes.forEach(function (mesh) {
  54831. _this.onMeshAdded(mesh);
  54832. });
  54833. _this._scene.getGeometries().forEach(function (geometry) {
  54834. _this.onGeometryAdded(geometry);
  54835. });
  54836. break;
  54837. case WorkerTaskType.UPDATE:
  54838. _this._runningUpdated--;
  54839. break;
  54840. case WorkerTaskType.COLLIDE:
  54841. var returnPayload = returnData.payload;
  54842. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54843. return;
  54844. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54845. if (callback) {
  54846. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54847. if (mesh) {
  54848. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54849. }
  54850. }
  54851. //cleanup
  54852. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54853. break;
  54854. }
  54855. };
  54856. this._collisionsCallbackArray = [];
  54857. this._init = false;
  54858. this._runningUpdated = 0;
  54859. this._addUpdateMeshesList = {};
  54860. this._addUpdateGeometriesList = {};
  54861. this._toRemoveGeometryArray = [];
  54862. this._toRemoveMeshesArray = [];
  54863. }
  54864. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54865. if (!this._init)
  54866. return;
  54867. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54868. return;
  54869. position.divideToRef(collider._radius, this._scaledPosition);
  54870. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54871. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54872. var payload = {
  54873. collider: {
  54874. position: this._scaledPosition.asArray(),
  54875. velocity: this._scaledVelocity.asArray(),
  54876. radius: collider._radius.asArray()
  54877. },
  54878. collisionId: collisionIndex,
  54879. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54880. maximumRetry: maximumRetry
  54881. };
  54882. var message = {
  54883. payload: payload,
  54884. taskType: WorkerTaskType.COLLIDE
  54885. };
  54886. this._worker.postMessage(message);
  54887. };
  54888. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54889. this._scene = scene;
  54890. this._scene.registerAfterRender(this._afterRender);
  54891. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54892. this._worker = new Worker(workerUrl);
  54893. this._worker.onmessage = this._onMessageFromWorker;
  54894. var message = {
  54895. payload: {},
  54896. taskType: WorkerTaskType.INIT
  54897. };
  54898. this._worker.postMessage(message);
  54899. };
  54900. CollisionCoordinatorWorker.prototype.destroy = function () {
  54901. this._scene.unregisterAfterRender(this._afterRender);
  54902. this._worker.terminate();
  54903. };
  54904. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54905. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54906. this.onMeshUpdated(mesh);
  54907. };
  54908. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54909. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54910. };
  54911. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54912. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54913. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54914. this.onGeometryUpdated(geometry);
  54915. };
  54916. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54917. this._toRemoveGeometryArray.push(geometry.id);
  54918. };
  54919. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54920. var submeshes = [];
  54921. if (mesh.subMeshes) {
  54922. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54923. var boundingInfo = sm.getBoundingInfo();
  54924. return {
  54925. position: idx,
  54926. verticesStart: sm.verticesStart,
  54927. verticesCount: sm.verticesCount,
  54928. indexStart: sm.indexStart,
  54929. indexCount: sm.indexCount,
  54930. hasMaterial: !!sm.getMaterial(),
  54931. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54932. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54933. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54934. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54935. };
  54936. });
  54937. }
  54938. var geometryId = null;
  54939. if (mesh instanceof BABYLON.Mesh) {
  54940. var geometry = mesh.geometry;
  54941. geometryId = geometry ? geometry.id : null;
  54942. }
  54943. else if (mesh instanceof BABYLON.InstancedMesh) {
  54944. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54945. geometryId = geometry ? geometry.id : null;
  54946. }
  54947. var boundingInfo = mesh.getBoundingInfo();
  54948. return {
  54949. uniqueId: mesh.uniqueId,
  54950. id: mesh.id,
  54951. name: mesh.name,
  54952. geometryId: geometryId,
  54953. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54954. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54955. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54956. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54957. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54958. subMeshes: submeshes,
  54959. checkCollisions: mesh.checkCollisions
  54960. };
  54961. };
  54962. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54963. return {
  54964. id: geometry.id,
  54965. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54966. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54967. indices: new Uint32Array(geometry.getIndices() || []),
  54968. };
  54969. };
  54970. return CollisionCoordinatorWorker;
  54971. }());
  54972. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54973. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54974. function CollisionCoordinatorLegacy() {
  54975. this._scaledPosition = BABYLON.Vector3.Zero();
  54976. this._scaledVelocity = BABYLON.Vector3.Zero();
  54977. this._finalPosition = BABYLON.Vector3.Zero();
  54978. }
  54979. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54980. position.divideToRef(collider._radius, this._scaledPosition);
  54981. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54982. collider.collidedMesh = null;
  54983. collider._retry = 0;
  54984. collider._initialVelocity = this._scaledVelocity;
  54985. collider._initialPosition = this._scaledPosition;
  54986. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54987. this._finalPosition.multiplyInPlace(collider._radius);
  54988. //run the callback
  54989. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54990. };
  54991. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54992. this._scene = scene;
  54993. };
  54994. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54995. //Legacy need no destruction method.
  54996. };
  54997. //No update in legacy mode
  54998. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54999. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55000. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55001. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55002. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55003. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55004. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55005. if (excludedMesh === void 0) { excludedMesh = null; }
  55006. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55007. if (collider._retry >= maximumRetry) {
  55008. finalPosition.copyFrom(position);
  55009. return;
  55010. }
  55011. // Check if this is a mesh else camera or -1
  55012. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55013. collider._initialize(position, velocity, closeDistance);
  55014. // Check all meshes
  55015. for (var index = 0; index < this._scene.meshes.length; index++) {
  55016. var mesh = this._scene.meshes[index];
  55017. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55018. mesh._checkCollision(collider);
  55019. }
  55020. }
  55021. if (!collider.collisionFound) {
  55022. position.addToRef(velocity, finalPosition);
  55023. return;
  55024. }
  55025. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55026. collider._getResponse(position, velocity);
  55027. }
  55028. if (velocity.length() <= closeDistance) {
  55029. finalPosition.copyFrom(position);
  55030. return;
  55031. }
  55032. collider._retry++;
  55033. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55034. };
  55035. return CollisionCoordinatorLegacy;
  55036. }());
  55037. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55038. })(BABYLON || (BABYLON = {}));
  55039. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55040. var BABYLON;
  55041. (function (BABYLON) {
  55042. /**
  55043. * A particle represents one of the element emitted by a particle system.
  55044. * This is mainly define by its coordinates, direction, velocity and age.
  55045. */
  55046. var Particle = /** @class */ (function () {
  55047. /**
  55048. * Creates a new instance Particle
  55049. * @param particleSystem the particle system the particle belongs to
  55050. */
  55051. function Particle(
  55052. /**
  55053. * particleSystem the particle system the particle belongs to.
  55054. */
  55055. particleSystem) {
  55056. this.particleSystem = particleSystem;
  55057. /**
  55058. * The world position of the particle in the scene.
  55059. */
  55060. this.position = BABYLON.Vector3.Zero();
  55061. /**
  55062. * The world direction of the particle in the scene.
  55063. */
  55064. this.direction = BABYLON.Vector3.Zero();
  55065. /**
  55066. * The color of the particle.
  55067. */
  55068. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55069. /**
  55070. * The color change of the particle per step.
  55071. */
  55072. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55073. /**
  55074. * Defines how long will the life of the particle be.
  55075. */
  55076. this.lifeTime = 1.0;
  55077. /**
  55078. * The current age of the particle.
  55079. */
  55080. this.age = 0;
  55081. /**
  55082. * The current size of the particle.
  55083. */
  55084. this.size = 0;
  55085. /**
  55086. * The current angle of the particle.
  55087. */
  55088. this.angle = 0;
  55089. /**
  55090. * Defines how fast is the angle changing.
  55091. */
  55092. this.angularSpeed = 0;
  55093. /**
  55094. * Defines the cell index used by the particle to be rendered from a sprite.
  55095. */
  55096. this.cellIndex = 0;
  55097. this._currentFrameCounter = 0;
  55098. if (!this.particleSystem.isAnimationSheetEnabled) {
  55099. return;
  55100. }
  55101. this.updateCellInfoFromSystem();
  55102. }
  55103. Particle.prototype.updateCellInfoFromSystem = function () {
  55104. this.cellIndex = this.particleSystem.startSpriteCellID;
  55105. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55106. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55107. }
  55108. else {
  55109. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55110. }
  55111. };
  55112. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55113. // (ageOffset / scaledUpdateSpeed) / available cells
  55114. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55115. this._currentFrameCounter += scaledUpdateSpeed;
  55116. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55117. this._currentFrameCounter = 0;
  55118. this.cellIndex++;
  55119. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55120. this.cellIndex = this.particleSystem.endSpriteCellID;
  55121. }
  55122. }
  55123. };
  55124. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55125. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55126. this.cellIndex++;
  55127. this._currentFrameCounter = 0;
  55128. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55129. if (this.particleSystem.spriteCellLoop) {
  55130. this.cellIndex = this.particleSystem.startSpriteCellID;
  55131. }
  55132. else {
  55133. this.cellIndex = this.particleSystem.endSpriteCellID;
  55134. }
  55135. }
  55136. }
  55137. else {
  55138. this._currentFrameCounter++;
  55139. }
  55140. };
  55141. /**
  55142. * Copy the properties of particle to another one.
  55143. * @param other the particle to copy the information to.
  55144. */
  55145. Particle.prototype.copyTo = function (other) {
  55146. other.position.copyFrom(this.position);
  55147. other.direction.copyFrom(this.direction);
  55148. other.color.copyFrom(this.color);
  55149. other.colorStep.copyFrom(this.colorStep);
  55150. other.lifeTime = this.lifeTime;
  55151. other.age = this.age;
  55152. other.size = this.size;
  55153. other.angle = this.angle;
  55154. other.angularSpeed = this.angularSpeed;
  55155. other.particleSystem = this.particleSystem;
  55156. other.cellIndex = this.cellIndex;
  55157. };
  55158. return Particle;
  55159. }());
  55160. BABYLON.Particle = Particle;
  55161. })(BABYLON || (BABYLON = {}));
  55162. //# sourceMappingURL=babylon.particle.js.map
  55163. var BABYLON;
  55164. (function (BABYLON) {
  55165. /**
  55166. * This represents a particle system in Babylon.
  55167. * 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.
  55168. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55169. * @example https://doc.babylonjs.com/babylon101/particles
  55170. */
  55171. var ParticleSystem = /** @class */ (function () {
  55172. /**
  55173. * Instantiates a particle system.
  55174. * 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.
  55175. * @param name The name of the particle system
  55176. * @param capacity The max number of particles alive at the same time
  55177. * @param scene The scene the particle system belongs to
  55178. * @param customEffect a custom effect used to change the way particles are rendered by default
  55179. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55180. * @param epsilon Offset used to render the particles
  55181. */
  55182. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55183. if (customEffect === void 0) { customEffect = null; }
  55184. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55185. if (epsilon === void 0) { epsilon = 0.01; }
  55186. var _this = this;
  55187. /**
  55188. * List of animations used by the particle system.
  55189. */
  55190. this.animations = [];
  55191. /**
  55192. * The rendering group used by the Particle system to chose when to render.
  55193. */
  55194. this.renderingGroupId = 0;
  55195. /**
  55196. * The emitter represents the Mesh or position we are attaching the particle system to.
  55197. */
  55198. this.emitter = null;
  55199. /**
  55200. * The maximum number of particles to emit per frame
  55201. */
  55202. this.emitRate = 10;
  55203. /**
  55204. * If you want to launch only a few particles at once, that can be done, as well.
  55205. */
  55206. this.manualEmitCount = -1;
  55207. /**
  55208. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55209. */
  55210. this.updateSpeed = 0.01;
  55211. /**
  55212. * The amount of time the particle system is running (depends of the overall update speed).
  55213. */
  55214. this.targetStopDuration = 0;
  55215. /**
  55216. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55217. */
  55218. this.disposeOnStop = false;
  55219. /**
  55220. * Minimum power of emitting particles.
  55221. */
  55222. this.minEmitPower = 1;
  55223. /**
  55224. * Maximum power of emitting particles.
  55225. */
  55226. this.maxEmitPower = 1;
  55227. /**
  55228. * Minimum life time of emitting particles.
  55229. */
  55230. this.minLifeTime = 1;
  55231. /**
  55232. * Maximum life time of emitting particles.
  55233. */
  55234. this.maxLifeTime = 1;
  55235. /**
  55236. * Minimum Size of emitting particles.
  55237. */
  55238. this.minSize = 1;
  55239. /**
  55240. * Maximum Size of emitting particles.
  55241. */
  55242. this.maxSize = 1;
  55243. /**
  55244. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55245. */
  55246. this.minAngularSpeed = 0;
  55247. /**
  55248. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55249. */
  55250. this.maxAngularSpeed = 0;
  55251. /**
  55252. * The layer mask we are rendering the particles through.
  55253. */
  55254. this.layerMask = 0x0FFFFFFF;
  55255. /**
  55256. * This can help using your own shader to render the particle system.
  55257. * The according effect will be created
  55258. */
  55259. this.customShader = null;
  55260. /**
  55261. * By default particle system starts as soon as they are created. This prevents the
  55262. * automatic start to happen and let you decide when to start emitting particles.
  55263. */
  55264. this.preventAutoStart = false;
  55265. /**
  55266. * Callback triggered when the particle animation is ending.
  55267. */
  55268. this.onAnimationEnd = null;
  55269. /**
  55270. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55271. */
  55272. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55273. /**
  55274. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55275. * to override the particles.
  55276. */
  55277. this.forceDepthWrite = false;
  55278. /**
  55279. * You can use gravity if you want to give an orientation to your particles.
  55280. */
  55281. this.gravity = BABYLON.Vector3.Zero();
  55282. /**
  55283. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55284. */
  55285. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55286. /**
  55287. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55288. */
  55289. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55290. /**
  55291. * Color the particle will have at the end of its lifetime.
  55292. */
  55293. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55294. /**
  55295. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55296. */
  55297. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55298. /**
  55299. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55300. */
  55301. this.spriteCellLoop = true;
  55302. /**
  55303. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55304. */
  55305. this.spriteCellChangeSpeed = 0;
  55306. /**
  55307. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55308. */
  55309. this.startSpriteCellID = 0;
  55310. /**
  55311. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55312. */
  55313. this.endSpriteCellID = 0;
  55314. /**
  55315. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55316. */
  55317. this.spriteCellWidth = 0;
  55318. /**
  55319. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55320. */
  55321. this.spriteCellHeight = 0;
  55322. /**
  55323. * An event triggered when the system is disposed.
  55324. */
  55325. this.onDisposeObservable = new BABYLON.Observable();
  55326. this._particles = new Array();
  55327. this._stockParticles = new Array();
  55328. this._newPartsExcess = 0;
  55329. this._vertexBuffers = {};
  55330. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55331. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55332. this._scaledDirection = BABYLON.Vector3.Zero();
  55333. this._scaledGravity = BABYLON.Vector3.Zero();
  55334. this._currentRenderId = -1;
  55335. this._started = false;
  55336. this._stopped = false;
  55337. this._actualFrame = 0;
  55338. this._vertexBufferSize = 11;
  55339. // start of sub system methods
  55340. /**
  55341. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55342. * Its lifetime will start back at 0.
  55343. */
  55344. this.recycleParticle = function (particle) {
  55345. var lastParticle = _this._particles.pop();
  55346. if (lastParticle !== particle) {
  55347. lastParticle.copyTo(particle);
  55348. }
  55349. _this._stockParticles.push(lastParticle);
  55350. };
  55351. this._createParticle = function () {
  55352. var particle;
  55353. if (_this._stockParticles.length !== 0) {
  55354. particle = _this._stockParticles.pop();
  55355. particle.age = 0;
  55356. particle.cellIndex = _this.startSpriteCellID;
  55357. }
  55358. else {
  55359. particle = new BABYLON.Particle(_this);
  55360. }
  55361. return particle;
  55362. };
  55363. this._emitFromParticle = function (particle) {
  55364. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55365. return;
  55366. }
  55367. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55368. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55369. subSystem._rootParticleSystem = _this;
  55370. _this.activeSubSystems.push(subSystem);
  55371. subSystem.start();
  55372. };
  55373. this._appendParticleVertexes = null;
  55374. this.id = name;
  55375. this.name = name;
  55376. this._capacity = capacity;
  55377. this._epsilon = epsilon;
  55378. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55379. if (isAnimationSheetEnabled) {
  55380. this._vertexBufferSize = 12;
  55381. }
  55382. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55383. this._customEffect = customEffect;
  55384. scene.particleSystems.push(this);
  55385. this._createIndexBuffer();
  55386. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55387. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55388. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55389. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55390. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55391. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55392. if (this._isAnimationSheetEnabled) {
  55393. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55394. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55395. }
  55396. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55397. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55398. this._vertexBuffers["options"] = options;
  55399. // Default emitter type
  55400. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55401. this.updateFunction = function (particles) {
  55402. for (var index = 0; index < particles.length; index++) {
  55403. var particle = particles[index];
  55404. particle.age += _this._scaledUpdateSpeed;
  55405. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55406. _this._emitFromParticle(particle);
  55407. _this.recycleParticle(particle);
  55408. index--;
  55409. continue;
  55410. }
  55411. else {
  55412. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55413. particle.color.addInPlace(_this._scaledColorStep);
  55414. if (particle.color.a < 0)
  55415. particle.color.a = 0;
  55416. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55417. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55418. particle.position.addInPlace(_this._scaledDirection);
  55419. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55420. particle.direction.addInPlace(_this._scaledGravity);
  55421. if (_this._isAnimationSheetEnabled) {
  55422. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55423. }
  55424. }
  55425. }
  55426. };
  55427. }
  55428. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55429. /**
  55430. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55431. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55432. */
  55433. get: function () {
  55434. if (this.particleEmitterType.direction1) {
  55435. return this.particleEmitterType.direction1;
  55436. }
  55437. return BABYLON.Vector3.Zero();
  55438. },
  55439. set: function (value) {
  55440. if (this.particleEmitterType.direction1) {
  55441. this.particleEmitterType.direction1 = value;
  55442. }
  55443. },
  55444. enumerable: true,
  55445. configurable: true
  55446. });
  55447. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55448. /**
  55449. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55450. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55451. */
  55452. get: function () {
  55453. if (this.particleEmitterType.direction2) {
  55454. return this.particleEmitterType.direction2;
  55455. }
  55456. return BABYLON.Vector3.Zero();
  55457. },
  55458. set: function (value) {
  55459. if (this.particleEmitterType.direction2) {
  55460. this.particleEmitterType.direction2 = value;
  55461. }
  55462. },
  55463. enumerable: true,
  55464. configurable: true
  55465. });
  55466. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55467. /**
  55468. * 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.
  55469. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55470. */
  55471. get: function () {
  55472. if (this.particleEmitterType.minEmitBox) {
  55473. return this.particleEmitterType.minEmitBox;
  55474. }
  55475. return BABYLON.Vector3.Zero();
  55476. },
  55477. set: function (value) {
  55478. if (this.particleEmitterType.minEmitBox) {
  55479. this.particleEmitterType.minEmitBox = value;
  55480. }
  55481. },
  55482. enumerable: true,
  55483. configurable: true
  55484. });
  55485. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55486. /**
  55487. * 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.
  55488. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55489. */
  55490. get: function () {
  55491. if (this.particleEmitterType.maxEmitBox) {
  55492. return this.particleEmitterType.maxEmitBox;
  55493. }
  55494. return BABYLON.Vector3.Zero();
  55495. },
  55496. set: function (value) {
  55497. if (this.particleEmitterType.maxEmitBox) {
  55498. this.particleEmitterType.maxEmitBox = value;
  55499. }
  55500. },
  55501. enumerable: true,
  55502. configurable: true
  55503. });
  55504. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55505. /**
  55506. * Sets a callback that will be triggered when the system is disposed.
  55507. */
  55508. set: function (callback) {
  55509. if (this._onDisposeObserver) {
  55510. this.onDisposeObservable.remove(this._onDisposeObserver);
  55511. }
  55512. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55513. },
  55514. enumerable: true,
  55515. configurable: true
  55516. });
  55517. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55518. /**
  55519. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55520. */
  55521. get: function () {
  55522. return this._isAnimationSheetEnabled;
  55523. },
  55524. enumerable: true,
  55525. configurable: true
  55526. });
  55527. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55528. //end of Sub-emitter
  55529. /**
  55530. * Gets the current list of active particles
  55531. */
  55532. get: function () {
  55533. return this._particles;
  55534. },
  55535. enumerable: true,
  55536. configurable: true
  55537. });
  55538. /**
  55539. * Returns the string "ParticleSystem"
  55540. * @returns a string containing the class name
  55541. */
  55542. ParticleSystem.prototype.getClassName = function () {
  55543. return "ParticleSystem";
  55544. };
  55545. ParticleSystem.prototype._createIndexBuffer = function () {
  55546. var indices = [];
  55547. var index = 0;
  55548. for (var count = 0; count < this._capacity; count++) {
  55549. indices.push(index);
  55550. indices.push(index + 1);
  55551. indices.push(index + 2);
  55552. indices.push(index);
  55553. indices.push(index + 2);
  55554. indices.push(index + 3);
  55555. index += 4;
  55556. }
  55557. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55558. };
  55559. /**
  55560. * Gets the maximum number of particles active at the same time.
  55561. * @returns The max number of active particles.
  55562. */
  55563. ParticleSystem.prototype.getCapacity = function () {
  55564. return this._capacity;
  55565. };
  55566. /**
  55567. * Gets Wether there are still active particles in the system.
  55568. * @returns True if it is alive, otherwise false.
  55569. */
  55570. ParticleSystem.prototype.isAlive = function () {
  55571. return this._alive;
  55572. };
  55573. /**
  55574. * Gets Wether the system has been started.
  55575. * @returns True if it has been started, otherwise false.
  55576. */
  55577. ParticleSystem.prototype.isStarted = function () {
  55578. return this._started;
  55579. };
  55580. /**
  55581. * Starts the particle system and begins to emit.
  55582. */
  55583. ParticleSystem.prototype.start = function () {
  55584. this._started = true;
  55585. this._stopped = false;
  55586. this._actualFrame = 0;
  55587. if (this.subEmitters && this.subEmitters.length != 0) {
  55588. this.activeSubSystems = new Array();
  55589. }
  55590. };
  55591. /**
  55592. * Stops the particle system.
  55593. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  55594. */
  55595. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55596. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55597. this._stopped = true;
  55598. if (stopSubEmitters) {
  55599. this._stopSubEmitters();
  55600. }
  55601. };
  55602. // animation sheet
  55603. /**
  55604. * Remove all active particles
  55605. */
  55606. ParticleSystem.prototype.reset = function () {
  55607. this._stockParticles = [];
  55608. this._particles = [];
  55609. };
  55610. /**
  55611. * @ignore (for internal use only)
  55612. */
  55613. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55614. var offset = index * this._vertexBufferSize;
  55615. this._vertexData[offset] = particle.position.x;
  55616. this._vertexData[offset + 1] = particle.position.y;
  55617. this._vertexData[offset + 2] = particle.position.z;
  55618. this._vertexData[offset + 3] = particle.color.r;
  55619. this._vertexData[offset + 4] = particle.color.g;
  55620. this._vertexData[offset + 5] = particle.color.b;
  55621. this._vertexData[offset + 6] = particle.color.a;
  55622. this._vertexData[offset + 7] = particle.angle;
  55623. this._vertexData[offset + 8] = particle.size;
  55624. this._vertexData[offset + 9] = offsetX;
  55625. this._vertexData[offset + 10] = offsetY;
  55626. };
  55627. /**
  55628. * @ignore (for internal use only)
  55629. */
  55630. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55631. if (offsetX === 0)
  55632. offsetX = this._epsilon;
  55633. else if (offsetX === 1)
  55634. offsetX = 1 - this._epsilon;
  55635. if (offsetY === 0)
  55636. offsetY = this._epsilon;
  55637. else if (offsetY === 1)
  55638. offsetY = 1 - this._epsilon;
  55639. var offset = index * this._vertexBufferSize;
  55640. this._vertexData[offset] = particle.position.x;
  55641. this._vertexData[offset + 1] = particle.position.y;
  55642. this._vertexData[offset + 2] = particle.position.z;
  55643. this._vertexData[offset + 3] = particle.color.r;
  55644. this._vertexData[offset + 4] = particle.color.g;
  55645. this._vertexData[offset + 5] = particle.color.b;
  55646. this._vertexData[offset + 6] = particle.color.a;
  55647. this._vertexData[offset + 7] = particle.angle;
  55648. this._vertexData[offset + 8] = particle.size;
  55649. this._vertexData[offset + 9] = offsetX;
  55650. this._vertexData[offset + 10] = offsetY;
  55651. this._vertexData[offset + 11] = particle.cellIndex;
  55652. };
  55653. ParticleSystem.prototype._stopSubEmitters = function () {
  55654. if (!this.activeSubSystems) {
  55655. return;
  55656. }
  55657. this.activeSubSystems.forEach(function (subSystem) {
  55658. subSystem.stop(true);
  55659. });
  55660. this.activeSubSystems = new Array();
  55661. };
  55662. ParticleSystem.prototype._removeFromRoot = function () {
  55663. if (!this._rootParticleSystem) {
  55664. return;
  55665. }
  55666. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55667. if (index !== -1) {
  55668. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55669. }
  55670. };
  55671. // end of sub system methods
  55672. ParticleSystem.prototype._update = function (newParticles) {
  55673. // Update current
  55674. this._alive = this._particles.length > 0;
  55675. this.updateFunction(this._particles);
  55676. // Add new ones
  55677. var worldMatrix;
  55678. if (this.emitter.position) {
  55679. var emitterMesh = this.emitter;
  55680. worldMatrix = emitterMesh.getWorldMatrix();
  55681. }
  55682. else {
  55683. var emitterPosition = this.emitter;
  55684. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55685. }
  55686. var particle;
  55687. for (var index = 0; index < newParticles; index++) {
  55688. if (this._particles.length === this._capacity) {
  55689. break;
  55690. }
  55691. particle = this._createParticle();
  55692. this._particles.push(particle);
  55693. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55694. if (this.startPositionFunction) {
  55695. this.startPositionFunction(worldMatrix, particle.position, particle);
  55696. }
  55697. else {
  55698. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55699. }
  55700. if (this.startDirectionFunction) {
  55701. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55702. }
  55703. else {
  55704. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55705. }
  55706. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55707. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55708. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55709. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55710. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55711. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55712. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55713. }
  55714. };
  55715. ParticleSystem.prototype._getEffect = function () {
  55716. if (this._customEffect) {
  55717. return this._customEffect;
  55718. }
  55719. ;
  55720. var defines = [];
  55721. if (this._scene.clipPlane) {
  55722. defines.push("#define CLIPPLANE");
  55723. }
  55724. if (this._isAnimationSheetEnabled) {
  55725. defines.push("#define ANIMATESHEET");
  55726. }
  55727. // Effect
  55728. var join = defines.join("\n");
  55729. if (this._cachedDefines !== join) {
  55730. this._cachedDefines = join;
  55731. var attributesNamesOrOptions;
  55732. var effectCreationOption;
  55733. if (this._isAnimationSheetEnabled) {
  55734. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  55735. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55736. }
  55737. else {
  55738. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  55739. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55740. }
  55741. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55742. }
  55743. return this._effect;
  55744. };
  55745. /**
  55746. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55747. */
  55748. ParticleSystem.prototype.animate = function () {
  55749. if (!this._started)
  55750. return;
  55751. var effect = this._getEffect();
  55752. // Check
  55753. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55754. return;
  55755. if (this._currentRenderId === this._scene.getRenderId()) {
  55756. return;
  55757. }
  55758. this._currentRenderId = this._scene.getRenderId();
  55759. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55760. // determine the number of particles we need to create
  55761. var newParticles;
  55762. if (this.manualEmitCount > -1) {
  55763. newParticles = this.manualEmitCount;
  55764. this._newPartsExcess = 0;
  55765. this.manualEmitCount = 0;
  55766. }
  55767. else {
  55768. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55769. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55770. }
  55771. if (this._newPartsExcess > 1.0) {
  55772. newParticles += this._newPartsExcess >> 0;
  55773. this._newPartsExcess -= this._newPartsExcess >> 0;
  55774. }
  55775. this._alive = false;
  55776. if (!this._stopped) {
  55777. this._actualFrame += this._scaledUpdateSpeed;
  55778. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55779. this.stop();
  55780. }
  55781. else {
  55782. newParticles = 0;
  55783. }
  55784. this._update(newParticles);
  55785. // Stopped?
  55786. if (this._stopped) {
  55787. if (!this._alive) {
  55788. this._started = false;
  55789. if (this.onAnimationEnd) {
  55790. this.onAnimationEnd();
  55791. }
  55792. if (this.disposeOnStop) {
  55793. this._scene._toBeDisposed.push(this);
  55794. }
  55795. }
  55796. }
  55797. // Animation sheet
  55798. if (this._isAnimationSheetEnabled) {
  55799. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55800. }
  55801. else {
  55802. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55803. }
  55804. // Update VBO
  55805. var offset = 0;
  55806. for (var index = 0; index < this._particles.length; index++) {
  55807. var particle = this._particles[index];
  55808. this._appendParticleVertexes(offset, particle);
  55809. offset += 4;
  55810. }
  55811. if (this._vertexBuffer) {
  55812. this._vertexBuffer.update(this._vertexData);
  55813. }
  55814. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55815. this.stop();
  55816. }
  55817. };
  55818. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55819. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55820. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55821. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55822. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55823. };
  55824. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55825. this._appendParticleVertex(offset++, particle, 0, 0);
  55826. this._appendParticleVertex(offset++, particle, 1, 0);
  55827. this._appendParticleVertex(offset++, particle, 1, 1);
  55828. this._appendParticleVertex(offset++, particle, 0, 1);
  55829. };
  55830. /**
  55831. * Rebuilds the particle system.
  55832. */
  55833. ParticleSystem.prototype.rebuild = function () {
  55834. this._createIndexBuffer();
  55835. if (this._vertexBuffer) {
  55836. this._vertexBuffer._rebuild();
  55837. }
  55838. };
  55839. /**
  55840. * Is this system ready to be used/rendered
  55841. * @return true if the system is ready
  55842. */
  55843. ParticleSystem.prototype.isReady = function () {
  55844. var effect = this._getEffect();
  55845. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55846. return false;
  55847. }
  55848. return true;
  55849. };
  55850. /**
  55851. * Renders the particle system in its current state.
  55852. * @returns the current number of particles
  55853. */
  55854. ParticleSystem.prototype.render = function () {
  55855. var effect = this._getEffect();
  55856. // Check
  55857. if (!this.isReady() || !this._particles.length) {
  55858. return 0;
  55859. }
  55860. var engine = this._scene.getEngine();
  55861. // Render
  55862. engine.enableEffect(effect);
  55863. engine.setState(false);
  55864. var viewMatrix = this._scene.getViewMatrix();
  55865. effect.setTexture("diffuseSampler", this.particleTexture);
  55866. effect.setMatrix("view", viewMatrix);
  55867. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55868. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55869. var baseSize = this.particleTexture.getBaseSize();
  55870. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55871. }
  55872. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55873. if (this._scene.clipPlane) {
  55874. var clipPlane = this._scene.clipPlane;
  55875. var invView = viewMatrix.clone();
  55876. invView.invert();
  55877. effect.setMatrix("invView", invView);
  55878. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55879. }
  55880. // VBOs
  55881. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55882. // Draw order
  55883. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55884. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55885. }
  55886. else {
  55887. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55888. }
  55889. if (this.forceDepthWrite) {
  55890. engine.setDepthWrite(true);
  55891. }
  55892. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55893. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55894. return this._particles.length;
  55895. };
  55896. /**
  55897. * Disposes the particle system and free the associated resources
  55898. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55899. */
  55900. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55901. if (disposeTexture === void 0) { disposeTexture = true; }
  55902. if (this._vertexBuffer) {
  55903. this._vertexBuffer.dispose();
  55904. this._vertexBuffer = null;
  55905. }
  55906. if (this._indexBuffer) {
  55907. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55908. this._indexBuffer = null;
  55909. }
  55910. if (disposeTexture && this.particleTexture) {
  55911. this.particleTexture.dispose();
  55912. this.particleTexture = null;
  55913. }
  55914. this._removeFromRoot();
  55915. // Remove from scene
  55916. var index = this._scene.particleSystems.indexOf(this);
  55917. if (index > -1) {
  55918. this._scene.particleSystems.splice(index, 1);
  55919. }
  55920. // Callback
  55921. this.onDisposeObservable.notifyObservers(this);
  55922. this.onDisposeObservable.clear();
  55923. };
  55924. /**
  55925. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55926. * @param radius The radius of the sphere to emit from
  55927. * @returns the emitter
  55928. */
  55929. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55930. if (radius === void 0) { radius = 1; }
  55931. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55932. this.particleEmitterType = particleEmitter;
  55933. return particleEmitter;
  55934. };
  55935. /**
  55936. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55937. * @param radius The radius of the sphere to emit from
  55938. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55939. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55940. * @returns the emitter
  55941. */
  55942. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55943. if (radius === void 0) { radius = 1; }
  55944. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55945. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55946. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55947. this.particleEmitterType = particleEmitter;
  55948. return particleEmitter;
  55949. };
  55950. /**
  55951. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55952. * @param radius The radius of the cone to emit from
  55953. * @param angle The base angle of the cone
  55954. * @returns the emitter
  55955. */
  55956. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55957. if (radius === void 0) { radius = 1; }
  55958. if (angle === void 0) { angle = Math.PI / 4; }
  55959. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55960. this.particleEmitterType = particleEmitter;
  55961. return particleEmitter;
  55962. };
  55963. // 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.
  55964. /**
  55965. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55966. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55967. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55968. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55969. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55970. * @returns the emitter
  55971. */
  55972. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55973. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55974. this.particleEmitterType = particleEmitter;
  55975. this.direction1 = direction1;
  55976. this.direction2 = direction2;
  55977. this.minEmitBox = minEmitBox;
  55978. this.maxEmitBox = maxEmitBox;
  55979. return particleEmitter;
  55980. };
  55981. // Clone
  55982. /**
  55983. * Clones the particle system.
  55984. * @param name The name of the cloned object
  55985. * @param newEmitter The new emitter to use
  55986. * @returns the cloned particle system
  55987. */
  55988. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55989. var custom = null;
  55990. var program = null;
  55991. if (this.customShader != null) {
  55992. program = this.customShader;
  55993. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55994. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55995. }
  55996. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55997. result.customShader = program;
  55998. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55999. if (newEmitter === undefined) {
  56000. newEmitter = this.emitter;
  56001. }
  56002. result.emitter = newEmitter;
  56003. if (this.particleTexture) {
  56004. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56005. }
  56006. if (!this.preventAutoStart) {
  56007. result.start();
  56008. }
  56009. return result;
  56010. };
  56011. /**
  56012. * Serializes the particle system to a JSON object.
  56013. * @returns the JSON object
  56014. */
  56015. ParticleSystem.prototype.serialize = function () {
  56016. var serializationObject = {};
  56017. serializationObject.name = this.name;
  56018. serializationObject.id = this.id;
  56019. // Emitter
  56020. if (this.emitter.position) {
  56021. var emitterMesh = this.emitter;
  56022. serializationObject.emitterId = emitterMesh.id;
  56023. }
  56024. else {
  56025. var emitterPosition = this.emitter;
  56026. serializationObject.emitter = emitterPosition.asArray();
  56027. }
  56028. serializationObject.capacity = this.getCapacity();
  56029. if (this.particleTexture) {
  56030. serializationObject.textureName = this.particleTexture.name;
  56031. }
  56032. // Animations
  56033. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56034. // Particle system
  56035. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56036. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56037. serializationObject.minSize = this.minSize;
  56038. serializationObject.maxSize = this.maxSize;
  56039. serializationObject.minEmitPower = this.minEmitPower;
  56040. serializationObject.maxEmitPower = this.maxEmitPower;
  56041. serializationObject.minLifeTime = this.minLifeTime;
  56042. serializationObject.maxLifeTime = this.maxLifeTime;
  56043. serializationObject.emitRate = this.emitRate;
  56044. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56045. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56046. serializationObject.gravity = this.gravity.asArray();
  56047. serializationObject.direction1 = this.direction1.asArray();
  56048. serializationObject.direction2 = this.direction2.asArray();
  56049. serializationObject.color1 = this.color1.asArray();
  56050. serializationObject.color2 = this.color2.asArray();
  56051. serializationObject.colorDead = this.colorDead.asArray();
  56052. serializationObject.updateSpeed = this.updateSpeed;
  56053. serializationObject.targetStopDuration = this.targetStopDuration;
  56054. serializationObject.textureMask = this.textureMask.asArray();
  56055. serializationObject.blendMode = this.blendMode;
  56056. serializationObject.customShader = this.customShader;
  56057. serializationObject.preventAutoStart = this.preventAutoStart;
  56058. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56059. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56060. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56061. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56062. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56063. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56064. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56065. // Emitter
  56066. if (this.particleEmitterType) {
  56067. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56068. }
  56069. return serializationObject;
  56070. };
  56071. /**
  56072. * Parses a JSON object to create a particle system.
  56073. * @param parsedParticleSystem The JSON object to parse
  56074. * @param scene The scene to create the particle system in
  56075. * @param rootUrl The root url to use to load external dependencies like texture
  56076. * @returns the Parsed particle system
  56077. */
  56078. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56079. var name = parsedParticleSystem.name;
  56080. var custom = null;
  56081. var program = null;
  56082. if (parsedParticleSystem.customShader) {
  56083. program = parsedParticleSystem.customShader;
  56084. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56085. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56086. }
  56087. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56088. particleSystem.customShader = program;
  56089. if (parsedParticleSystem.id) {
  56090. particleSystem.id = parsedParticleSystem.id;
  56091. }
  56092. // Auto start
  56093. if (parsedParticleSystem.preventAutoStart) {
  56094. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56095. }
  56096. // Texture
  56097. if (parsedParticleSystem.textureName) {
  56098. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56099. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56100. }
  56101. // Emitter
  56102. if (parsedParticleSystem.emitterId) {
  56103. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56104. }
  56105. else {
  56106. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56107. }
  56108. // Animations
  56109. if (parsedParticleSystem.animations) {
  56110. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56111. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56112. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56113. }
  56114. }
  56115. if (parsedParticleSystem.autoAnimate) {
  56116. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56117. }
  56118. // Particle system
  56119. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56120. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56121. particleSystem.minSize = parsedParticleSystem.minSize;
  56122. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56123. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56124. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56125. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56126. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56127. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56128. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56129. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56130. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56131. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56132. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56133. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56134. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56135. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56136. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56137. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56138. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56139. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56140. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56141. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56142. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56143. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56144. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56145. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56146. if (!particleSystem.preventAutoStart) {
  56147. particleSystem.start();
  56148. }
  56149. return particleSystem;
  56150. };
  56151. /**
  56152. * Source color is added to the destination color without alpha affecting the result.
  56153. */
  56154. ParticleSystem.BLENDMODE_ONEONE = 0;
  56155. /**
  56156. * Blend current color and particle color using particle’s alpha.
  56157. */
  56158. ParticleSystem.BLENDMODE_STANDARD = 1;
  56159. return ParticleSystem;
  56160. }());
  56161. BABYLON.ParticleSystem = ParticleSystem;
  56162. })(BABYLON || (BABYLON = {}));
  56163. //# sourceMappingURL=babylon.particleSystem.js.map
  56164. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56165. var BABYLON;
  56166. (function (BABYLON) {
  56167. /**
  56168. * Particle emitter emitting particles from the inside of a box.
  56169. * It emits the particles randomly between 2 given directions.
  56170. */
  56171. var BoxParticleEmitter = /** @class */ (function () {
  56172. /**
  56173. * Creates a new instance BoxParticleEmitter
  56174. */
  56175. function BoxParticleEmitter() {
  56176. /**
  56177. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56178. */
  56179. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56180. /**
  56181. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56182. */
  56183. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56184. /**
  56185. * 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.
  56186. */
  56187. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56188. /**
  56189. * 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.
  56190. */
  56191. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56192. }
  56193. /**
  56194. * Called by the particle System when the direction is computed for the created particle.
  56195. * @param emitPower is the power of the particle (speed)
  56196. * @param worldMatrix is the world matrix of the particle system
  56197. * @param directionToUpdate is the direction vector to update with the result
  56198. * @param particle is the particle we are computed the direction for
  56199. */
  56200. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56201. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56202. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56203. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56204. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56205. };
  56206. /**
  56207. * Called by the particle System when the position is computed for the created particle.
  56208. * @param worldMatrix is the world matrix of the particle system
  56209. * @param positionToUpdate is the position vector to update with the result
  56210. * @param particle is the particle we are computed the position for
  56211. */
  56212. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56213. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56214. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56215. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56216. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56217. };
  56218. /**
  56219. * Clones the current emitter and returns a copy of it
  56220. * @returns the new emitter
  56221. */
  56222. BoxParticleEmitter.prototype.clone = function () {
  56223. var newOne = new BoxParticleEmitter();
  56224. BABYLON.Tools.DeepCopy(this, newOne);
  56225. return newOne;
  56226. };
  56227. /**
  56228. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56229. * @param effect defines the update shader
  56230. */
  56231. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56232. effect.setVector3("direction1", this.direction1);
  56233. effect.setVector3("direction2", this.direction2);
  56234. effect.setVector3("minEmitBox", this.minEmitBox);
  56235. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56236. };
  56237. /**
  56238. * Returns a string to use to update the GPU particles update shader
  56239. * @returns a string containng the defines string
  56240. */
  56241. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56242. return "#define BOXEMITTER";
  56243. };
  56244. /**
  56245. * Returns the string "BoxEmitter"
  56246. * @returns a string containing the class name
  56247. */
  56248. BoxParticleEmitter.prototype.getClassName = function () {
  56249. return "BoxEmitter";
  56250. };
  56251. /**
  56252. * Serializes the particle system to a JSON object.
  56253. * @returns the JSON object
  56254. */
  56255. BoxParticleEmitter.prototype.serialize = function () {
  56256. var serializationObject = {};
  56257. serializationObject.type = this.getClassName();
  56258. serializationObject.direction1 = this.direction1.asArray();
  56259. ;
  56260. serializationObject.direction2 = this.direction2.asArray();
  56261. ;
  56262. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56263. ;
  56264. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56265. ;
  56266. return serializationObject;
  56267. };
  56268. /**
  56269. * Parse properties from a JSON object
  56270. * @param serializationObject defines the JSON object
  56271. */
  56272. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56273. this.direction1.copyFrom(serializationObject.direction1);
  56274. this.direction2.copyFrom(serializationObject.direction2);
  56275. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56276. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56277. };
  56278. return BoxParticleEmitter;
  56279. }());
  56280. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56281. })(BABYLON || (BABYLON = {}));
  56282. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56283. var BABYLON;
  56284. (function (BABYLON) {
  56285. /**
  56286. * Particle emitter emitting particles from the inside of a cone.
  56287. * It emits the particles alongside the cone volume from the base to the particle.
  56288. * The emission direction might be randomized.
  56289. */
  56290. var ConeParticleEmitter = /** @class */ (function () {
  56291. /**
  56292. * Creates a new instance ConeParticleEmitter
  56293. * @param radius the radius of the emission cone (1 by default)
  56294. * @param angles the cone base angle (PI by default)
  56295. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56296. */
  56297. function ConeParticleEmitter(radius,
  56298. /**
  56299. * The radius of the emission cone.
  56300. */
  56301. angle,
  56302. /**
  56303. * The cone base angle.
  56304. */
  56305. directionRandomizer) {
  56306. if (radius === void 0) { radius = 1; }
  56307. if (angle === void 0) { angle = Math.PI; }
  56308. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56309. this.angle = angle;
  56310. this.directionRandomizer = directionRandomizer;
  56311. this.radius = radius;
  56312. }
  56313. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56314. /**
  56315. * Gets the radius of the emission cone.
  56316. */
  56317. get: function () {
  56318. return this._radius;
  56319. },
  56320. /**
  56321. * Sets the radius of the emission cone.
  56322. */
  56323. set: function (value) {
  56324. this._radius = value;
  56325. if (this.angle !== 0) {
  56326. this._height = value / Math.tan(this.angle / 2);
  56327. }
  56328. else {
  56329. this._height = 1;
  56330. }
  56331. },
  56332. enumerable: true,
  56333. configurable: true
  56334. });
  56335. /**
  56336. * Called by the particle System when the direction is computed for the created particle.
  56337. * @param emitPower is the power of the particle (speed)
  56338. * @param worldMatrix is the world matrix of the particle system
  56339. * @param directionToUpdate is the direction vector to update with the result
  56340. * @param particle is the particle we are computed the direction for
  56341. */
  56342. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56343. if (this.angle === 0) {
  56344. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56345. }
  56346. else {
  56347. // measure the direction Vector from the emitter to the particle.
  56348. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56349. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56350. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56351. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56352. direction.x += randX;
  56353. direction.y += randY;
  56354. direction.z += randZ;
  56355. direction.normalize();
  56356. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56357. }
  56358. };
  56359. /**
  56360. * Called by the particle System when the position is computed for the created particle.
  56361. * @param worldMatrix is the world matrix of the particle system
  56362. * @param positionToUpdate is the position vector to update with the result
  56363. * @param particle is the particle we are computed the position for
  56364. */
  56365. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56366. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56367. var h = BABYLON.Scalar.RandomRange(0, 1);
  56368. // Better distribution in a cone at normal angles.
  56369. h = 1 - h * h;
  56370. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56371. radius = radius * h;
  56372. var randX = radius * Math.sin(s);
  56373. var randZ = radius * Math.cos(s);
  56374. var randY = h * this._height;
  56375. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56376. };
  56377. /**
  56378. * Clones the current emitter and returns a copy of it
  56379. * @returns the new emitter
  56380. */
  56381. ConeParticleEmitter.prototype.clone = function () {
  56382. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56383. BABYLON.Tools.DeepCopy(this, newOne);
  56384. return newOne;
  56385. };
  56386. /**
  56387. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56388. * @param effect defines the update shader
  56389. */
  56390. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56391. effect.setFloat("radius", this.radius);
  56392. effect.setFloat("angle", this.angle);
  56393. effect.setFloat("height", this._height);
  56394. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56395. };
  56396. /**
  56397. * Returns a string to use to update the GPU particles update shader
  56398. * @returns a string containng the defines string
  56399. */
  56400. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56401. return "#define CONEEMITTER";
  56402. };
  56403. /**
  56404. * Returns the string "BoxEmitter"
  56405. * @returns a string containing the class name
  56406. */
  56407. ConeParticleEmitter.prototype.getClassName = function () {
  56408. return "ConeEmitter";
  56409. };
  56410. /**
  56411. * Serializes the particle system to a JSON object.
  56412. * @returns the JSON object
  56413. */
  56414. ConeParticleEmitter.prototype.serialize = function () {
  56415. var serializationObject = {};
  56416. serializationObject.type = this.getClassName();
  56417. serializationObject.radius = this.radius;
  56418. serializationObject.angle = this.angle;
  56419. serializationObject.directionRandomizer = this.directionRandomizer;
  56420. return serializationObject;
  56421. };
  56422. /**
  56423. * Parse properties from a JSON object
  56424. * @param serializationObject defines the JSON object
  56425. */
  56426. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56427. this.radius = serializationObject.radius;
  56428. this.angle = serializationObject.angle;
  56429. this.directionRandomizer = serializationObject.directionRandomizer;
  56430. };
  56431. return ConeParticleEmitter;
  56432. }());
  56433. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56434. })(BABYLON || (BABYLON = {}));
  56435. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56436. var BABYLON;
  56437. (function (BABYLON) {
  56438. /**
  56439. * Particle emitter emitting particles from the inside of a sphere.
  56440. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56441. */
  56442. var SphereParticleEmitter = /** @class */ (function () {
  56443. /**
  56444. * Creates a new instance SphereParticleEmitter
  56445. * @param radius the radius of the emission sphere (1 by default)
  56446. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56447. */
  56448. function SphereParticleEmitter(
  56449. /**
  56450. * The radius of the emission sphere.
  56451. */
  56452. radius,
  56453. /**
  56454. * How much to randomize the particle direction [0-1].
  56455. */
  56456. directionRandomizer) {
  56457. if (radius === void 0) { radius = 1; }
  56458. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56459. this.radius = radius;
  56460. this.directionRandomizer = directionRandomizer;
  56461. }
  56462. /**
  56463. * Called by the particle System when the direction is computed for the created particle.
  56464. * @param emitPower is the power of the particle (speed)
  56465. * @param worldMatrix is the world matrix of the particle system
  56466. * @param directionToUpdate is the direction vector to update with the result
  56467. * @param particle is the particle we are computed the direction for
  56468. */
  56469. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56470. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56471. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56472. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56473. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56474. direction.x += randX;
  56475. direction.y += randY;
  56476. direction.z += randZ;
  56477. direction.normalize();
  56478. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56479. };
  56480. /**
  56481. * Called by the particle System when the position is computed for the created particle.
  56482. * @param worldMatrix is the world matrix of the particle system
  56483. * @param positionToUpdate is the position vector to update with the result
  56484. * @param particle is the particle we are computed the position for
  56485. */
  56486. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56487. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56488. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56489. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56490. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56491. var randY = randRadius * Math.cos(theta);
  56492. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56493. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56494. };
  56495. /**
  56496. * Clones the current emitter and returns a copy of it
  56497. * @returns the new emitter
  56498. */
  56499. SphereParticleEmitter.prototype.clone = function () {
  56500. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56501. BABYLON.Tools.DeepCopy(this, newOne);
  56502. return newOne;
  56503. };
  56504. /**
  56505. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56506. * @param effect defines the update shader
  56507. */
  56508. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56509. effect.setFloat("radius", this.radius);
  56510. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56511. };
  56512. /**
  56513. * Returns a string to use to update the GPU particles update shader
  56514. * @returns a string containng the defines string
  56515. */
  56516. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56517. return "#define SPHEREEMITTER";
  56518. };
  56519. /**
  56520. * Returns the string "SphereParticleEmitter"
  56521. * @returns a string containing the class name
  56522. */
  56523. SphereParticleEmitter.prototype.getClassName = function () {
  56524. return "SphereParticleEmitter";
  56525. };
  56526. /**
  56527. * Serializes the particle system to a JSON object.
  56528. * @returns the JSON object
  56529. */
  56530. SphereParticleEmitter.prototype.serialize = function () {
  56531. var serializationObject = {};
  56532. serializationObject.type = this.getClassName();
  56533. serializationObject.radius = this.radius;
  56534. serializationObject.directionRandomizer = this.directionRandomizer;
  56535. return serializationObject;
  56536. };
  56537. /**
  56538. * Parse properties from a JSON object
  56539. * @param serializationObject defines the JSON object
  56540. */
  56541. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56542. this.radius = serializationObject.radius;
  56543. this.directionRandomizer = serializationObject.directionRandomizer;
  56544. };
  56545. return SphereParticleEmitter;
  56546. }());
  56547. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56548. /**
  56549. * Particle emitter emitting particles from the inside of a sphere.
  56550. * It emits the particles randomly between two vectors.
  56551. */
  56552. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56553. __extends(SphereDirectedParticleEmitter, _super);
  56554. /**
  56555. * Creates a new instance SphereDirectedParticleEmitter
  56556. * @param radius the radius of the emission sphere (1 by default)
  56557. * @param direction1 the min limit of the emission direction (up vector by default)
  56558. * @param direction2 the max limit of the emission direction (up vector by default)
  56559. */
  56560. function SphereDirectedParticleEmitter(radius,
  56561. /**
  56562. * The min limit of the emission direction.
  56563. */
  56564. direction1,
  56565. /**
  56566. * The max limit of the emission direction.
  56567. */
  56568. direction2) {
  56569. if (radius === void 0) { radius = 1; }
  56570. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56571. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56572. var _this = _super.call(this, radius) || this;
  56573. _this.direction1 = direction1;
  56574. _this.direction2 = direction2;
  56575. return _this;
  56576. }
  56577. /**
  56578. * Called by the particle System when the direction is computed for the created particle.
  56579. * @param emitPower is the power of the particle (speed)
  56580. * @param worldMatrix is the world matrix of the particle system
  56581. * @param directionToUpdate is the direction vector to update with the result
  56582. * @param particle is the particle we are computed the direction for
  56583. */
  56584. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56585. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56586. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56587. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56588. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56589. };
  56590. /**
  56591. * Clones the current emitter and returns a copy of it
  56592. * @returns the new emitter
  56593. */
  56594. SphereDirectedParticleEmitter.prototype.clone = function () {
  56595. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56596. BABYLON.Tools.DeepCopy(this, newOne);
  56597. return newOne;
  56598. };
  56599. /**
  56600. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56601. * @param effect defines the update shader
  56602. */
  56603. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56604. effect.setFloat("radius", this.radius);
  56605. effect.setVector3("direction1", this.direction1);
  56606. effect.setVector3("direction2", this.direction2);
  56607. };
  56608. /**
  56609. * Returns a string to use to update the GPU particles update shader
  56610. * @returns a string containng the defines string
  56611. */
  56612. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56613. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56614. };
  56615. /**
  56616. * Returns the string "SphereDirectedParticleEmitter"
  56617. * @returns a string containing the class name
  56618. */
  56619. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56620. return "SphereDirectedParticleEmitter";
  56621. };
  56622. /**
  56623. * Serializes the particle system to a JSON object.
  56624. * @returns the JSON object
  56625. */
  56626. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56627. var serializationObject = _super.prototype.serialize.call(this);
  56628. ;
  56629. serializationObject.direction1 = this.direction1.asArray();
  56630. ;
  56631. serializationObject.direction2 = this.direction2.asArray();
  56632. ;
  56633. return serializationObject;
  56634. };
  56635. /**
  56636. * Parse properties from a JSON object
  56637. * @param serializationObject defines the JSON object
  56638. */
  56639. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56640. _super.prototype.parse.call(this, serializationObject);
  56641. this.direction1.copyFrom(serializationObject.direction1);
  56642. this.direction2.copyFrom(serializationObject.direction2);
  56643. };
  56644. return SphereDirectedParticleEmitter;
  56645. }(SphereParticleEmitter));
  56646. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56647. })(BABYLON || (BABYLON = {}));
  56648. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56649. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56650. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56651. s = arguments[i];
  56652. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56653. t[p] = s[p];
  56654. }
  56655. return t;
  56656. };
  56657. var BABYLON;
  56658. (function (BABYLON) {
  56659. /**
  56660. * This represents a GPU particle system in Babylon
  56661. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56662. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56663. */
  56664. var GPUParticleSystem = /** @class */ (function () {
  56665. /**
  56666. * Instantiates a GPU particle system.
  56667. * 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.
  56668. * @param name The name of the particle system
  56669. * @param capacity The max number of particles alive at the same time
  56670. * @param scene The scene the particle system belongs to
  56671. */
  56672. function GPUParticleSystem(name, options, scene) {
  56673. /**
  56674. * The emitter represents the Mesh or position we are attaching the particle system to.
  56675. */
  56676. this.emitter = null;
  56677. /**
  56678. * The rendering group used by the Particle system to chose when to render.
  56679. */
  56680. this.renderingGroupId = 0;
  56681. /**
  56682. * The layer mask we are rendering the particles through.
  56683. */
  56684. this.layerMask = 0x0FFFFFFF;
  56685. this._targetIndex = 0;
  56686. this._currentRenderId = -1;
  56687. this._started = false;
  56688. this._stopped = false;
  56689. this._timeDelta = 0;
  56690. this._attributesStrideSize = 14;
  56691. this._actualFrame = 0;
  56692. /**
  56693. * List of animations used by the particle system.
  56694. */
  56695. this.animations = [];
  56696. /**
  56697. * An event triggered when the system is disposed.
  56698. */
  56699. this.onDisposeObservable = new BABYLON.Observable();
  56700. /**
  56701. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56702. */
  56703. this.updateSpeed = 0.01;
  56704. /**
  56705. * The amount of time the particle system is running (depends of the overall update speed).
  56706. */
  56707. this.targetStopDuration = 0;
  56708. /**
  56709. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56710. */
  56711. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56712. /**
  56713. * Minimum life time of emitting particles.
  56714. */
  56715. this.minLifeTime = 1;
  56716. /**
  56717. * Maximum life time of emitting particles.
  56718. */
  56719. this.maxLifeTime = 1;
  56720. /**
  56721. * Minimum Size of emitting particles.
  56722. */
  56723. this.minSize = 1;
  56724. /**
  56725. * Maximum Size of emitting particles.
  56726. */
  56727. this.maxSize = 1;
  56728. /**
  56729. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56730. */
  56731. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56732. /**
  56733. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56734. */
  56735. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56736. /**
  56737. * Color the particle will have at the end of its lifetime.
  56738. */
  56739. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56740. /**
  56741. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56742. */
  56743. this.emitRate = 100;
  56744. /**
  56745. * You can use gravity if you want to give an orientation to your particles.
  56746. */
  56747. this.gravity = BABYLON.Vector3.Zero();
  56748. /**
  56749. * Minimum power of emitting particles.
  56750. */
  56751. this.minEmitPower = 1;
  56752. /**
  56753. * Maximum power of emitting particles.
  56754. */
  56755. this.maxEmitPower = 1;
  56756. /**
  56757. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56758. * to override the particles.
  56759. */
  56760. this.forceDepthWrite = false;
  56761. this.id = name;
  56762. this.name = name;
  56763. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56764. this._engine = this._scene.getEngine();
  56765. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56766. this._capacity = fullOptions.capacity;
  56767. this._activeCount = fullOptions.capacity;
  56768. this._currentActiveCount = 0;
  56769. this._scene.particleSystems.push(this);
  56770. this._updateEffectOptions = {
  56771. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  56772. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  56773. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  56774. uniformBuffersNames: [],
  56775. samplers: ["randomSampler"],
  56776. defines: "",
  56777. fallbacks: null,
  56778. onCompiled: null,
  56779. onError: null,
  56780. indexParameters: null,
  56781. maxSimultaneousLights: 0,
  56782. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  56783. };
  56784. // Random data
  56785. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56786. var d = [];
  56787. for (var i = 0; i < maxTextureSize; ++i) {
  56788. d.push(Math.random());
  56789. d.push(Math.random());
  56790. d.push(Math.random());
  56791. d.push(Math.random());
  56792. }
  56793. 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);
  56794. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56795. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56796. this._randomTextureSize = maxTextureSize;
  56797. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56798. }
  56799. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56800. /**
  56801. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56802. */
  56803. get: function () {
  56804. if (!BABYLON.Engine.LastCreatedEngine) {
  56805. return false;
  56806. }
  56807. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56808. },
  56809. enumerable: true,
  56810. configurable: true
  56811. });
  56812. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56813. /**
  56814. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56815. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56816. */
  56817. get: function () {
  56818. if (this.particleEmitterType.direction1) {
  56819. return this.particleEmitterType.direction1;
  56820. }
  56821. return BABYLON.Vector3.Zero();
  56822. },
  56823. set: function (value) {
  56824. if (this.particleEmitterType.direction1) {
  56825. this.particleEmitterType.direction1 = value;
  56826. }
  56827. },
  56828. enumerable: true,
  56829. configurable: true
  56830. });
  56831. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56832. /**
  56833. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56834. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56835. */
  56836. get: function () {
  56837. if (this.particleEmitterType.direction2) {
  56838. return this.particleEmitterType.direction2;
  56839. }
  56840. return BABYLON.Vector3.Zero();
  56841. },
  56842. set: function (value) {
  56843. if (this.particleEmitterType.direction2) {
  56844. this.particleEmitterType.direction2 = value;
  56845. }
  56846. },
  56847. enumerable: true,
  56848. configurable: true
  56849. });
  56850. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56851. /**
  56852. * 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.
  56853. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56854. */
  56855. get: function () {
  56856. if (this.particleEmitterType.minEmitBox) {
  56857. return this.particleEmitterType.minEmitBox;
  56858. }
  56859. return BABYLON.Vector3.Zero();
  56860. },
  56861. set: function (value) {
  56862. if (this.particleEmitterType.minEmitBox) {
  56863. this.particleEmitterType.minEmitBox = value;
  56864. }
  56865. },
  56866. enumerable: true,
  56867. configurable: true
  56868. });
  56869. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56870. /**
  56871. * 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.
  56872. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56873. */
  56874. get: function () {
  56875. if (this.particleEmitterType.maxEmitBox) {
  56876. return this.particleEmitterType.maxEmitBox;
  56877. }
  56878. return BABYLON.Vector3.Zero();
  56879. },
  56880. set: function (value) {
  56881. if (this.particleEmitterType.maxEmitBox) {
  56882. this.particleEmitterType.maxEmitBox = value;
  56883. }
  56884. },
  56885. enumerable: true,
  56886. configurable: true
  56887. });
  56888. /**
  56889. * Gets the maximum number of particles active at the same time.
  56890. * @returns The max number of active particles.
  56891. */
  56892. GPUParticleSystem.prototype.getCapacity = function () {
  56893. return this._capacity;
  56894. };
  56895. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56896. /**
  56897. * Gets or set the number of active particles
  56898. */
  56899. get: function () {
  56900. return this._activeCount;
  56901. },
  56902. set: function (value) {
  56903. this._activeCount = Math.min(value, this._capacity);
  56904. },
  56905. enumerable: true,
  56906. configurable: true
  56907. });
  56908. /**
  56909. * Is this system ready to be used/rendered
  56910. * @return true if the system is ready
  56911. */
  56912. GPUParticleSystem.prototype.isReady = function () {
  56913. if (!this._updateEffect) {
  56914. this._recreateUpdateEffect();
  56915. this._recreateRenderEffect();
  56916. return false;
  56917. }
  56918. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56919. return false;
  56920. }
  56921. return true;
  56922. };
  56923. /**
  56924. * Gets Wether the system has been started.
  56925. * @returns True if it has been started, otherwise false.
  56926. */
  56927. GPUParticleSystem.prototype.isStarted = function () {
  56928. return this._started;
  56929. };
  56930. /**
  56931. * Starts the particle system and begins to emit.
  56932. */
  56933. GPUParticleSystem.prototype.start = function () {
  56934. this._started = true;
  56935. this._stopped = false;
  56936. };
  56937. /**
  56938. * Stops the particle system.
  56939. */
  56940. GPUParticleSystem.prototype.stop = function () {
  56941. this._stopped = true;
  56942. };
  56943. /**
  56944. * Remove all active particles
  56945. */
  56946. GPUParticleSystem.prototype.reset = function () {
  56947. this._releaseBuffers();
  56948. this._releaseVAOs();
  56949. this._currentActiveCount = 0;
  56950. this._targetIndex = 0;
  56951. };
  56952. /**
  56953. * Returns the string "GPUParticleSystem"
  56954. * @returns a string containing the class name
  56955. */
  56956. GPUParticleSystem.prototype.getClassName = function () {
  56957. return "GPUParticleSystem";
  56958. };
  56959. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56960. var updateVertexBuffers = {};
  56961. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56962. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56963. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56964. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56965. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  56966. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  56967. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  56968. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56969. this._engine.bindArrayBuffer(null);
  56970. return vao;
  56971. };
  56972. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56973. var renderVertexBuffers = {};
  56974. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56975. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56976. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56977. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  56978. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  56979. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56980. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56981. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56982. this._engine.bindArrayBuffer(null);
  56983. return vao;
  56984. };
  56985. GPUParticleSystem.prototype._initialize = function (force) {
  56986. if (force === void 0) { force = false; }
  56987. if (this._buffer0 && !force) {
  56988. return;
  56989. }
  56990. var engine = this._scene.getEngine();
  56991. var data = new Array();
  56992. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56993. // position
  56994. data.push(0.0);
  56995. data.push(0.0);
  56996. data.push(0.0);
  56997. // Age and life
  56998. data.push(0.0); // create the particle as a dead one to create a new one at start
  56999. data.push(0.0);
  57000. // Seed
  57001. data.push(Math.random());
  57002. // Size
  57003. data.push(0.0);
  57004. // color
  57005. data.push(0.0);
  57006. data.push(0.0);
  57007. data.push(0.0);
  57008. data.push(0.0);
  57009. // direction
  57010. data.push(0.0);
  57011. data.push(0.0);
  57012. data.push(0.0);
  57013. }
  57014. // Sprite data
  57015. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57016. -0.5, 0.5, 0, 1,
  57017. -0.5, -0.5, 0, 0,
  57018. 0.5, -0.5, 1, 0]);
  57019. // Buffers
  57020. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57021. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57022. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57023. // Update VAO
  57024. this._updateVAO = [];
  57025. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57026. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57027. // Render VAO
  57028. this._renderVAO = [];
  57029. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57030. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57031. // Links
  57032. this._sourceBuffer = this._buffer0;
  57033. this._targetBuffer = this._buffer1;
  57034. };
  57035. /** @ignore */
  57036. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57037. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57038. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57039. return;
  57040. }
  57041. this._updateEffectOptions.defines = defines;
  57042. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57043. };
  57044. /** @ignore */
  57045. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57046. var defines = "";
  57047. if (this._scene.clipPlane) {
  57048. defines = "\n#define CLIPPLANE";
  57049. }
  57050. if (this._renderEffect && this._renderEffect.defines === defines) {
  57051. return;
  57052. }
  57053. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57054. };
  57055. /**
  57056. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57057. */
  57058. GPUParticleSystem.prototype.animate = function () {
  57059. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57060. this._actualFrame += this._timeDelta;
  57061. if (!this._stopped) {
  57062. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57063. this.stop();
  57064. }
  57065. }
  57066. };
  57067. /**
  57068. * Renders the particle system in its current state.
  57069. * @returns the current number of particles
  57070. */
  57071. GPUParticleSystem.prototype.render = function () {
  57072. if (!this._started) {
  57073. return 0;
  57074. }
  57075. this._recreateUpdateEffect();
  57076. this._recreateRenderEffect();
  57077. if (!this.isReady()) {
  57078. return 0;
  57079. }
  57080. if (this._currentRenderId === this._scene.getRenderId()) {
  57081. return 0;
  57082. }
  57083. this._currentRenderId = this._scene.getRenderId();
  57084. // Get everything ready to render
  57085. this._initialize();
  57086. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57087. // Enable update effect
  57088. this._engine.enableEffect(this._updateEffect);
  57089. this._engine.setState(false);
  57090. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57091. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57092. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57093. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57094. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57095. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57096. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57097. this._updateEffect.setDirectColor4("color1", this.color1);
  57098. this._updateEffect.setDirectColor4("color2", this.color2);
  57099. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57100. this._updateEffect.setVector3("gravity", this.gravity);
  57101. if (this.particleEmitterType) {
  57102. this.particleEmitterType.applyToShader(this._updateEffect);
  57103. }
  57104. var emitterWM;
  57105. if (this.emitter.position) {
  57106. var emitterMesh = this.emitter;
  57107. emitterWM = emitterMesh.getWorldMatrix();
  57108. }
  57109. else {
  57110. var emitterPosition = this.emitter;
  57111. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57112. }
  57113. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57114. // Bind source VAO
  57115. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57116. // Update
  57117. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57118. this._engine.setRasterizerState(false);
  57119. this._engine.beginTransformFeedback();
  57120. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57121. this._engine.endTransformFeedback();
  57122. this._engine.setRasterizerState(true);
  57123. this._engine.bindTransformFeedbackBuffer(null);
  57124. // Enable render effect
  57125. this._engine.enableEffect(this._renderEffect);
  57126. var viewMatrix = this._scene.getViewMatrix();
  57127. this._renderEffect.setMatrix("view", viewMatrix);
  57128. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57129. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57130. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57131. if (this._scene.clipPlane) {
  57132. var clipPlane = this._scene.clipPlane;
  57133. var invView = viewMatrix.clone();
  57134. invView.invert();
  57135. this._renderEffect.setMatrix("invView", invView);
  57136. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57137. }
  57138. // Draw order
  57139. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57140. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57141. }
  57142. else {
  57143. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57144. }
  57145. if (this.forceDepthWrite) {
  57146. this._engine.setDepthWrite(true);
  57147. }
  57148. // Bind source VAO
  57149. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57150. // Render
  57151. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57152. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57153. // Switch VAOs
  57154. this._targetIndex++;
  57155. if (this._targetIndex === 2) {
  57156. this._targetIndex = 0;
  57157. }
  57158. // Switch buffers
  57159. var tmpBuffer = this._sourceBuffer;
  57160. this._sourceBuffer = this._targetBuffer;
  57161. this._targetBuffer = tmpBuffer;
  57162. return this._currentActiveCount;
  57163. };
  57164. /**
  57165. * Rebuilds the particle system
  57166. */
  57167. GPUParticleSystem.prototype.rebuild = function () {
  57168. this._initialize(true);
  57169. };
  57170. GPUParticleSystem.prototype._releaseBuffers = function () {
  57171. if (this._buffer0) {
  57172. this._buffer0.dispose();
  57173. this._buffer0 = null;
  57174. }
  57175. if (this._buffer1) {
  57176. this._buffer1.dispose();
  57177. this._buffer1 = null;
  57178. }
  57179. if (this._spriteBuffer) {
  57180. this._spriteBuffer.dispose();
  57181. this._spriteBuffer = null;
  57182. }
  57183. };
  57184. GPUParticleSystem.prototype._releaseVAOs = function () {
  57185. if (!this._updateVAO) {
  57186. return;
  57187. }
  57188. for (var index = 0; index < this._updateVAO.length; index++) {
  57189. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57190. }
  57191. this._updateVAO = [];
  57192. for (var index = 0; index < this._renderVAO.length; index++) {
  57193. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57194. }
  57195. this._renderVAO = [];
  57196. };
  57197. /**
  57198. * Disposes the particle system and free the associated resources
  57199. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57200. */
  57201. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57202. if (disposeTexture === void 0) { disposeTexture = true; }
  57203. var index = this._scene.particleSystems.indexOf(this);
  57204. if (index > -1) {
  57205. this._scene.particleSystems.splice(index, 1);
  57206. }
  57207. this._releaseBuffers();
  57208. this._releaseVAOs();
  57209. if (this._randomTexture) {
  57210. this._randomTexture.dispose();
  57211. this._randomTexture = null;
  57212. }
  57213. if (disposeTexture && this.particleTexture) {
  57214. this.particleTexture.dispose();
  57215. this.particleTexture = null;
  57216. }
  57217. // Callback
  57218. this.onDisposeObservable.notifyObservers(this);
  57219. this.onDisposeObservable.clear();
  57220. };
  57221. /**
  57222. * Clones the particle system.
  57223. * @param name The name of the cloned object
  57224. * @param newEmitter The new emitter to use
  57225. * @returns the cloned particle system
  57226. */
  57227. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57228. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57229. BABYLON.Tools.DeepCopy(this, result);
  57230. if (newEmitter === undefined) {
  57231. newEmitter = this.emitter;
  57232. }
  57233. result.emitter = newEmitter;
  57234. if (this.particleTexture) {
  57235. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57236. }
  57237. return result;
  57238. };
  57239. /**
  57240. * Serializes the particle system to a JSON object.
  57241. * @returns the JSON object
  57242. */
  57243. GPUParticleSystem.prototype.serialize = function () {
  57244. var serializationObject = {};
  57245. serializationObject.name = this.name;
  57246. serializationObject.id = this.id;
  57247. // Emitter
  57248. if (this.emitter.position) {
  57249. var emitterMesh = this.emitter;
  57250. serializationObject.emitterId = emitterMesh.id;
  57251. }
  57252. else {
  57253. var emitterPosition = this.emitter;
  57254. serializationObject.emitter = emitterPosition.asArray();
  57255. }
  57256. serializationObject.capacity = this.getCapacity();
  57257. if (this.particleTexture) {
  57258. serializationObject.textureName = this.particleTexture.name;
  57259. }
  57260. // Animations
  57261. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57262. // Particle system
  57263. serializationObject.activeParticleCount = this.activeParticleCount;
  57264. serializationObject.randomTextureSize = this._randomTextureSize;
  57265. serializationObject.minSize = this.minSize;
  57266. serializationObject.maxSize = this.maxSize;
  57267. serializationObject.minEmitPower = this.minEmitPower;
  57268. serializationObject.maxEmitPower = this.maxEmitPower;
  57269. serializationObject.minLifeTime = this.minLifeTime;
  57270. serializationObject.maxLifeTime = this.maxLifeTime;
  57271. serializationObject.emitRate = this.emitRate;
  57272. serializationObject.gravity = this.gravity.asArray();
  57273. serializationObject.color1 = this.color1.asArray();
  57274. serializationObject.color2 = this.color2.asArray();
  57275. serializationObject.colorDead = this.colorDead.asArray();
  57276. serializationObject.updateSpeed = this.updateSpeed;
  57277. serializationObject.targetStopDuration = this.targetStopDuration;
  57278. serializationObject.blendMode = this.blendMode;
  57279. // Emitter
  57280. if (this.particleEmitterType) {
  57281. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57282. }
  57283. return serializationObject;
  57284. };
  57285. /**
  57286. * Parses a JSON object to create a GPU particle system.
  57287. * @param parsedParticleSystem The JSON object to parse
  57288. * @param scene The scene to create the particle system in
  57289. * @param rootUrl The root url to use to load external dependencies like texture
  57290. * @returns the parsed GPU particle system
  57291. */
  57292. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57293. var name = parsedParticleSystem.name;
  57294. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57295. if (parsedParticleSystem.id) {
  57296. particleSystem.id = parsedParticleSystem.id;
  57297. }
  57298. // Texture
  57299. if (parsedParticleSystem.textureName) {
  57300. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57301. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57302. }
  57303. // Emitter
  57304. if (parsedParticleSystem.emitterId) {
  57305. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57306. }
  57307. else {
  57308. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57309. }
  57310. // Animations
  57311. if (parsedParticleSystem.animations) {
  57312. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57313. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57314. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57315. }
  57316. }
  57317. // Particle system
  57318. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57319. particleSystem.minSize = parsedParticleSystem.minSize;
  57320. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57321. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57322. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57323. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57324. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57325. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57326. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57327. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57328. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57329. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57330. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57331. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57332. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57333. // Emitter
  57334. if (parsedParticleSystem.particleEmitterType) {
  57335. var emitterType = void 0;
  57336. switch (parsedParticleSystem.particleEmitterType.type) {
  57337. case "SphereEmitter":
  57338. emitterType = new BABYLON.SphereParticleEmitter();
  57339. break;
  57340. case "SphereDirectedParticleEmitter":
  57341. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57342. break;
  57343. case "ConeEmitter":
  57344. emitterType = new BABYLON.ConeParticleEmitter();
  57345. break;
  57346. case "BoxEmitter":
  57347. default:
  57348. emitterType = new BABYLON.BoxParticleEmitter();
  57349. break;
  57350. }
  57351. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57352. particleSystem.particleEmitterType = emitterType;
  57353. }
  57354. return particleSystem;
  57355. };
  57356. return GPUParticleSystem;
  57357. }());
  57358. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57359. })(BABYLON || (BABYLON = {}));
  57360. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57361. var BABYLON;
  57362. (function (BABYLON) {
  57363. /**
  57364. * Represents one particle of a solid particle system.
  57365. */
  57366. var SolidParticle = /** @class */ (function () {
  57367. /**
  57368. * Creates a Solid Particle object.
  57369. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57370. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57371. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57372. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57373. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57374. * @param shapeId (integer) is the model shape identifier in the SPS.
  57375. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57376. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57377. */
  57378. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57379. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57380. /**
  57381. * particle global index
  57382. */
  57383. this.idx = 0;
  57384. /**
  57385. * The color of the particle
  57386. */
  57387. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57388. /**
  57389. * The world space position of the particle.
  57390. */
  57391. this.position = BABYLON.Vector3.Zero();
  57392. /**
  57393. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57394. */
  57395. this.rotation = BABYLON.Vector3.Zero();
  57396. /**
  57397. * The scaling of the particle.
  57398. */
  57399. this.scaling = BABYLON.Vector3.One();
  57400. /**
  57401. * The uvs of the particle.
  57402. */
  57403. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57404. /**
  57405. * The current speed of the particle.
  57406. */
  57407. this.velocity = BABYLON.Vector3.Zero();
  57408. /**
  57409. * The pivot point in the particle local space.
  57410. */
  57411. this.pivot = BABYLON.Vector3.Zero();
  57412. /**
  57413. * Must the particle be translated from its pivot point in its local space ?
  57414. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57415. * Default : false
  57416. */
  57417. this.translateFromPivot = false;
  57418. /**
  57419. * Is the particle active or not ?
  57420. */
  57421. this.alive = true;
  57422. /**
  57423. * Is the particle visible or not ?
  57424. */
  57425. this.isVisible = true;
  57426. /**
  57427. * Index of this particle in the global "positions" array (Internal use)
  57428. */
  57429. this._pos = 0;
  57430. /**
  57431. * Index of this particle in the global "indices" array (Internal use)
  57432. */
  57433. this._ind = 0;
  57434. /**
  57435. * ModelShape id of this particle
  57436. */
  57437. this.shapeId = 0;
  57438. /**
  57439. * Index of the particle in its shape id (Internal use)
  57440. */
  57441. this.idxInShape = 0;
  57442. /**
  57443. * Still set as invisible in order to skip useless computations (Internal use)
  57444. */
  57445. this._stillInvisible = false;
  57446. /**
  57447. * Last computed particle rotation matrix
  57448. */
  57449. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57450. /**
  57451. * Parent particle Id, if any.
  57452. * Default null.
  57453. */
  57454. this.parentId = null;
  57455. /**
  57456. * Internal global position in the SPS.
  57457. */
  57458. this._globalPosition = BABYLON.Vector3.Zero();
  57459. this.idx = particleIndex;
  57460. this._pos = positionIndex;
  57461. this._ind = indiceIndex;
  57462. this._model = model;
  57463. this.shapeId = shapeId;
  57464. this.idxInShape = idxInShape;
  57465. this._sps = sps;
  57466. if (modelBoundingInfo) {
  57467. this._modelBoundingInfo = modelBoundingInfo;
  57468. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57469. }
  57470. }
  57471. Object.defineProperty(SolidParticle.prototype, "scale", {
  57472. /**
  57473. * Legacy support, changed scale to scaling
  57474. */
  57475. get: function () {
  57476. return this.scaling;
  57477. },
  57478. /**
  57479. * Legacy support, changed scale to scaling
  57480. */
  57481. set: function (scale) {
  57482. this.scaling = scale;
  57483. },
  57484. enumerable: true,
  57485. configurable: true
  57486. });
  57487. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57488. /**
  57489. * Legacy support, changed quaternion to rotationQuaternion
  57490. */
  57491. get: function () {
  57492. return this.rotationQuaternion;
  57493. },
  57494. /**
  57495. * Legacy support, changed quaternion to rotationQuaternion
  57496. */
  57497. set: function (q) {
  57498. this.rotationQuaternion = q;
  57499. },
  57500. enumerable: true,
  57501. configurable: true
  57502. });
  57503. /**
  57504. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57505. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57506. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57507. * @returns true if it intersects
  57508. */
  57509. SolidParticle.prototype.intersectsMesh = function (target) {
  57510. if (!this._boundingInfo || !target._boundingInfo) {
  57511. return false;
  57512. }
  57513. if (this._sps._bSphereOnly) {
  57514. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57515. }
  57516. return this._boundingInfo.intersects(target._boundingInfo, false);
  57517. };
  57518. return SolidParticle;
  57519. }());
  57520. BABYLON.SolidParticle = SolidParticle;
  57521. /**
  57522. * Represents the shape of the model used by one particle of a solid particle system.
  57523. * SPS internal tool, don't use it manually.
  57524. */
  57525. var ModelShape = /** @class */ (function () {
  57526. /**
  57527. * 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.
  57528. * SPS internal tool, don't use it manually.
  57529. * @ignore
  57530. */
  57531. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57532. /**
  57533. * length of the shape in the model indices array (internal use)
  57534. */
  57535. this._indicesLength = 0;
  57536. this.shapeID = id;
  57537. this._shape = shape;
  57538. this._indicesLength = indicesLength;
  57539. this._shapeUV = shapeUV;
  57540. this._positionFunction = posFunction;
  57541. this._vertexFunction = vtxFunction;
  57542. }
  57543. return ModelShape;
  57544. }());
  57545. BABYLON.ModelShape = ModelShape;
  57546. /**
  57547. * Represents a Depth Sorted Particle in the solid particle system.
  57548. */
  57549. var DepthSortedParticle = /** @class */ (function () {
  57550. function DepthSortedParticle() {
  57551. /**
  57552. * Index of the particle in the "indices" array
  57553. */
  57554. this.ind = 0;
  57555. /**
  57556. * Length of the particle shape in the "indices" array
  57557. */
  57558. this.indicesLength = 0;
  57559. /**
  57560. * Squared distance from the particle to the camera
  57561. */
  57562. this.sqDistance = 0.0;
  57563. }
  57564. return DepthSortedParticle;
  57565. }());
  57566. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57567. })(BABYLON || (BABYLON = {}));
  57568. //# sourceMappingURL=babylon.solidParticle.js.map
  57569. var BABYLON;
  57570. (function (BABYLON) {
  57571. /**
  57572. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57573. *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.
  57574. * The SPS is also a particle system. It provides some methods to manage the particles.
  57575. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57576. *
  57577. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57578. */
  57579. var SolidParticleSystem = /** @class */ (function () {
  57580. /**
  57581. * Creates a SPS (Solid Particle System) object.
  57582. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57583. * @param scene (Scene) is the scene in which the SPS is added.
  57584. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57585. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57586. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57587. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57588. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57589. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57590. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57591. */
  57592. function SolidParticleSystem(name, scene, options) {
  57593. /**
  57594. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57595. * Example : var p = SPS.particles[i];
  57596. */
  57597. this.particles = new Array();
  57598. /**
  57599. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57600. */
  57601. this.nbParticles = 0;
  57602. /**
  57603. * If the particles must ever face the camera (default false). Useful for planar particles.
  57604. */
  57605. this.billboard = false;
  57606. /**
  57607. * Recompute normals when adding a shape
  57608. */
  57609. this.recomputeNormals = true;
  57610. /**
  57611. * This a counter ofr your own usage. It's not set by any SPS functions.
  57612. */
  57613. this.counter = 0;
  57614. /**
  57615. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57616. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57617. */
  57618. this.vars = {};
  57619. /**
  57620. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57621. */
  57622. this._bSphereOnly = false;
  57623. /**
  57624. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57625. */
  57626. this._bSphereRadiusFactor = 1.0;
  57627. this._positions = new Array();
  57628. this._indices = new Array();
  57629. this._normals = new Array();
  57630. this._colors = new Array();
  57631. this._uvs = new Array();
  57632. this._index = 0; // indices index
  57633. this._updatable = true;
  57634. this._pickable = false;
  57635. this._isVisibilityBoxLocked = false;
  57636. this._alwaysVisible = false;
  57637. this._depthSort = false;
  57638. this._shapeCounter = 0;
  57639. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57640. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57641. this._computeParticleColor = true;
  57642. this._computeParticleTexture = true;
  57643. this._computeParticleRotation = true;
  57644. this._computeParticleVertex = false;
  57645. this._computeBoundingBox = false;
  57646. this._depthSortParticles = true;
  57647. this._cam_axisZ = BABYLON.Vector3.Zero();
  57648. this._cam_axisY = BABYLON.Vector3.Zero();
  57649. this._cam_axisX = BABYLON.Vector3.Zero();
  57650. this._axisZ = BABYLON.Axis.Z;
  57651. this._camDir = BABYLON.Vector3.Zero();
  57652. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57653. this._rotMatrix = new BABYLON.Matrix();
  57654. this._invertMatrix = new BABYLON.Matrix();
  57655. this._rotated = BABYLON.Vector3.Zero();
  57656. this._quaternion = new BABYLON.Quaternion();
  57657. this._vertex = BABYLON.Vector3.Zero();
  57658. this._normal = BABYLON.Vector3.Zero();
  57659. this._yaw = 0.0;
  57660. this._pitch = 0.0;
  57661. this._roll = 0.0;
  57662. this._halfroll = 0.0;
  57663. this._halfpitch = 0.0;
  57664. this._halfyaw = 0.0;
  57665. this._sinRoll = 0.0;
  57666. this._cosRoll = 0.0;
  57667. this._sinPitch = 0.0;
  57668. this._cosPitch = 0.0;
  57669. this._sinYaw = 0.0;
  57670. this._cosYaw = 0.0;
  57671. this._mustUnrotateFixedNormals = false;
  57672. this._minimum = BABYLON.Vector3.Zero();
  57673. this._maximum = BABYLON.Vector3.Zero();
  57674. this._minBbox = BABYLON.Vector3.Zero();
  57675. this._maxBbox = BABYLON.Vector3.Zero();
  57676. this._particlesIntersect = false;
  57677. this._depthSortFunction = function (p1, p2) {
  57678. return (p2.sqDistance - p1.sqDistance);
  57679. };
  57680. this._needs32Bits = false;
  57681. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57682. this._scaledPivot = BABYLON.Vector3.Zero();
  57683. this._particleHasParent = false;
  57684. this.name = name;
  57685. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57686. this._camera = scene.activeCamera;
  57687. this._pickable = options ? options.isPickable : false;
  57688. this._depthSort = options ? options.enableDepthSort : false;
  57689. this._particlesIntersect = options ? options.particleIntersection : false;
  57690. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57691. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57692. if (options && options.updatable) {
  57693. this._updatable = options.updatable;
  57694. }
  57695. else {
  57696. this._updatable = true;
  57697. }
  57698. if (this._pickable) {
  57699. this.pickedParticles = [];
  57700. }
  57701. if (this._depthSort) {
  57702. this.depthSortedParticles = [];
  57703. }
  57704. }
  57705. /**
  57706. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57707. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57708. * @returns the created mesh
  57709. */
  57710. SolidParticleSystem.prototype.buildMesh = function () {
  57711. if (this.nbParticles === 0) {
  57712. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57713. this.addShape(triangle, 1);
  57714. triangle.dispose();
  57715. }
  57716. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57717. this._positions32 = new Float32Array(this._positions);
  57718. this._uvs32 = new Float32Array(this._uvs);
  57719. this._colors32 = new Float32Array(this._colors);
  57720. if (this.recomputeNormals) {
  57721. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57722. }
  57723. this._normals32 = new Float32Array(this._normals);
  57724. this._fixedNormal32 = new Float32Array(this._normals);
  57725. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57726. this._unrotateFixedNormals();
  57727. }
  57728. var vertexData = new BABYLON.VertexData();
  57729. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57730. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57731. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57732. if (this._uvs32) {
  57733. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57734. ;
  57735. }
  57736. if (this._colors32) {
  57737. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57738. }
  57739. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57740. vertexData.applyToMesh(mesh, this._updatable);
  57741. this.mesh = mesh;
  57742. this.mesh.isPickable = this._pickable;
  57743. // free memory
  57744. if (!this._depthSort) {
  57745. this._indices = null;
  57746. }
  57747. this._positions = null;
  57748. this._normals = null;
  57749. this._uvs = null;
  57750. this._colors = null;
  57751. if (!this._updatable) {
  57752. this.particles.length = 0;
  57753. }
  57754. return mesh;
  57755. };
  57756. /**
  57757. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57758. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57759. * Thus the particles generated from `digest()` have their property `position` set yet.
  57760. * @param mesh ( Mesh ) is the mesh to be digested
  57761. * @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
  57762. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57763. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57764. * @returns the current SPS
  57765. */
  57766. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57767. var size = (options && options.facetNb) || 1;
  57768. var number = (options && options.number) || 0;
  57769. var delta = (options && options.delta) || 0;
  57770. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57771. var meshInd = mesh.getIndices();
  57772. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57773. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57774. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57775. var f = 0; // facet counter
  57776. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57777. // compute size from number
  57778. if (number) {
  57779. number = (number > totalFacets) ? totalFacets : number;
  57780. size = Math.round(totalFacets / number);
  57781. delta = 0;
  57782. }
  57783. else {
  57784. size = (size > totalFacets) ? totalFacets : size;
  57785. }
  57786. var facetPos = []; // submesh positions
  57787. var facetInd = []; // submesh indices
  57788. var facetUV = []; // submesh UV
  57789. var facetCol = []; // submesh colors
  57790. var barycenter = BABYLON.Vector3.Zero();
  57791. var sizeO = size;
  57792. while (f < totalFacets) {
  57793. size = sizeO + Math.floor((1 + delta) * Math.random());
  57794. if (f > totalFacets - size) {
  57795. size = totalFacets - f;
  57796. }
  57797. // reset temp arrays
  57798. facetPos.length = 0;
  57799. facetInd.length = 0;
  57800. facetUV.length = 0;
  57801. facetCol.length = 0;
  57802. // iterate over "size" facets
  57803. var fi = 0;
  57804. for (var j = f * 3; j < (f + size) * 3; j++) {
  57805. facetInd.push(fi);
  57806. var i = meshInd[j];
  57807. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57808. if (meshUV) {
  57809. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57810. }
  57811. if (meshCol) {
  57812. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57813. }
  57814. fi++;
  57815. }
  57816. // create a model shape for each single particle
  57817. var idx = this.nbParticles;
  57818. var shape = this._posToShape(facetPos);
  57819. var shapeUV = this._uvsToShapeUV(facetUV);
  57820. // compute the barycenter of the shape
  57821. var v;
  57822. for (v = 0; v < shape.length; v++) {
  57823. barycenter.addInPlace(shape[v]);
  57824. }
  57825. barycenter.scaleInPlace(1 / shape.length);
  57826. // shift the shape from its barycenter to the origin
  57827. for (v = 0; v < shape.length; v++) {
  57828. shape[v].subtractInPlace(barycenter);
  57829. }
  57830. var bInfo;
  57831. if (this._particlesIntersect) {
  57832. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57833. }
  57834. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57835. // add the particle in the SPS
  57836. var currentPos = this._positions.length;
  57837. var currentInd = this._indices.length;
  57838. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57839. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57840. // initialize the particle position
  57841. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57842. this._index += shape.length;
  57843. idx++;
  57844. this.nbParticles++;
  57845. this._shapeCounter++;
  57846. f += size;
  57847. }
  57848. return this;
  57849. };
  57850. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57851. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57852. var index = 0;
  57853. var idx = 0;
  57854. for (var p = 0; p < this.particles.length; p++) {
  57855. this._particle = this.particles[p];
  57856. this._shape = this._particle._model._shape;
  57857. if (this._particle.rotationQuaternion) {
  57858. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57859. }
  57860. else {
  57861. this._yaw = this._particle.rotation.y;
  57862. this._pitch = this._particle.rotation.x;
  57863. this._roll = this._particle.rotation.z;
  57864. this._quaternionRotationYPR();
  57865. }
  57866. this._quaternionToRotationMatrix();
  57867. this._rotMatrix.invertToRef(this._invertMatrix);
  57868. for (var pt = 0; pt < this._shape.length; pt++) {
  57869. idx = index + pt * 3;
  57870. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57871. this._fixedNormal32[idx] = this._normal.x;
  57872. this._fixedNormal32[idx + 1] = this._normal.y;
  57873. this._fixedNormal32[idx + 2] = this._normal.z;
  57874. }
  57875. index = idx + 3;
  57876. }
  57877. };
  57878. //reset copy
  57879. SolidParticleSystem.prototype._resetCopy = function () {
  57880. this._copy.position.x = 0;
  57881. this._copy.position.y = 0;
  57882. this._copy.position.z = 0;
  57883. this._copy.rotation.x = 0;
  57884. this._copy.rotation.y = 0;
  57885. this._copy.rotation.z = 0;
  57886. this._copy.rotationQuaternion = null;
  57887. this._copy.scaling.x = 1.0;
  57888. this._copy.scaling.y = 1.0;
  57889. this._copy.scaling.z = 1.0;
  57890. this._copy.uvs.x = 0;
  57891. this._copy.uvs.y = 0;
  57892. this._copy.uvs.z = 1.0;
  57893. this._copy.uvs.w = 1.0;
  57894. this._copy.color = null;
  57895. this._copy.translateFromPivot = false;
  57896. };
  57897. // _meshBuilder : inserts the shape model in the global SPS mesh
  57898. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57899. var i;
  57900. var u = 0;
  57901. var c = 0;
  57902. var n = 0;
  57903. this._resetCopy();
  57904. if (options && options.positionFunction) { // call to custom positionFunction
  57905. options.positionFunction(this._copy, idx, idxInShape);
  57906. this._mustUnrotateFixedNormals = true;
  57907. }
  57908. if (this._copy.rotationQuaternion) {
  57909. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57910. }
  57911. else {
  57912. this._yaw = this._copy.rotation.y;
  57913. this._pitch = this._copy.rotation.x;
  57914. this._roll = this._copy.rotation.z;
  57915. this._quaternionRotationYPR();
  57916. }
  57917. this._quaternionToRotationMatrix();
  57918. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57919. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57920. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57921. if (this._copy.translateFromPivot) {
  57922. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57923. }
  57924. else {
  57925. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57926. }
  57927. for (i = 0; i < shape.length; i++) {
  57928. this._vertex.x = shape[i].x;
  57929. this._vertex.y = shape[i].y;
  57930. this._vertex.z = shape[i].z;
  57931. if (options && options.vertexFunction) {
  57932. options.vertexFunction(this._copy, this._vertex, i);
  57933. }
  57934. this._vertex.x *= this._copy.scaling.x;
  57935. this._vertex.y *= this._copy.scaling.y;
  57936. this._vertex.z *= this._copy.scaling.z;
  57937. this._vertex.x -= this._scaledPivot.x;
  57938. this._vertex.y -= this._scaledPivot.y;
  57939. this._vertex.z -= this._scaledPivot.z;
  57940. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57941. this._rotated.addInPlace(this._pivotBackTranslation);
  57942. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57943. if (meshUV) {
  57944. 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);
  57945. u += 2;
  57946. }
  57947. if (this._copy.color) {
  57948. this._color = this._copy.color;
  57949. }
  57950. else if (meshCol && meshCol[c] !== undefined) {
  57951. this._color.r = meshCol[c];
  57952. this._color.g = meshCol[c + 1];
  57953. this._color.b = meshCol[c + 2];
  57954. this._color.a = meshCol[c + 3];
  57955. }
  57956. else {
  57957. this._color.r = 1.0;
  57958. this._color.g = 1.0;
  57959. this._color.b = 1.0;
  57960. this._color.a = 1.0;
  57961. }
  57962. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57963. c += 4;
  57964. if (!this.recomputeNormals && meshNor) {
  57965. this._normal.x = meshNor[n];
  57966. this._normal.y = meshNor[n + 1];
  57967. this._normal.z = meshNor[n + 2];
  57968. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57969. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57970. n += 3;
  57971. }
  57972. }
  57973. for (i = 0; i < meshInd.length; i++) {
  57974. var current_ind = p + meshInd[i];
  57975. indices.push(current_ind);
  57976. if (current_ind > 65535) {
  57977. this._needs32Bits = true;
  57978. }
  57979. }
  57980. if (this._pickable) {
  57981. var nbfaces = meshInd.length / 3;
  57982. for (i = 0; i < nbfaces; i++) {
  57983. this.pickedParticles.push({ idx: idx, faceId: i });
  57984. }
  57985. }
  57986. if (this._depthSort) {
  57987. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57988. }
  57989. return this._copy;
  57990. };
  57991. // returns a shape array from positions array
  57992. SolidParticleSystem.prototype._posToShape = function (positions) {
  57993. var shape = [];
  57994. for (var i = 0; i < positions.length; i += 3) {
  57995. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57996. }
  57997. return shape;
  57998. };
  57999. // returns a shapeUV array from a Vector4 uvs
  58000. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58001. var shapeUV = [];
  58002. if (uvs) {
  58003. for (var i = 0; i < uvs.length; i++)
  58004. shapeUV.push(uvs[i]);
  58005. }
  58006. return shapeUV;
  58007. };
  58008. // adds a new particle object in the particles array
  58009. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58010. if (bInfo === void 0) { bInfo = null; }
  58011. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58012. this.particles.push(sp);
  58013. return sp;
  58014. };
  58015. /**
  58016. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58017. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58018. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58019. * @param nb (positive integer) the number of particles to be created from this model
  58020. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58021. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58022. * @returns the number of shapes in the system
  58023. */
  58024. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58025. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58026. var meshInd = mesh.getIndices();
  58027. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58028. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58029. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58030. var bbInfo;
  58031. if (this._particlesIntersect) {
  58032. bbInfo = mesh.getBoundingInfo();
  58033. }
  58034. var shape = this._posToShape(meshPos);
  58035. var shapeUV = this._uvsToShapeUV(meshUV);
  58036. var posfunc = options ? options.positionFunction : null;
  58037. var vtxfunc = options ? options.vertexFunction : null;
  58038. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58039. // particles
  58040. var sp;
  58041. var currentCopy;
  58042. var idx = this.nbParticles;
  58043. for (var i = 0; i < nb; i++) {
  58044. var currentPos = this._positions.length;
  58045. var currentInd = this._indices.length;
  58046. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58047. if (this._updatable) {
  58048. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58049. sp.position.copyFrom(currentCopy.position);
  58050. sp.rotation.copyFrom(currentCopy.rotation);
  58051. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58052. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58053. }
  58054. if (currentCopy.color && sp.color) {
  58055. sp.color.copyFrom(currentCopy.color);
  58056. }
  58057. sp.scaling.copyFrom(currentCopy.scaling);
  58058. sp.uvs.copyFrom(currentCopy.uvs);
  58059. }
  58060. this._index += shape.length;
  58061. idx++;
  58062. }
  58063. this.nbParticles += nb;
  58064. this._shapeCounter++;
  58065. return this._shapeCounter - 1;
  58066. };
  58067. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58068. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58069. this._resetCopy();
  58070. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58071. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58072. }
  58073. if (this._copy.rotationQuaternion) {
  58074. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58075. }
  58076. else {
  58077. this._yaw = this._copy.rotation.y;
  58078. this._pitch = this._copy.rotation.x;
  58079. this._roll = this._copy.rotation.z;
  58080. this._quaternionRotationYPR();
  58081. }
  58082. this._quaternionToRotationMatrix();
  58083. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58084. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58085. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58086. if (this._copy.translateFromPivot) {
  58087. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58088. }
  58089. else {
  58090. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58091. }
  58092. this._shape = particle._model._shape;
  58093. for (var pt = 0; pt < this._shape.length; pt++) {
  58094. this._vertex.x = this._shape[pt].x;
  58095. this._vertex.y = this._shape[pt].y;
  58096. this._vertex.z = this._shape[pt].z;
  58097. if (particle._model._vertexFunction) {
  58098. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58099. }
  58100. this._vertex.x *= this._copy.scaling.x;
  58101. this._vertex.y *= this._copy.scaling.y;
  58102. this._vertex.z *= this._copy.scaling.z;
  58103. this._vertex.x -= this._scaledPivot.x;
  58104. this._vertex.y -= this._scaledPivot.y;
  58105. this._vertex.z -= this._scaledPivot.z;
  58106. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58107. this._rotated.addInPlace(this._pivotBackTranslation);
  58108. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58109. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58110. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58111. }
  58112. particle.position.x = 0.0;
  58113. particle.position.y = 0.0;
  58114. particle.position.z = 0.0;
  58115. particle.rotation.x = 0.0;
  58116. particle.rotation.y = 0.0;
  58117. particle.rotation.z = 0.0;
  58118. particle.rotationQuaternion = null;
  58119. particle.scaling.x = 1.0;
  58120. particle.scaling.y = 1.0;
  58121. particle.scaling.z = 1.0;
  58122. particle.uvs.x = 0.0;
  58123. particle.uvs.y = 0.0;
  58124. particle.uvs.z = 1.0;
  58125. particle.uvs.w = 1.0;
  58126. particle.pivot.x = 0.0;
  58127. particle.pivot.y = 0.0;
  58128. particle.pivot.z = 0.0;
  58129. particle.translateFromPivot = false;
  58130. particle.parentId = null;
  58131. };
  58132. /**
  58133. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58134. * @returns the SPS.
  58135. */
  58136. SolidParticleSystem.prototype.rebuildMesh = function () {
  58137. for (var p = 0; p < this.particles.length; p++) {
  58138. this._rebuildParticle(this.particles[p]);
  58139. }
  58140. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58141. return this;
  58142. };
  58143. /**
  58144. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58145. * This method calls `updateParticle()` for each particle of the SPS.
  58146. * For an animated SPS, it is usually called within the render loop.
  58147. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58148. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58149. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58150. * @returns the SPS.
  58151. */
  58152. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58153. if (start === void 0) { start = 0; }
  58154. if (end === void 0) { end = this.nbParticles - 1; }
  58155. if (update === void 0) { update = true; }
  58156. if (!this._updatable) {
  58157. return this;
  58158. }
  58159. // custom beforeUpdate
  58160. this.beforeUpdateParticles(start, end, update);
  58161. this._cam_axisX.x = 1.0;
  58162. this._cam_axisX.y = 0.0;
  58163. this._cam_axisX.z = 0.0;
  58164. this._cam_axisY.x = 0.0;
  58165. this._cam_axisY.y = 1.0;
  58166. this._cam_axisY.z = 0.0;
  58167. this._cam_axisZ.x = 0.0;
  58168. this._cam_axisZ.y = 0.0;
  58169. this._cam_axisZ.z = 1.0;
  58170. // cases when the World Matrix is to be computed first
  58171. if (this.billboard || this._depthSort) {
  58172. this.mesh.computeWorldMatrix(true);
  58173. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58174. }
  58175. // if the particles will always face the camera
  58176. if (this.billboard) {
  58177. // compute the camera position and un-rotate it by the current mesh rotation
  58178. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58179. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58180. this._cam_axisZ.normalize();
  58181. // same for camera up vector extracted from the cam view matrix
  58182. var view = this._camera.getViewMatrix(true);
  58183. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58184. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58185. this._cam_axisY.normalize();
  58186. this._cam_axisX.normalize();
  58187. }
  58188. // if depthSort, compute the camera global position in the mesh local system
  58189. if (this._depthSort) {
  58190. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58191. }
  58192. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58193. var idx = 0; // current position index in the global array positions32
  58194. var index = 0; // position start index in the global array positions32 of the current particle
  58195. var colidx = 0; // current color index in the global array colors32
  58196. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58197. var uvidx = 0; // current uv index in the global array uvs32
  58198. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58199. var pt = 0; // current index in the particle model shape
  58200. if (this.mesh.isFacetDataEnabled) {
  58201. this._computeBoundingBox = true;
  58202. }
  58203. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58204. if (this._computeBoundingBox) {
  58205. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58206. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58207. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58208. }
  58209. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58210. if (this.mesh._boundingInfo) {
  58211. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58212. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58213. }
  58214. }
  58215. }
  58216. // particle loop
  58217. index = this.particles[start]._pos;
  58218. var vpos = (index / 3) | 0;
  58219. colorIndex = vpos * 4;
  58220. uvIndex = vpos * 2;
  58221. for (var p = start; p <= end; p++) {
  58222. this._particle = this.particles[p];
  58223. this._shape = this._particle._model._shape;
  58224. this._shapeUV = this._particle._model._shapeUV;
  58225. // call to custom user function to update the particle properties
  58226. this.updateParticle(this._particle);
  58227. // camera-particle distance for depth sorting
  58228. if (this._depthSort && this._depthSortParticles) {
  58229. var dsp = this.depthSortedParticles[p];
  58230. dsp.ind = this._particle._ind;
  58231. dsp.indicesLength = this._particle._model._indicesLength;
  58232. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58233. }
  58234. // skip the computations for inactive or already invisible particles
  58235. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58236. // increment indexes for the next particle
  58237. pt = this._shape.length;
  58238. index += pt * 3;
  58239. colorIndex += pt * 4;
  58240. uvIndex += pt * 2;
  58241. continue;
  58242. }
  58243. if (this._particle.isVisible) {
  58244. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58245. this._particleHasParent = (this._particle.parentId !== null);
  58246. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58247. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58248. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58249. // particle rotation matrix
  58250. if (this.billboard) {
  58251. this._particle.rotation.x = 0.0;
  58252. this._particle.rotation.y = 0.0;
  58253. }
  58254. if (this._computeParticleRotation || this.billboard) {
  58255. if (this._particle.rotationQuaternion) {
  58256. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58257. }
  58258. else {
  58259. this._yaw = this._particle.rotation.y;
  58260. this._pitch = this._particle.rotation.x;
  58261. this._roll = this._particle.rotation.z;
  58262. this._quaternionRotationYPR();
  58263. }
  58264. this._quaternionToRotationMatrix();
  58265. }
  58266. if (this._particleHasParent) {
  58267. this._parent = this.particles[this._particle.parentId];
  58268. 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];
  58269. 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];
  58270. 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];
  58271. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58272. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58273. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58274. if (this._computeParticleRotation || this.billboard) {
  58275. 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];
  58276. 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];
  58277. 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];
  58278. 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];
  58279. 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];
  58280. 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];
  58281. 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];
  58282. 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];
  58283. 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];
  58284. }
  58285. }
  58286. else {
  58287. this._particle._globalPosition.x = this._particle.position.x;
  58288. this._particle._globalPosition.y = this._particle.position.y;
  58289. this._particle._globalPosition.z = this._particle.position.z;
  58290. if (this._computeParticleRotation || this.billboard) {
  58291. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58292. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58293. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58294. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58295. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58296. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58297. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58298. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58299. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58300. }
  58301. }
  58302. if (this._particle.translateFromPivot) {
  58303. this._pivotBackTranslation.x = 0.0;
  58304. this._pivotBackTranslation.y = 0.0;
  58305. this._pivotBackTranslation.z = 0.0;
  58306. }
  58307. else {
  58308. this._pivotBackTranslation.x = this._scaledPivot.x;
  58309. this._pivotBackTranslation.y = this._scaledPivot.y;
  58310. this._pivotBackTranslation.z = this._scaledPivot.z;
  58311. }
  58312. // particle vertex loop
  58313. for (pt = 0; pt < this._shape.length; pt++) {
  58314. idx = index + pt * 3;
  58315. colidx = colorIndex + pt * 4;
  58316. uvidx = uvIndex + pt * 2;
  58317. this._vertex.x = this._shape[pt].x;
  58318. this._vertex.y = this._shape[pt].y;
  58319. this._vertex.z = this._shape[pt].z;
  58320. if (this._computeParticleVertex) {
  58321. this.updateParticleVertex(this._particle, this._vertex, pt);
  58322. }
  58323. // positions
  58324. this._vertex.x *= this._particle.scaling.x;
  58325. this._vertex.y *= this._particle.scaling.y;
  58326. this._vertex.z *= this._particle.scaling.z;
  58327. this._vertex.x -= this._scaledPivot.x;
  58328. this._vertex.y -= this._scaledPivot.y;
  58329. this._vertex.z -= this._scaledPivot.z;
  58330. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58331. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58332. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58333. this._rotated.x += this._pivotBackTranslation.x;
  58334. this._rotated.y += this._pivotBackTranslation.y;
  58335. this._rotated.z += this._pivotBackTranslation.z;
  58336. 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;
  58337. 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;
  58338. 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;
  58339. if (this._computeBoundingBox) {
  58340. if (this._positions32[idx] < this._minimum.x) {
  58341. this._minimum.x = this._positions32[idx];
  58342. }
  58343. if (this._positions32[idx] > this._maximum.x) {
  58344. this._maximum.x = this._positions32[idx];
  58345. }
  58346. if (this._positions32[idx + 1] < this._minimum.y) {
  58347. this._minimum.y = this._positions32[idx + 1];
  58348. }
  58349. if (this._positions32[idx + 1] > this._maximum.y) {
  58350. this._maximum.y = this._positions32[idx + 1];
  58351. }
  58352. if (this._positions32[idx + 2] < this._minimum.z) {
  58353. this._minimum.z = this._positions32[idx + 2];
  58354. }
  58355. if (this._positions32[idx + 2] > this._maximum.z) {
  58356. this._maximum.z = this._positions32[idx + 2];
  58357. }
  58358. }
  58359. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58360. if (!this._computeParticleVertex) {
  58361. this._normal.x = this._fixedNormal32[idx];
  58362. this._normal.y = this._fixedNormal32[idx + 1];
  58363. this._normal.z = this._fixedNormal32[idx + 2];
  58364. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58365. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58366. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58367. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58368. 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;
  58369. 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;
  58370. }
  58371. if (this._computeParticleColor && this._particle.color) {
  58372. this._colors32[colidx] = this._particle.color.r;
  58373. this._colors32[colidx + 1] = this._particle.color.g;
  58374. this._colors32[colidx + 2] = this._particle.color.b;
  58375. this._colors32[colidx + 3] = this._particle.color.a;
  58376. }
  58377. if (this._computeParticleTexture) {
  58378. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58379. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58380. }
  58381. }
  58382. }
  58383. // particle just set invisible : scaled to zero and positioned at the origin
  58384. else {
  58385. this._particle._stillInvisible = true; // mark the particle as invisible
  58386. for (pt = 0; pt < this._shape.length; pt++) {
  58387. idx = index + pt * 3;
  58388. colidx = colorIndex + pt * 4;
  58389. uvidx = uvIndex + pt * 2;
  58390. this._positions32[idx] = 0.0;
  58391. this._positions32[idx + 1] = 0.0;
  58392. this._positions32[idx + 2] = 0.0;
  58393. this._normals32[idx] = 0.0;
  58394. this._normals32[idx + 1] = 0.0;
  58395. this._normals32[idx + 2] = 0.0;
  58396. if (this._computeParticleColor && this._particle.color) {
  58397. this._colors32[colidx] = this._particle.color.r;
  58398. this._colors32[colidx + 1] = this._particle.color.g;
  58399. this._colors32[colidx + 2] = this._particle.color.b;
  58400. this._colors32[colidx + 3] = this._particle.color.a;
  58401. }
  58402. if (this._computeParticleTexture) {
  58403. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58404. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58405. }
  58406. }
  58407. }
  58408. // if the particle intersections must be computed : update the bbInfo
  58409. if (this._particlesIntersect) {
  58410. var bInfo = this._particle._boundingInfo;
  58411. var bBox = bInfo.boundingBox;
  58412. var bSphere = bInfo.boundingSphere;
  58413. if (!this._bSphereOnly) {
  58414. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58415. for (var b = 0; b < bBox.vectors.length; b++) {
  58416. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58417. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58418. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58419. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58420. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58421. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58422. 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;
  58423. 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;
  58424. 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;
  58425. }
  58426. bBox._update(this.mesh._worldMatrix);
  58427. }
  58428. // place and scale the particle bouding sphere in the SPS local system, then update it
  58429. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58430. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58431. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58432. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58433. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58434. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58435. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58436. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58437. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58438. 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));
  58439. bSphere._update(this.mesh._worldMatrix);
  58440. }
  58441. // increment indexes for the next particle
  58442. index = idx + 3;
  58443. colorIndex = colidx + 4;
  58444. uvIndex = uvidx + 2;
  58445. }
  58446. // if the VBO must be updated
  58447. if (update) {
  58448. if (this._computeParticleColor) {
  58449. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58450. }
  58451. if (this._computeParticleTexture) {
  58452. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58453. }
  58454. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58455. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58456. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58457. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58458. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58459. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58460. for (var i = 0; i < this._normals32.length; i++) {
  58461. this._fixedNormal32[i] = this._normals32[i];
  58462. }
  58463. }
  58464. if (!this.mesh.areNormalsFrozen) {
  58465. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58466. }
  58467. }
  58468. if (this._depthSort && this._depthSortParticles) {
  58469. this.depthSortedParticles.sort(this._depthSortFunction);
  58470. var dspl = this.depthSortedParticles.length;
  58471. var sorted = 0;
  58472. var lind = 0;
  58473. var sind = 0;
  58474. var sid = 0;
  58475. for (sorted = 0; sorted < dspl; sorted++) {
  58476. lind = this.depthSortedParticles[sorted].indicesLength;
  58477. sind = this.depthSortedParticles[sorted].ind;
  58478. for (var i = 0; i < lind; i++) {
  58479. this._indices32[sid] = this._indices[sind + i];
  58480. sid++;
  58481. }
  58482. }
  58483. this.mesh.updateIndices(this._indices32);
  58484. }
  58485. }
  58486. if (this._computeBoundingBox) {
  58487. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58488. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58489. }
  58490. this.afterUpdateParticles(start, end, update);
  58491. return this;
  58492. };
  58493. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58494. this._halfroll = this._roll * 0.5;
  58495. this._halfpitch = this._pitch * 0.5;
  58496. this._halfyaw = this._yaw * 0.5;
  58497. this._sinRoll = Math.sin(this._halfroll);
  58498. this._cosRoll = Math.cos(this._halfroll);
  58499. this._sinPitch = Math.sin(this._halfpitch);
  58500. this._cosPitch = Math.cos(this._halfpitch);
  58501. this._sinYaw = Math.sin(this._halfyaw);
  58502. this._cosYaw = Math.cos(this._halfyaw);
  58503. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58504. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58505. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58506. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58507. };
  58508. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58509. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58510. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58511. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58512. this._rotMatrix.m[3] = 0;
  58513. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58514. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58515. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58516. this._rotMatrix.m[7] = 0;
  58517. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58518. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58519. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58520. this._rotMatrix.m[11] = 0;
  58521. this._rotMatrix.m[12] = 0;
  58522. this._rotMatrix.m[13] = 0;
  58523. this._rotMatrix.m[14] = 0;
  58524. this._rotMatrix.m[15] = 1.0;
  58525. };
  58526. /**
  58527. * Disposes the SPS.
  58528. */
  58529. SolidParticleSystem.prototype.dispose = function () {
  58530. this.mesh.dispose();
  58531. this.vars = null;
  58532. // drop references to internal big arrays for the GC
  58533. this._positions = null;
  58534. this._indices = null;
  58535. this._normals = null;
  58536. this._uvs = null;
  58537. this._colors = null;
  58538. this._indices32 = null;
  58539. this._positions32 = null;
  58540. this._normals32 = null;
  58541. this._fixedNormal32 = null;
  58542. this._uvs32 = null;
  58543. this._colors32 = null;
  58544. this.pickedParticles = null;
  58545. };
  58546. /**
  58547. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58548. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58549. * @returns the SPS.
  58550. */
  58551. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58552. if (!this._isVisibilityBoxLocked) {
  58553. this.mesh.refreshBoundingInfo();
  58554. }
  58555. return this;
  58556. };
  58557. /**
  58558. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58559. * @param size the size (float) of the visibility box
  58560. * note : this doesn't lock the SPS mesh bounding box.
  58561. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58562. */
  58563. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58564. var vis = size / 2;
  58565. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58566. };
  58567. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58568. /**
  58569. * Gets whether the SPS as always visible or not
  58570. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58571. */
  58572. get: function () {
  58573. return this._alwaysVisible;
  58574. },
  58575. /**
  58576. * Sets the SPS as always visible or not
  58577. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58578. */
  58579. set: function (val) {
  58580. this._alwaysVisible = val;
  58581. this.mesh.alwaysSelectAsActiveMesh = val;
  58582. },
  58583. enumerable: true,
  58584. configurable: true
  58585. });
  58586. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58587. /**
  58588. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58589. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58590. */
  58591. get: function () {
  58592. return this._isVisibilityBoxLocked;
  58593. },
  58594. /**
  58595. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58596. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58597. */
  58598. set: function (val) {
  58599. this._isVisibilityBoxLocked = val;
  58600. var boundingInfo = this.mesh.getBoundingInfo();
  58601. boundingInfo.isLocked = val;
  58602. },
  58603. enumerable: true,
  58604. configurable: true
  58605. });
  58606. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58607. /**
  58608. * Gets if `setParticles()` computes the particle rotations or not.
  58609. * Default value : true. The SPS is faster when it's set to false.
  58610. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58611. */
  58612. get: function () {
  58613. return this._computeParticleRotation;
  58614. },
  58615. /**
  58616. * Tells to `setParticles()` to compute the particle rotations or not.
  58617. * Default value : true. The SPS is faster when it's set to false.
  58618. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58619. */
  58620. set: function (val) {
  58621. this._computeParticleRotation = val;
  58622. },
  58623. enumerable: true,
  58624. configurable: true
  58625. });
  58626. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58627. /**
  58628. * Gets if `setParticles()` computes the particle colors or not.
  58629. * Default value : true. The SPS is faster when it's set to false.
  58630. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58631. */
  58632. get: function () {
  58633. return this._computeParticleColor;
  58634. },
  58635. /**
  58636. * Tells to `setParticles()` to compute the particle colors or not.
  58637. * Default value : true. The SPS is faster when it's set to false.
  58638. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58639. */
  58640. set: function (val) {
  58641. this._computeParticleColor = val;
  58642. },
  58643. enumerable: true,
  58644. configurable: true
  58645. });
  58646. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58647. /**
  58648. * Gets if `setParticles()` computes the particle textures or not.
  58649. * Default value : true. The SPS is faster when it's set to false.
  58650. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58651. */
  58652. get: function () {
  58653. return this._computeParticleTexture;
  58654. },
  58655. set: function (val) {
  58656. this._computeParticleTexture = val;
  58657. },
  58658. enumerable: true,
  58659. configurable: true
  58660. });
  58661. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58662. /**
  58663. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58664. * Default value : false. The SPS is faster when it's set to false.
  58665. * Note : the particle custom vertex positions aren't stored values.
  58666. */
  58667. get: function () {
  58668. return this._computeParticleVertex;
  58669. },
  58670. /**
  58671. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58672. * Default value : false. The SPS is faster when it's set to false.
  58673. * Note : the particle custom vertex positions aren't stored values.
  58674. */
  58675. set: function (val) {
  58676. this._computeParticleVertex = val;
  58677. },
  58678. enumerable: true,
  58679. configurable: true
  58680. });
  58681. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58682. /**
  58683. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58684. */
  58685. get: function () {
  58686. return this._computeBoundingBox;
  58687. },
  58688. /**
  58689. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58690. */
  58691. set: function (val) {
  58692. this._computeBoundingBox = val;
  58693. },
  58694. enumerable: true,
  58695. configurable: true
  58696. });
  58697. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58698. /**
  58699. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58700. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58701. * Default : `true`
  58702. */
  58703. get: function () {
  58704. return this._depthSortParticles;
  58705. },
  58706. /**
  58707. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58708. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58709. * Default : `true`
  58710. */
  58711. set: function (val) {
  58712. this._depthSortParticles = val;
  58713. },
  58714. enumerable: true,
  58715. configurable: true
  58716. });
  58717. // =======================================================================
  58718. // Particle behavior logic
  58719. // these following methods may be overwritten by the user to fit his needs
  58720. /**
  58721. * This function does nothing. It may be overwritten to set all the particle first values.
  58722. * The SPS doesn't call this function, you may have to call it by your own.
  58723. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58724. */
  58725. SolidParticleSystem.prototype.initParticles = function () {
  58726. };
  58727. /**
  58728. * This function does nothing. It may be overwritten to recycle a particle.
  58729. * The SPS doesn't call this function, you may have to call it by your own.
  58730. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58731. * @param particle The particle to recycle
  58732. * @returns the recycled particle
  58733. */
  58734. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58735. return particle;
  58736. };
  58737. /**
  58738. * Updates a particle : this function should be overwritten by the user.
  58739. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58740. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58741. * @example : just set a particle position or velocity and recycle conditions
  58742. * @param particle The particle to update
  58743. * @returns the updated particle
  58744. */
  58745. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58746. return particle;
  58747. };
  58748. /**
  58749. * Updates a vertex of a particle : it can be overwritten by the user.
  58750. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58751. * @param particle the current particle
  58752. * @param vertex the current index of the current particle
  58753. * @param pt the index of the current vertex in the particle shape
  58754. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58755. * @example : just set a vertex particle position
  58756. * @returns the updated vertex
  58757. */
  58758. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58759. return vertex;
  58760. };
  58761. /**
  58762. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58763. * This does nothing and may be overwritten by the user.
  58764. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58765. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58766. * @param update the boolean update value actually passed to setParticles()
  58767. */
  58768. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58769. };
  58770. /**
  58771. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58772. * This will be passed three parameters.
  58773. * This does nothing and may be overwritten by the user.
  58774. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58775. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58776. * @param update the boolean update value actually passed to setParticles()
  58777. */
  58778. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58779. };
  58780. return SolidParticleSystem;
  58781. }());
  58782. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58783. })(BABYLON || (BABYLON = {}));
  58784. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58785. var BABYLON;
  58786. (function (BABYLON) {
  58787. var ShaderMaterial = /** @class */ (function (_super) {
  58788. __extends(ShaderMaterial, _super);
  58789. function ShaderMaterial(name, scene, shaderPath, options) {
  58790. var _this = _super.call(this, name, scene) || this;
  58791. _this._textures = {};
  58792. _this._textureArrays = {};
  58793. _this._floats = {};
  58794. _this._ints = {};
  58795. _this._floatsArrays = {};
  58796. _this._colors3 = {};
  58797. _this._colors3Arrays = {};
  58798. _this._colors4 = {};
  58799. _this._vectors2 = {};
  58800. _this._vectors3 = {};
  58801. _this._vectors4 = {};
  58802. _this._matrices = {};
  58803. _this._matrices3x3 = {};
  58804. _this._matrices2x2 = {};
  58805. _this._vectors2Arrays = {};
  58806. _this._vectors3Arrays = {};
  58807. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58808. _this._shaderPath = shaderPath;
  58809. options.needAlphaBlending = options.needAlphaBlending || false;
  58810. options.needAlphaTesting = options.needAlphaTesting || false;
  58811. options.attributes = options.attributes || ["position", "normal", "uv"];
  58812. options.uniforms = options.uniforms || ["worldViewProjection"];
  58813. options.uniformBuffers = options.uniformBuffers || [];
  58814. options.samplers = options.samplers || [];
  58815. options.defines = options.defines || [];
  58816. _this._options = options;
  58817. return _this;
  58818. }
  58819. ShaderMaterial.prototype.getClassName = function () {
  58820. return "ShaderMaterial";
  58821. };
  58822. ShaderMaterial.prototype.needAlphaBlending = function () {
  58823. return this._options.needAlphaBlending;
  58824. };
  58825. ShaderMaterial.prototype.needAlphaTesting = function () {
  58826. return this._options.needAlphaTesting;
  58827. };
  58828. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58829. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58830. this._options.uniforms.push(uniformName);
  58831. }
  58832. };
  58833. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58834. if (this._options.samplers.indexOf(name) === -1) {
  58835. this._options.samplers.push(name);
  58836. }
  58837. this._textures[name] = texture;
  58838. return this;
  58839. };
  58840. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58841. if (this._options.samplers.indexOf(name) === -1) {
  58842. this._options.samplers.push(name);
  58843. }
  58844. this._checkUniform(name);
  58845. this._textureArrays[name] = textures;
  58846. return this;
  58847. };
  58848. ShaderMaterial.prototype.setFloat = function (name, value) {
  58849. this._checkUniform(name);
  58850. this._floats[name] = value;
  58851. return this;
  58852. };
  58853. ShaderMaterial.prototype.setInt = function (name, value) {
  58854. this._checkUniform(name);
  58855. this._ints[name] = value;
  58856. return this;
  58857. };
  58858. ShaderMaterial.prototype.setFloats = function (name, value) {
  58859. this._checkUniform(name);
  58860. this._floatsArrays[name] = value;
  58861. return this;
  58862. };
  58863. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58864. this._checkUniform(name);
  58865. this._colors3[name] = value;
  58866. return this;
  58867. };
  58868. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58869. this._checkUniform(name);
  58870. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58871. color.toArray(arr, arr.length);
  58872. return arr;
  58873. }, []);
  58874. return this;
  58875. };
  58876. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58877. this._checkUniform(name);
  58878. this._colors4[name] = value;
  58879. return this;
  58880. };
  58881. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58882. this._checkUniform(name);
  58883. this._vectors2[name] = value;
  58884. return this;
  58885. };
  58886. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58887. this._checkUniform(name);
  58888. this._vectors3[name] = value;
  58889. return this;
  58890. };
  58891. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58892. this._checkUniform(name);
  58893. this._vectors4[name] = value;
  58894. return this;
  58895. };
  58896. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58897. this._checkUniform(name);
  58898. this._matrices[name] = value;
  58899. return this;
  58900. };
  58901. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58902. this._checkUniform(name);
  58903. this._matrices3x3[name] = value;
  58904. return this;
  58905. };
  58906. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58907. this._checkUniform(name);
  58908. this._matrices2x2[name] = value;
  58909. return this;
  58910. };
  58911. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58912. this._checkUniform(name);
  58913. this._vectors2Arrays[name] = value;
  58914. return this;
  58915. };
  58916. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58917. this._checkUniform(name);
  58918. this._vectors3Arrays[name] = value;
  58919. return this;
  58920. };
  58921. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58922. if (!mesh) {
  58923. return true;
  58924. }
  58925. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58926. return false;
  58927. }
  58928. return false;
  58929. };
  58930. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58931. var scene = this.getScene();
  58932. var engine = scene.getEngine();
  58933. if (!this.checkReadyOnEveryCall) {
  58934. if (this._renderId === scene.getRenderId()) {
  58935. if (this._checkCache(scene, mesh, useInstances)) {
  58936. return true;
  58937. }
  58938. }
  58939. }
  58940. // Instances
  58941. var defines = [];
  58942. var attribs = [];
  58943. var fallbacks = new BABYLON.EffectFallbacks();
  58944. if (useInstances) {
  58945. defines.push("#define INSTANCES");
  58946. }
  58947. for (var index = 0; index < this._options.defines.length; index++) {
  58948. defines.push(this._options.defines[index]);
  58949. }
  58950. for (var index = 0; index < this._options.attributes.length; index++) {
  58951. attribs.push(this._options.attributes[index]);
  58952. }
  58953. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58954. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58955. defines.push("#define VERTEXCOLOR");
  58956. }
  58957. // Bones
  58958. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58959. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58960. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58961. if (mesh.numBoneInfluencers > 4) {
  58962. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58963. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58964. }
  58965. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58966. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58967. fallbacks.addCPUSkinningFallback(0, mesh);
  58968. if (this._options.uniforms.indexOf("mBones") === -1) {
  58969. this._options.uniforms.push("mBones");
  58970. }
  58971. }
  58972. else {
  58973. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58974. }
  58975. // Textures
  58976. for (var name in this._textures) {
  58977. if (!this._textures[name].isReady()) {
  58978. return false;
  58979. }
  58980. }
  58981. // Alpha test
  58982. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58983. defines.push("#define ALPHATEST");
  58984. }
  58985. var previousEffect = this._effect;
  58986. var join = defines.join("\n");
  58987. this._effect = engine.createEffect(this._shaderPath, {
  58988. attributes: attribs,
  58989. uniformsNames: this._options.uniforms,
  58990. uniformBuffersNames: this._options.uniformBuffers,
  58991. samplers: this._options.samplers,
  58992. defines: join,
  58993. fallbacks: fallbacks,
  58994. onCompiled: this.onCompiled,
  58995. onError: this.onError
  58996. }, engine);
  58997. if (!this._effect.isReady()) {
  58998. return false;
  58999. }
  59000. if (previousEffect !== this._effect) {
  59001. scene.resetCachedMaterial();
  59002. }
  59003. this._renderId = scene.getRenderId();
  59004. return true;
  59005. };
  59006. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59007. var scene = this.getScene();
  59008. if (!this._effect) {
  59009. return;
  59010. }
  59011. if (this._options.uniforms.indexOf("world") !== -1) {
  59012. this._effect.setMatrix("world", world);
  59013. }
  59014. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59015. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59016. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59017. }
  59018. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59019. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59020. }
  59021. };
  59022. ShaderMaterial.prototype.bind = function (world, mesh) {
  59023. // Std values
  59024. this.bindOnlyWorldMatrix(world);
  59025. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59026. if (this._options.uniforms.indexOf("view") !== -1) {
  59027. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59028. }
  59029. if (this._options.uniforms.indexOf("projection") !== -1) {
  59030. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59031. }
  59032. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59033. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59034. }
  59035. // Bones
  59036. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59037. var name;
  59038. // Texture
  59039. for (name in this._textures) {
  59040. this._effect.setTexture(name, this._textures[name]);
  59041. }
  59042. // Texture arrays
  59043. for (name in this._textureArrays) {
  59044. this._effect.setTextureArray(name, this._textureArrays[name]);
  59045. }
  59046. // Int
  59047. for (name in this._ints) {
  59048. this._effect.setInt(name, this._ints[name]);
  59049. }
  59050. // Float
  59051. for (name in this._floats) {
  59052. this._effect.setFloat(name, this._floats[name]);
  59053. }
  59054. // Floats
  59055. for (name in this._floatsArrays) {
  59056. this._effect.setArray(name, this._floatsArrays[name]);
  59057. }
  59058. // Color3
  59059. for (name in this._colors3) {
  59060. this._effect.setColor3(name, this._colors3[name]);
  59061. }
  59062. for (name in this._colors3Arrays) {
  59063. this._effect.setArray3(name, this._colors3Arrays[name]);
  59064. }
  59065. // Color4
  59066. for (name in this._colors4) {
  59067. var color = this._colors4[name];
  59068. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59069. }
  59070. // Vector2
  59071. for (name in this._vectors2) {
  59072. this._effect.setVector2(name, this._vectors2[name]);
  59073. }
  59074. // Vector3
  59075. for (name in this._vectors3) {
  59076. this._effect.setVector3(name, this._vectors3[name]);
  59077. }
  59078. // Vector4
  59079. for (name in this._vectors4) {
  59080. this._effect.setVector4(name, this._vectors4[name]);
  59081. }
  59082. // Matrix
  59083. for (name in this._matrices) {
  59084. this._effect.setMatrix(name, this._matrices[name]);
  59085. }
  59086. // Matrix 3x3
  59087. for (name in this._matrices3x3) {
  59088. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59089. }
  59090. // Matrix 2x2
  59091. for (name in this._matrices2x2) {
  59092. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59093. }
  59094. // Vector2Array
  59095. for (name in this._vectors2Arrays) {
  59096. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59097. }
  59098. // Vector3Array
  59099. for (name in this._vectors3Arrays) {
  59100. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59101. }
  59102. }
  59103. this._afterBind(mesh);
  59104. };
  59105. ShaderMaterial.prototype.getActiveTextures = function () {
  59106. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59107. for (var name in this._textures) {
  59108. activeTextures.push(this._textures[name]);
  59109. }
  59110. for (var name in this._textureArrays) {
  59111. var array = this._textureArrays[name];
  59112. for (var index = 0; index < array.length; index++) {
  59113. activeTextures.push(array[index]);
  59114. }
  59115. }
  59116. return activeTextures;
  59117. };
  59118. ShaderMaterial.prototype.hasTexture = function (texture) {
  59119. if (_super.prototype.hasTexture.call(this, texture)) {
  59120. return true;
  59121. }
  59122. for (var name in this._textures) {
  59123. if (this._textures[name] === texture) {
  59124. return true;
  59125. }
  59126. }
  59127. for (var name in this._textureArrays) {
  59128. var array = this._textureArrays[name];
  59129. for (var index = 0; index < array.length; index++) {
  59130. if (array[index] === texture) {
  59131. return true;
  59132. }
  59133. }
  59134. }
  59135. return false;
  59136. };
  59137. ShaderMaterial.prototype.clone = function (name) {
  59138. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59139. return newShaderMaterial;
  59140. };
  59141. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59142. if (forceDisposeTextures) {
  59143. var name;
  59144. for (name in this._textures) {
  59145. this._textures[name].dispose();
  59146. }
  59147. for (name in this._textureArrays) {
  59148. var array = this._textureArrays[name];
  59149. for (var index = 0; index < array.length; index++) {
  59150. array[index].dispose();
  59151. }
  59152. }
  59153. }
  59154. this._textures = {};
  59155. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59156. };
  59157. ShaderMaterial.prototype.serialize = function () {
  59158. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59159. serializationObject.customType = "BABYLON.ShaderMaterial";
  59160. serializationObject.options = this._options;
  59161. serializationObject.shaderPath = this._shaderPath;
  59162. var name;
  59163. // Texture
  59164. serializationObject.textures = {};
  59165. for (name in this._textures) {
  59166. serializationObject.textures[name] = this._textures[name].serialize();
  59167. }
  59168. // Texture arrays
  59169. serializationObject.textureArrays = {};
  59170. for (name in this._textureArrays) {
  59171. serializationObject.textureArrays[name] = [];
  59172. var array = this._textureArrays[name];
  59173. for (var index = 0; index < array.length; index++) {
  59174. serializationObject.textureArrays[name].push(array[index].serialize());
  59175. }
  59176. }
  59177. // Float
  59178. serializationObject.floats = {};
  59179. for (name in this._floats) {
  59180. serializationObject.floats[name] = this._floats[name];
  59181. }
  59182. // Float s
  59183. serializationObject.FloatArrays = {};
  59184. for (name in this._floatsArrays) {
  59185. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59186. }
  59187. // Color3
  59188. serializationObject.colors3 = {};
  59189. for (name in this._colors3) {
  59190. serializationObject.colors3[name] = this._colors3[name].asArray();
  59191. }
  59192. // Color3 array
  59193. serializationObject.colors3Arrays = {};
  59194. for (name in this._colors3Arrays) {
  59195. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59196. }
  59197. // Color4
  59198. serializationObject.colors4 = {};
  59199. for (name in this._colors4) {
  59200. serializationObject.colors4[name] = this._colors4[name].asArray();
  59201. }
  59202. // Vector2
  59203. serializationObject.vectors2 = {};
  59204. for (name in this._vectors2) {
  59205. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59206. }
  59207. // Vector3
  59208. serializationObject.vectors3 = {};
  59209. for (name in this._vectors3) {
  59210. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59211. }
  59212. // Vector4
  59213. serializationObject.vectors4 = {};
  59214. for (name in this._vectors4) {
  59215. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59216. }
  59217. // Matrix
  59218. serializationObject.matrices = {};
  59219. for (name in this._matrices) {
  59220. serializationObject.matrices[name] = this._matrices[name].asArray();
  59221. }
  59222. // Matrix 3x3
  59223. serializationObject.matrices3x3 = {};
  59224. for (name in this._matrices3x3) {
  59225. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59226. }
  59227. // Matrix 2x2
  59228. serializationObject.matrices2x2 = {};
  59229. for (name in this._matrices2x2) {
  59230. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59231. }
  59232. // Vector2Array
  59233. serializationObject.vectors2Arrays = {};
  59234. for (name in this._vectors2Arrays) {
  59235. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59236. }
  59237. // Vector3Array
  59238. serializationObject.vectors3Arrays = {};
  59239. for (name in this._vectors3Arrays) {
  59240. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59241. }
  59242. return serializationObject;
  59243. };
  59244. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59245. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59246. var name;
  59247. // Texture
  59248. for (name in source.textures) {
  59249. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59250. }
  59251. // Texture arrays
  59252. for (name in source.textureArrays) {
  59253. var array = source.textureArrays[name];
  59254. var textureArray = new Array();
  59255. for (var index = 0; index < array.length; index++) {
  59256. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59257. }
  59258. material.setTextureArray(name, textureArray);
  59259. }
  59260. // Float
  59261. for (name in source.floats) {
  59262. material.setFloat(name, source.floats[name]);
  59263. }
  59264. // Float s
  59265. for (name in source.floatsArrays) {
  59266. material.setFloats(name, source.floatsArrays[name]);
  59267. }
  59268. // Color3
  59269. for (name in source.colors3) {
  59270. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59271. }
  59272. // Color3 arrays
  59273. for (name in source.colors3Arrays) {
  59274. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59275. if (i % 3 === 0) {
  59276. arr.push([num]);
  59277. }
  59278. else {
  59279. arr[arr.length - 1].push(num);
  59280. }
  59281. return arr;
  59282. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59283. material.setColor3Array(name, colors);
  59284. }
  59285. // Color4
  59286. for (name in source.colors4) {
  59287. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59288. }
  59289. // Vector2
  59290. for (name in source.vectors2) {
  59291. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59292. }
  59293. // Vector3
  59294. for (name in source.vectors3) {
  59295. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59296. }
  59297. // Vector4
  59298. for (name in source.vectors4) {
  59299. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59300. }
  59301. // Matrix
  59302. for (name in source.matrices) {
  59303. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59304. }
  59305. // Matrix 3x3
  59306. for (name in source.matrices3x3) {
  59307. material.setMatrix3x3(name, source.matrices3x3[name]);
  59308. }
  59309. // Matrix 2x2
  59310. for (name in source.matrices2x2) {
  59311. material.setMatrix2x2(name, source.matrices2x2[name]);
  59312. }
  59313. // Vector2Array
  59314. for (name in source.vectors2Arrays) {
  59315. material.setArray2(name, source.vectors2Arrays[name]);
  59316. }
  59317. // Vector3Array
  59318. for (name in source.vectors3Arrays) {
  59319. material.setArray3(name, source.vectors3Arrays[name]);
  59320. }
  59321. return material;
  59322. };
  59323. return ShaderMaterial;
  59324. }(BABYLON.Material));
  59325. BABYLON.ShaderMaterial = ShaderMaterial;
  59326. })(BABYLON || (BABYLON = {}));
  59327. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59328. var BABYLON;
  59329. (function (BABYLON) {
  59330. var GroundMesh = /** @class */ (function (_super) {
  59331. __extends(GroundMesh, _super);
  59332. function GroundMesh(name, scene) {
  59333. var _this = _super.call(this, name, scene) || this;
  59334. _this.generateOctree = false;
  59335. return _this;
  59336. }
  59337. GroundMesh.prototype.getClassName = function () {
  59338. return "GroundMesh";
  59339. };
  59340. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59341. get: function () {
  59342. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59343. },
  59344. enumerable: true,
  59345. configurable: true
  59346. });
  59347. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59348. get: function () {
  59349. return this._subdivisionsX;
  59350. },
  59351. enumerable: true,
  59352. configurable: true
  59353. });
  59354. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59355. get: function () {
  59356. return this._subdivisionsY;
  59357. },
  59358. enumerable: true,
  59359. configurable: true
  59360. });
  59361. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59362. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59363. this._subdivisionsX = chunksCount;
  59364. this._subdivisionsY = chunksCount;
  59365. this.subdivide(chunksCount);
  59366. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59367. };
  59368. /**
  59369. * Returns a height (y) value in the Worl system :
  59370. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59371. * Returns the ground y position if (x, z) are outside the ground surface.
  59372. */
  59373. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59374. var world = this.getWorldMatrix();
  59375. var invMat = BABYLON.Tmp.Matrix[5];
  59376. world.invertToRef(invMat);
  59377. var tmpVect = BABYLON.Tmp.Vector3[8];
  59378. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59379. x = tmpVect.x;
  59380. z = tmpVect.z;
  59381. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59382. return this.position.y;
  59383. }
  59384. if (!this._heightQuads || this._heightQuads.length == 0) {
  59385. this._initHeightQuads();
  59386. this._computeHeightQuads();
  59387. }
  59388. var facet = this._getFacetAt(x, z);
  59389. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59390. // return y in the World system
  59391. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59392. return tmpVect.y;
  59393. };
  59394. /**
  59395. * Returns a normalized vector (Vector3) orthogonal to the ground
  59396. * at the ground coordinates (x, z) expressed in the World system.
  59397. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59398. */
  59399. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59400. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59401. this.getNormalAtCoordinatesToRef(x, z, normal);
  59402. return normal;
  59403. };
  59404. /**
  59405. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59406. * at the ground coordinates (x, z) expressed in the World system.
  59407. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59408. * Returns the GroundMesh.
  59409. */
  59410. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59411. var world = this.getWorldMatrix();
  59412. var tmpMat = BABYLON.Tmp.Matrix[5];
  59413. world.invertToRef(tmpMat);
  59414. var tmpVect = BABYLON.Tmp.Vector3[8];
  59415. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59416. x = tmpVect.x;
  59417. z = tmpVect.z;
  59418. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59419. return this;
  59420. }
  59421. if (!this._heightQuads || this._heightQuads.length == 0) {
  59422. this._initHeightQuads();
  59423. this._computeHeightQuads();
  59424. }
  59425. var facet = this._getFacetAt(x, z);
  59426. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59427. return this;
  59428. };
  59429. /**
  59430. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59431. * if the ground has been updated.
  59432. * This can be used in the render loop.
  59433. * Returns the GroundMesh.
  59434. */
  59435. GroundMesh.prototype.updateCoordinateHeights = function () {
  59436. if (!this._heightQuads || this._heightQuads.length == 0) {
  59437. this._initHeightQuads();
  59438. }
  59439. this._computeHeightQuads();
  59440. return this;
  59441. };
  59442. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59443. GroundMesh.prototype._getFacetAt = function (x, z) {
  59444. // retrieve col and row from x, z coordinates in the ground local system
  59445. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59446. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59447. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59448. var facet;
  59449. if (z < quad.slope.x * x + quad.slope.y) {
  59450. facet = quad.facet1;
  59451. }
  59452. else {
  59453. facet = quad.facet2;
  59454. }
  59455. return facet;
  59456. };
  59457. // Creates and populates the heightMap array with "facet" elements :
  59458. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59459. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59460. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59461. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59462. // Returns the GroundMesh.
  59463. GroundMesh.prototype._initHeightQuads = function () {
  59464. var subdivisionsX = this._subdivisionsX;
  59465. var subdivisionsY = this._subdivisionsY;
  59466. this._heightQuads = new Array();
  59467. for (var row = 0; row < subdivisionsY; row++) {
  59468. for (var col = 0; col < subdivisionsX; col++) {
  59469. 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) };
  59470. this._heightQuads[row * subdivisionsX + col] = quad;
  59471. }
  59472. }
  59473. return this;
  59474. };
  59475. // Compute each quad element values and update the the heightMap array :
  59476. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59477. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59478. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59479. // Returns the GroundMesh.
  59480. GroundMesh.prototype._computeHeightQuads = function () {
  59481. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59482. if (!positions) {
  59483. return this;
  59484. }
  59485. var v1 = BABYLON.Tmp.Vector3[3];
  59486. var v2 = BABYLON.Tmp.Vector3[2];
  59487. var v3 = BABYLON.Tmp.Vector3[1];
  59488. var v4 = BABYLON.Tmp.Vector3[0];
  59489. var v1v2 = BABYLON.Tmp.Vector3[4];
  59490. var v1v3 = BABYLON.Tmp.Vector3[5];
  59491. var v1v4 = BABYLON.Tmp.Vector3[6];
  59492. var norm1 = BABYLON.Tmp.Vector3[7];
  59493. var norm2 = BABYLON.Tmp.Vector3[8];
  59494. var i = 0;
  59495. var j = 0;
  59496. var k = 0;
  59497. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59498. var h = 0;
  59499. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59500. var d2 = 0;
  59501. var subdivisionsX = this._subdivisionsX;
  59502. var subdivisionsY = this._subdivisionsY;
  59503. for (var row = 0; row < subdivisionsY; row++) {
  59504. for (var col = 0; col < subdivisionsX; col++) {
  59505. i = col * 3;
  59506. j = row * (subdivisionsX + 1) * 3;
  59507. k = (row + 1) * (subdivisionsX + 1) * 3;
  59508. v1.x = positions[j + i];
  59509. v1.y = positions[j + i + 1];
  59510. v1.z = positions[j + i + 2];
  59511. v2.x = positions[j + i + 3];
  59512. v2.y = positions[j + i + 4];
  59513. v2.z = positions[j + i + 5];
  59514. v3.x = positions[k + i];
  59515. v3.y = positions[k + i + 1];
  59516. v3.z = positions[k + i + 2];
  59517. v4.x = positions[k + i + 3];
  59518. v4.y = positions[k + i + 4];
  59519. v4.z = positions[k + i + 5];
  59520. // 2D slope V1V4
  59521. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59522. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59523. // facet equations :
  59524. // we compute each facet normal vector
  59525. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59526. // we compute the value d by applying the equation to v1 which belongs to the plane
  59527. // then we store the facet equation in a Vector4
  59528. v2.subtractToRef(v1, v1v2);
  59529. v3.subtractToRef(v1, v1v3);
  59530. v4.subtractToRef(v1, v1v4);
  59531. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59532. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59533. norm1.normalize();
  59534. norm2.normalize();
  59535. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59536. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59537. var quad = this._heightQuads[row * subdivisionsX + col];
  59538. quad.slope.copyFromFloats(cd, h);
  59539. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59540. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59541. }
  59542. }
  59543. return this;
  59544. };
  59545. GroundMesh.prototype.serialize = function (serializationObject) {
  59546. _super.prototype.serialize.call(this, serializationObject);
  59547. serializationObject.subdivisionsX = this._subdivisionsX;
  59548. serializationObject.subdivisionsY = this._subdivisionsY;
  59549. serializationObject.minX = this._minX;
  59550. serializationObject.maxX = this._maxX;
  59551. serializationObject.minZ = this._minZ;
  59552. serializationObject.maxZ = this._maxZ;
  59553. serializationObject.width = this._width;
  59554. serializationObject.height = this._height;
  59555. };
  59556. GroundMesh.Parse = function (parsedMesh, scene) {
  59557. var result = new GroundMesh(parsedMesh.name, scene);
  59558. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59559. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59560. result._minX = parsedMesh.minX;
  59561. result._maxX = parsedMesh.maxX;
  59562. result._minZ = parsedMesh.minZ;
  59563. result._maxZ = parsedMesh.maxZ;
  59564. result._width = parsedMesh.width;
  59565. result._height = parsedMesh.height;
  59566. return result;
  59567. };
  59568. return GroundMesh;
  59569. }(BABYLON.Mesh));
  59570. BABYLON.GroundMesh = GroundMesh;
  59571. })(BABYLON || (BABYLON = {}));
  59572. //# sourceMappingURL=babylon.groundMesh.js.map
  59573. var BABYLON;
  59574. (function (BABYLON) {
  59575. /**
  59576. * Creates an instance based on a source mesh.
  59577. */
  59578. var InstancedMesh = /** @class */ (function (_super) {
  59579. __extends(InstancedMesh, _super);
  59580. function InstancedMesh(name, source) {
  59581. var _this = _super.call(this, name, source.getScene()) || this;
  59582. source.instances.push(_this);
  59583. _this._sourceMesh = source;
  59584. _this.position.copyFrom(source.position);
  59585. _this.rotation.copyFrom(source.rotation);
  59586. _this.scaling.copyFrom(source.scaling);
  59587. if (source.rotationQuaternion) {
  59588. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59589. }
  59590. _this.infiniteDistance = source.infiniteDistance;
  59591. _this.setPivotMatrix(source.getPivotMatrix());
  59592. _this.refreshBoundingInfo();
  59593. _this._syncSubMeshes();
  59594. return _this;
  59595. }
  59596. /**
  59597. * Returns the string "InstancedMesh".
  59598. */
  59599. InstancedMesh.prototype.getClassName = function () {
  59600. return "InstancedMesh";
  59601. };
  59602. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59603. // Methods
  59604. get: function () {
  59605. return this._sourceMesh.receiveShadows;
  59606. },
  59607. enumerable: true,
  59608. configurable: true
  59609. });
  59610. Object.defineProperty(InstancedMesh.prototype, "material", {
  59611. get: function () {
  59612. return this._sourceMesh.material;
  59613. },
  59614. enumerable: true,
  59615. configurable: true
  59616. });
  59617. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59618. get: function () {
  59619. return this._sourceMesh.visibility;
  59620. },
  59621. enumerable: true,
  59622. configurable: true
  59623. });
  59624. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59625. get: function () {
  59626. return this._sourceMesh.skeleton;
  59627. },
  59628. enumerable: true,
  59629. configurable: true
  59630. });
  59631. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59632. get: function () {
  59633. return this._sourceMesh.renderingGroupId;
  59634. },
  59635. set: function (value) {
  59636. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59637. return;
  59638. }
  59639. //no-op with warning
  59640. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59641. },
  59642. enumerable: true,
  59643. configurable: true
  59644. });
  59645. /**
  59646. * Returns the total number of vertices (integer).
  59647. */
  59648. InstancedMesh.prototype.getTotalVertices = function () {
  59649. return this._sourceMesh.getTotalVertices();
  59650. };
  59651. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59652. get: function () {
  59653. return this._sourceMesh;
  59654. },
  59655. enumerable: true,
  59656. configurable: true
  59657. });
  59658. /**
  59659. * Is this node ready to be used/rendered
  59660. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59661. * @return {boolean} is it ready
  59662. */
  59663. InstancedMesh.prototype.isReady = function (completeCheck) {
  59664. if (completeCheck === void 0) { completeCheck = false; }
  59665. return this._sourceMesh.isReady(completeCheck, true);
  59666. };
  59667. /**
  59668. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59669. */
  59670. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59671. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59672. };
  59673. /**
  59674. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59675. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59676. * The `data` are either a numeric array either a Float32Array.
  59677. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59678. * 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).
  59679. * Note that a new underlying VertexBuffer object is created each call.
  59680. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59681. *
  59682. * Possible `kind` values :
  59683. * - BABYLON.VertexBuffer.PositionKind
  59684. * - BABYLON.VertexBuffer.UVKind
  59685. * - BABYLON.VertexBuffer.UV2Kind
  59686. * - BABYLON.VertexBuffer.UV3Kind
  59687. * - BABYLON.VertexBuffer.UV4Kind
  59688. * - BABYLON.VertexBuffer.UV5Kind
  59689. * - BABYLON.VertexBuffer.UV6Kind
  59690. * - BABYLON.VertexBuffer.ColorKind
  59691. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59692. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59693. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59694. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59695. *
  59696. * Returns the Mesh.
  59697. */
  59698. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59699. if (this.sourceMesh) {
  59700. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59701. }
  59702. return this.sourceMesh;
  59703. };
  59704. /**
  59705. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59706. * If the mesh has no geometry, it is simply returned as it is.
  59707. * The `data` are either a numeric array either a Float32Array.
  59708. * No new underlying VertexBuffer object is created.
  59709. * 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.
  59710. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59711. *
  59712. * Possible `kind` values :
  59713. * - BABYLON.VertexBuffer.PositionKind
  59714. * - BABYLON.VertexBuffer.UVKind
  59715. * - BABYLON.VertexBuffer.UV2Kind
  59716. * - BABYLON.VertexBuffer.UV3Kind
  59717. * - BABYLON.VertexBuffer.UV4Kind
  59718. * - BABYLON.VertexBuffer.UV5Kind
  59719. * - BABYLON.VertexBuffer.UV6Kind
  59720. * - BABYLON.VertexBuffer.ColorKind
  59721. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59722. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59723. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59724. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59725. *
  59726. * Returns the Mesh.
  59727. */
  59728. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59729. if (this.sourceMesh) {
  59730. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59731. }
  59732. return this.sourceMesh;
  59733. };
  59734. /**
  59735. * Sets the mesh indices.
  59736. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59737. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59738. * This method creates a new index buffer each call.
  59739. * Returns the Mesh.
  59740. */
  59741. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59742. if (totalVertices === void 0) { totalVertices = null; }
  59743. if (this.sourceMesh) {
  59744. this.sourceMesh.setIndices(indices, totalVertices);
  59745. }
  59746. return this.sourceMesh;
  59747. };
  59748. /**
  59749. * Boolean : True if the mesh owns the requested kind of data.
  59750. */
  59751. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59752. return this._sourceMesh.isVerticesDataPresent(kind);
  59753. };
  59754. /**
  59755. * Returns an array of indices (IndicesArray).
  59756. */
  59757. InstancedMesh.prototype.getIndices = function () {
  59758. return this._sourceMesh.getIndices();
  59759. };
  59760. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59761. get: function () {
  59762. return this._sourceMesh._positions;
  59763. },
  59764. enumerable: true,
  59765. configurable: true
  59766. });
  59767. /**
  59768. * Sets a new updated BoundingInfo to the mesh.
  59769. * Returns the mesh.
  59770. */
  59771. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59772. var meshBB = this._sourceMesh.getBoundingInfo();
  59773. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59774. this._updateBoundingInfo();
  59775. return this;
  59776. };
  59777. InstancedMesh.prototype._preActivate = function () {
  59778. if (this._currentLOD) {
  59779. this._currentLOD._preActivate();
  59780. }
  59781. return this;
  59782. };
  59783. InstancedMesh.prototype._activate = function (renderId) {
  59784. if (this._currentLOD) {
  59785. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59786. }
  59787. return this;
  59788. };
  59789. /**
  59790. * Returns the current associated LOD AbstractMesh.
  59791. */
  59792. InstancedMesh.prototype.getLOD = function (camera) {
  59793. if (!camera) {
  59794. return this;
  59795. }
  59796. var boundingInfo = this.getBoundingInfo();
  59797. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59798. if (this._currentLOD === this.sourceMesh) {
  59799. return this;
  59800. }
  59801. return this._currentLOD;
  59802. };
  59803. InstancedMesh.prototype._syncSubMeshes = function () {
  59804. this.releaseSubMeshes();
  59805. if (this._sourceMesh.subMeshes) {
  59806. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59807. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59808. }
  59809. }
  59810. return this;
  59811. };
  59812. InstancedMesh.prototype._generatePointsArray = function () {
  59813. return this._sourceMesh._generatePointsArray();
  59814. };
  59815. /**
  59816. * Creates a new InstancedMesh from the current mesh.
  59817. * - name (string) : the cloned mesh name
  59818. * - newParent (optional Node) : the optional Node to parent the clone to.
  59819. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59820. *
  59821. * Returns the clone.
  59822. */
  59823. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59824. var result = this._sourceMesh.createInstance(name);
  59825. // Deep copy
  59826. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59827. // Bounding info
  59828. this.refreshBoundingInfo();
  59829. // Parent
  59830. if (newParent) {
  59831. result.parent = newParent;
  59832. }
  59833. if (!doNotCloneChildren) {
  59834. // Children
  59835. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59836. var mesh = this.getScene().meshes[index];
  59837. if (mesh.parent === this) {
  59838. mesh.clone(mesh.name, result);
  59839. }
  59840. }
  59841. }
  59842. result.computeWorldMatrix(true);
  59843. return result;
  59844. };
  59845. /**
  59846. * Disposes the InstancedMesh.
  59847. * Returns nothing.
  59848. */
  59849. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59850. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59851. // Remove from mesh
  59852. var index = this._sourceMesh.instances.indexOf(this);
  59853. this._sourceMesh.instances.splice(index, 1);
  59854. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59855. };
  59856. return InstancedMesh;
  59857. }(BABYLON.AbstractMesh));
  59858. BABYLON.InstancedMesh = InstancedMesh;
  59859. })(BABYLON || (BABYLON = {}));
  59860. //# sourceMappingURL=babylon.instancedMesh.js.map
  59861. var BABYLON;
  59862. (function (BABYLON) {
  59863. var LinesMesh = /** @class */ (function (_super) {
  59864. __extends(LinesMesh, _super);
  59865. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59866. if (scene === void 0) { scene = null; }
  59867. if (parent === void 0) { parent = null; }
  59868. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59869. _this.useVertexColor = useVertexColor;
  59870. _this.useVertexAlpha = useVertexAlpha;
  59871. _this.color = new BABYLON.Color3(1, 1, 1);
  59872. _this.alpha = 1;
  59873. if (source) {
  59874. _this.color = source.color.clone();
  59875. _this.alpha = source.alpha;
  59876. _this.useVertexColor = source.useVertexColor;
  59877. _this.useVertexAlpha = source.useVertexAlpha;
  59878. }
  59879. _this._intersectionThreshold = 0.1;
  59880. var defines = [];
  59881. var options = {
  59882. attributes: [BABYLON.VertexBuffer.PositionKind],
  59883. uniforms: ["world", "viewProjection"],
  59884. needAlphaBlending: true,
  59885. defines: defines
  59886. };
  59887. if (useVertexAlpha === false) {
  59888. options.needAlphaBlending = false;
  59889. }
  59890. if (!useVertexColor) {
  59891. options.uniforms.push("color");
  59892. }
  59893. else {
  59894. options.defines.push("#define VERTEXCOLOR");
  59895. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59896. }
  59897. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59898. return _this;
  59899. }
  59900. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59901. /**
  59902. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59903. * This margin is expressed in world space coordinates, so its value may vary.
  59904. * Default value is 0.1
  59905. * @returns the intersection Threshold value.
  59906. */
  59907. get: function () {
  59908. return this._intersectionThreshold;
  59909. },
  59910. /**
  59911. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59912. * This margin is expressed in world space coordinates, so its value may vary.
  59913. * @param value the new threshold to apply
  59914. */
  59915. set: function (value) {
  59916. if (this._intersectionThreshold === value) {
  59917. return;
  59918. }
  59919. this._intersectionThreshold = value;
  59920. if (this.geometry) {
  59921. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59922. }
  59923. },
  59924. enumerable: true,
  59925. configurable: true
  59926. });
  59927. /**
  59928. * Returns the string "LineMesh"
  59929. */
  59930. LinesMesh.prototype.getClassName = function () {
  59931. return "LinesMesh";
  59932. };
  59933. Object.defineProperty(LinesMesh.prototype, "material", {
  59934. get: function () {
  59935. return this._colorShader;
  59936. },
  59937. set: function (value) {
  59938. // Do nothing
  59939. },
  59940. enumerable: true,
  59941. configurable: true
  59942. });
  59943. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59944. get: function () {
  59945. return false;
  59946. },
  59947. enumerable: true,
  59948. configurable: true
  59949. });
  59950. LinesMesh.prototype.createInstance = function (name) {
  59951. throw new Error("LinesMeshes do not support createInstance.");
  59952. };
  59953. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59954. if (!this._geometry) {
  59955. return this;
  59956. }
  59957. // VBOs
  59958. this._geometry._bind(this._colorShader.getEffect());
  59959. // Color
  59960. if (!this.useVertexColor) {
  59961. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59962. }
  59963. return this;
  59964. };
  59965. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59966. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59967. return this;
  59968. }
  59969. var engine = this.getScene().getEngine();
  59970. // Draw order
  59971. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59972. return this;
  59973. };
  59974. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59975. this._colorShader.dispose();
  59976. _super.prototype.dispose.call(this, doNotRecurse);
  59977. };
  59978. /**
  59979. * Returns a new LineMesh object cloned from the current one.
  59980. */
  59981. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59982. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59983. };
  59984. return LinesMesh;
  59985. }(BABYLON.Mesh));
  59986. BABYLON.LinesMesh = LinesMesh;
  59987. })(BABYLON || (BABYLON = {}));
  59988. //# sourceMappingURL=babylon.linesMesh.js.map
  59989. var BABYLON;
  59990. (function (BABYLON) {
  59991. /**
  59992. * Class containing static functions to help procedurally build meshes
  59993. */
  59994. var MeshBuilder = /** @class */ (function () {
  59995. function MeshBuilder() {
  59996. }
  59997. MeshBuilder.updateSideOrientation = function (orientation) {
  59998. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59999. return BABYLON.Mesh.DOUBLESIDE;
  60000. }
  60001. if (orientation === undefined || orientation === null) {
  60002. return BABYLON.Mesh.FRONTSIDE;
  60003. }
  60004. return orientation;
  60005. };
  60006. /**
  60007. * Creates a box mesh
  60008. * * The parameter `size` sets the size (float) of each box side (default 1)
  60009. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60010. * * 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)
  60011. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60012. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60013. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60014. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60015. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60016. * @param name defines the name of the mesh
  60017. * @param options defines the options used to create the mesh
  60018. * @param scene defines the hosting scene
  60019. * @returns the box mesh
  60020. */
  60021. MeshBuilder.CreateBox = function (name, options, scene) {
  60022. if (scene === void 0) { scene = null; }
  60023. var box = new BABYLON.Mesh(name, scene);
  60024. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60025. box._originalBuilderSideOrientation = options.sideOrientation;
  60026. var vertexData = BABYLON.VertexData.CreateBox(options);
  60027. vertexData.applyToMesh(box, options.updatable);
  60028. return box;
  60029. };
  60030. /**
  60031. * Creates a sphere mesh
  60032. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60033. * * 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`)
  60034. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60035. * * 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
  60036. * * 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)
  60037. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60038. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60039. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60040. * @param name defines the name of the mesh
  60041. * @param options defines the options used to create the mesh
  60042. * @param scene defines the hosting scene
  60043. * @returns the sphere mesh
  60044. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60045. */
  60046. MeshBuilder.CreateSphere = function (name, options, scene) {
  60047. var sphere = new BABYLON.Mesh(name, scene);
  60048. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60049. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60050. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60051. vertexData.applyToMesh(sphere, options.updatable);
  60052. return sphere;
  60053. };
  60054. /**
  60055. * Creates a plane polygonal mesh. By default, this is a disc
  60056. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60057. * * 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
  60058. * * 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
  60059. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60060. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60061. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60062. * @param name defines the name of the mesh
  60063. * @param options defines the options used to create the mesh
  60064. * @param scene defines the hosting scene
  60065. * @returns the plane polygonal mesh
  60066. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  60067. */
  60068. MeshBuilder.CreateDisc = function (name, options, scene) {
  60069. if (scene === void 0) { scene = null; }
  60070. var disc = new BABYLON.Mesh(name, scene);
  60071. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60072. disc._originalBuilderSideOrientation = options.sideOrientation;
  60073. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60074. vertexData.applyToMesh(disc, options.updatable);
  60075. return disc;
  60076. };
  60077. /**
  60078. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60079. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60080. * * 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`)
  60081. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60082. * * 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
  60083. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60084. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60085. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60086. * @param name defines the name of the mesh
  60087. * @param options defines the options used to create the mesh
  60088. * @param scene defines the hosting scene
  60089. * @returns the icosahedron mesh
  60090. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  60091. */
  60092. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60093. var sphere = new BABYLON.Mesh(name, scene);
  60094. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60095. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60096. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60097. vertexData.applyToMesh(sphere, options.updatable);
  60098. return sphere;
  60099. };
  60100. ;
  60101. /**
  60102. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60103. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60104. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60105. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60106. * * 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
  60107. * * 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
  60108. * * 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
  60109. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60110. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60111. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60112. * * 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
  60113. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60114. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60115. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60116. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60117. * @param name defines the name of the mesh
  60118. * @param options defines the options used to create the mesh
  60119. * @param scene defines the hosting scene
  60120. * @returns the ribbon mesh
  60121. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60122. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60123. */
  60124. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60125. if (scene === void 0) { scene = null; }
  60126. var pathArray = options.pathArray;
  60127. var closeArray = options.closeArray;
  60128. var closePath = options.closePath;
  60129. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60130. var instance = options.instance;
  60131. var updatable = options.updatable;
  60132. if (instance) { // existing ribbon instance update
  60133. // positionFunction : ribbon case
  60134. // only pathArray and sideOrientation parameters are taken into account for positions update
  60135. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60136. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60137. var positionFunction = function (positions) {
  60138. var minlg = pathArray[0].length;
  60139. var i = 0;
  60140. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60141. for (var si = 1; si <= ns; si++) {
  60142. for (var p = 0; p < pathArray.length; p++) {
  60143. var path = pathArray[p];
  60144. var l = path.length;
  60145. minlg = (minlg < l) ? minlg : l;
  60146. var j = 0;
  60147. while (j < minlg) {
  60148. positions[i] = path[j].x;
  60149. positions[i + 1] = path[j].y;
  60150. positions[i + 2] = path[j].z;
  60151. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60152. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60153. }
  60154. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60155. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60156. }
  60157. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60158. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60159. }
  60160. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60161. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60162. }
  60163. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60164. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60165. }
  60166. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60167. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60168. }
  60169. j++;
  60170. i += 3;
  60171. }
  60172. if (instance._closePath) {
  60173. positions[i] = path[0].x;
  60174. positions[i + 1] = path[0].y;
  60175. positions[i + 2] = path[0].z;
  60176. i += 3;
  60177. }
  60178. }
  60179. }
  60180. };
  60181. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60182. positionFunction(positions);
  60183. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60184. instance._boundingInfo.update(instance._worldMatrix);
  60185. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60186. if (options.colors) {
  60187. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60188. for (var c = 0; c < options.colors.length; c++) {
  60189. colors[c * 4] = options.colors[c].r;
  60190. colors[c * 4 + 1] = options.colors[c].g;
  60191. colors[c * 4 + 2] = options.colors[c].b;
  60192. colors[c * 4 + 3] = options.colors[c].a;
  60193. }
  60194. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60195. }
  60196. if (options.uvs) {
  60197. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60198. for (var i = 0; i < options.uvs.length; i++) {
  60199. uvs[i * 2] = options.uvs[i].x;
  60200. uvs[i * 2 + 1] = options.uvs[i].y;
  60201. }
  60202. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60203. }
  60204. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60205. var indices = instance.getIndices();
  60206. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60207. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60208. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60209. if (instance._closePath) {
  60210. var indexFirst = 0;
  60211. var indexLast = 0;
  60212. for (var p = 0; p < pathArray.length; p++) {
  60213. indexFirst = instance._idx[p] * 3;
  60214. if (p + 1 < pathArray.length) {
  60215. indexLast = (instance._idx[p + 1] - 1) * 3;
  60216. }
  60217. else {
  60218. indexLast = normals.length - 3;
  60219. }
  60220. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60221. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60222. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60223. normals[indexLast] = normals[indexFirst];
  60224. normals[indexLast + 1] = normals[indexFirst + 1];
  60225. normals[indexLast + 2] = normals[indexFirst + 2];
  60226. }
  60227. }
  60228. if (!(instance.areNormalsFrozen)) {
  60229. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60230. }
  60231. }
  60232. return instance;
  60233. }
  60234. else { // new ribbon creation
  60235. var ribbon = new BABYLON.Mesh(name, scene);
  60236. ribbon._originalBuilderSideOrientation = sideOrientation;
  60237. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60238. if (closePath) {
  60239. ribbon._idx = vertexData._idx;
  60240. }
  60241. ribbon._closePath = closePath;
  60242. ribbon._closeArray = closeArray;
  60243. vertexData.applyToMesh(ribbon, updatable);
  60244. return ribbon;
  60245. }
  60246. };
  60247. /**
  60248. * Creates a cylinder or a cone mesh
  60249. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60250. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60251. * * 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.
  60252. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60253. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60254. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60255. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60256. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60257. * * 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).
  60258. * * 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
  60259. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60260. * * 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
  60261. * * 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.
  60262. * * If `enclose` is false, a ring surface is one element.
  60263. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60264. * * 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
  60265. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60266. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60267. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60268. * @param name defines the name of the mesh
  60269. * @param options defines the options used to create the mesh
  60270. * @param scene defines the hosting scene
  60271. * @returns the cylinder mesh
  60272. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60273. */
  60274. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60275. var cylinder = new BABYLON.Mesh(name, scene);
  60276. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60277. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60278. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60279. vertexData.applyToMesh(cylinder, options.updatable);
  60280. return cylinder;
  60281. };
  60282. /**
  60283. * Creates a torus mesh
  60284. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60285. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60286. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60287. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60288. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60289. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60290. * @param name defines the name of the mesh
  60291. * @param options defines the options used to create the mesh
  60292. * @param scene defines the hosting scene
  60293. * @returns the torus mesh
  60294. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60295. */
  60296. MeshBuilder.CreateTorus = function (name, options, scene) {
  60297. var torus = new BABYLON.Mesh(name, scene);
  60298. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60299. torus._originalBuilderSideOrientation = options.sideOrientation;
  60300. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60301. vertexData.applyToMesh(torus, options.updatable);
  60302. return torus;
  60303. };
  60304. /**
  60305. * Creates a torus knot mesh
  60306. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60307. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60308. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60309. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60310. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60311. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60312. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60313. * @param name defines the name of the mesh
  60314. * @param options defines the options used to create the mesh
  60315. * @param scene defines the hosting scene
  60316. * @returns the torus knot mesh
  60317. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60318. */
  60319. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60320. var torusKnot = new BABYLON.Mesh(name, scene);
  60321. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60322. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60323. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60324. vertexData.applyToMesh(torusKnot, options.updatable);
  60325. return torusKnot;
  60326. };
  60327. /**
  60328. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60329. * * 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
  60330. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60331. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60332. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60333. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60334. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60335. * * 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
  60336. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60337. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60338. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  60339. * @param name defines the name of the new line system
  60340. * @param options defines the options used to create the line system
  60341. * @param scene defines the hosting scene
  60342. * @returns a new line system mesh
  60343. */
  60344. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60345. var instance = options.instance;
  60346. var lines = options.lines;
  60347. var colors = options.colors;
  60348. if (instance) { // lines update
  60349. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60350. var vertexColor;
  60351. var lineColors;
  60352. if (colors) {
  60353. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60354. }
  60355. var i = 0;
  60356. var c = 0;
  60357. for (var l = 0; l < lines.length; l++) {
  60358. var points = lines[l];
  60359. for (var p = 0; p < points.length; p++) {
  60360. positions[i] = points[p].x;
  60361. positions[i + 1] = points[p].y;
  60362. positions[i + 2] = points[p].z;
  60363. if (colors && vertexColor) {
  60364. lineColors = colors[l];
  60365. vertexColor[c] = lineColors[p].r;
  60366. vertexColor[c + 1] = lineColors[p].g;
  60367. vertexColor[c + 2] = lineColors[p].b;
  60368. vertexColor[c + 3] = lineColors[p].a;
  60369. c += 4;
  60370. }
  60371. i += 3;
  60372. }
  60373. }
  60374. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60375. if (colors && vertexColor) {
  60376. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60377. }
  60378. return instance;
  60379. }
  60380. // line system creation
  60381. var useVertexColor = (colors) ? true : false;
  60382. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60383. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60384. vertexData.applyToMesh(lineSystem, options.updatable);
  60385. return lineSystem;
  60386. };
  60387. /**
  60388. * Creates a line mesh
  60389. * 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
  60390. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60391. * * The parameter `points` is an array successive Vector3
  60392. * * 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
  60393. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60394. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60395. * * When updating an instance, remember that only point positions can change, not the number of points
  60396. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60397. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  60398. * @param name defines the name of the new line system
  60399. * @param options defines the options used to create the line system
  60400. * @param scene defines the hosting scene
  60401. * @returns a new line mesh
  60402. */
  60403. MeshBuilder.CreateLines = function (name, options, scene) {
  60404. if (scene === void 0) { scene = null; }
  60405. var colors = (options.colors) ? [options.colors] : null;
  60406. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60407. return lines;
  60408. };
  60409. /**
  60410. * Creates a dashed line mesh
  60411. * * 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
  60412. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60413. * * The parameter `points` is an array successive Vector3
  60414. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60415. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60416. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60417. * * 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
  60418. * * When updating an instance, remember that only point positions can change, not the number of points
  60419. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60420. * @param name defines the name of the mesh
  60421. * @param options defines the options used to create the mesh
  60422. * @param scene defines the hosting scene
  60423. * @returns the dashed line mesh
  60424. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  60425. */
  60426. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60427. if (scene === void 0) { scene = null; }
  60428. var points = options.points;
  60429. var instance = options.instance;
  60430. var gapSize = options.gapSize || 1;
  60431. var dashSize = options.dashSize || 3;
  60432. if (instance) { // dashed lines update
  60433. var positionFunction = function (positions) {
  60434. var curvect = BABYLON.Vector3.Zero();
  60435. var nbSeg = positions.length / 6;
  60436. var lg = 0;
  60437. var nb = 0;
  60438. var shft = 0;
  60439. var dashshft = 0;
  60440. var curshft = 0;
  60441. var p = 0;
  60442. var i = 0;
  60443. var j = 0;
  60444. for (i = 0; i < points.length - 1; i++) {
  60445. points[i + 1].subtractToRef(points[i], curvect);
  60446. lg += curvect.length();
  60447. }
  60448. shft = lg / nbSeg;
  60449. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60450. for (i = 0; i < points.length - 1; i++) {
  60451. points[i + 1].subtractToRef(points[i], curvect);
  60452. nb = Math.floor(curvect.length() / shft);
  60453. curvect.normalize();
  60454. j = 0;
  60455. while (j < nb && p < positions.length) {
  60456. curshft = shft * j;
  60457. positions[p] = points[i].x + curshft * curvect.x;
  60458. positions[p + 1] = points[i].y + curshft * curvect.y;
  60459. positions[p + 2] = points[i].z + curshft * curvect.z;
  60460. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60461. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60462. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60463. p += 6;
  60464. j++;
  60465. }
  60466. }
  60467. while (p < positions.length) {
  60468. positions[p] = points[i].x;
  60469. positions[p + 1] = points[i].y;
  60470. positions[p + 2] = points[i].z;
  60471. p += 3;
  60472. }
  60473. };
  60474. instance.updateMeshPositions(positionFunction, false);
  60475. return instance;
  60476. }
  60477. // dashed lines creation
  60478. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60479. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60480. vertexData.applyToMesh(dashedLines, options.updatable);
  60481. dashedLines.dashSize = dashSize;
  60482. dashedLines.gapSize = gapSize;
  60483. return dashedLines;
  60484. };
  60485. /**
  60486. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60487. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60488. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60489. * * 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.
  60490. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60491. * * 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
  60492. * * 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
  60493. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60494. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60495. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60496. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60497. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60498. * @param name defines the name of the mesh
  60499. * @param options defines the options used to create the mesh
  60500. * @param scene defines the hosting scene
  60501. * @returns the extruded shape mesh
  60502. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60503. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60504. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  60505. */
  60506. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60507. if (scene === void 0) { scene = null; }
  60508. var path = options.path;
  60509. var shape = options.shape;
  60510. var scale = options.scale || 1;
  60511. var rotation = options.rotation || 0;
  60512. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60513. var updatable = options.updatable;
  60514. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60515. var instance = options.instance || null;
  60516. var invertUV = options.invertUV || false;
  60517. 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);
  60518. };
  60519. /**
  60520. * Creates an custom extruded shape mesh.
  60521. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60522. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60523. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60524. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60525. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60526. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60527. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60528. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60529. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60530. * * 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
  60531. * * 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
  60532. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60533. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60534. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60535. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60536. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60537. * @param name defines the name of the mesh
  60538. * @param options defines the options used to create the mesh
  60539. * @param scene defines the hosting scene
  60540. * @returns the custom extruded shape mesh
  60541. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60542. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60543. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60544. */
  60545. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60546. var path = options.path;
  60547. var shape = options.shape;
  60548. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60549. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60550. var ribbonCloseArray = options.ribbonCloseArray || false;
  60551. var ribbonClosePath = options.ribbonClosePath || false;
  60552. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60553. var updatable = options.updatable;
  60554. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60555. var instance = options.instance;
  60556. var invertUV = options.invertUV || false;
  60557. 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);
  60558. };
  60559. /**
  60560. * Creates lathe mesh.
  60561. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60562. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  60563. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60564. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60565. * * 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
  60566. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60567. * * 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
  60568. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60569. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60570. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60571. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60572. * @param name defines the name of the mesh
  60573. * @param options defines the options used to create the mesh
  60574. * @param scene defines the hosting scene
  60575. * @returns the lathe mesh
  60576. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  60577. */
  60578. MeshBuilder.CreateLathe = function (name, options, scene) {
  60579. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60580. var closed = (options.closed === undefined) ? true : options.closed;
  60581. var shape = options.shape;
  60582. var radius = options.radius || 1;
  60583. var tessellation = options.tessellation || 64;
  60584. var updatable = options.updatable;
  60585. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60586. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60587. var pi2 = Math.PI * 2;
  60588. var paths = new Array();
  60589. var invertUV = options.invertUV || false;
  60590. var i = 0;
  60591. var p = 0;
  60592. var step = pi2 / tessellation * arc;
  60593. var rotated;
  60594. var path = new Array();
  60595. ;
  60596. for (i = 0; i <= tessellation; i++) {
  60597. var path = [];
  60598. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60599. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60600. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60601. }
  60602. for (p = 0; p < shape.length; p++) {
  60603. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60604. path.push(rotated);
  60605. }
  60606. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60607. 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));
  60608. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60609. }
  60610. paths.push(path);
  60611. }
  60612. // lathe ribbon
  60613. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60614. return lathe;
  60615. };
  60616. /**
  60617. * Creates a plane mesh
  60618. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60619. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60620. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60621. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60622. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60623. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60624. * @param name defines the name of the mesh
  60625. * @param options defines the options used to create the mesh
  60626. * @param scene defines the hosting scene
  60627. * @returns the plane mesh
  60628. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60629. */
  60630. MeshBuilder.CreatePlane = function (name, options, scene) {
  60631. var plane = new BABYLON.Mesh(name, scene);
  60632. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60633. plane._originalBuilderSideOrientation = options.sideOrientation;
  60634. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60635. vertexData.applyToMesh(plane, options.updatable);
  60636. if (options.sourcePlane) {
  60637. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60638. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60639. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60640. plane.rotate(vectorProduct, product);
  60641. }
  60642. return plane;
  60643. };
  60644. /**
  60645. * Creates a ground mesh
  60646. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60647. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60648. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60649. * @param name defines the name of the mesh
  60650. * @param options defines the options used to create the mesh
  60651. * @param scene defines the hosting scene
  60652. * @returns the ground mesh
  60653. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60654. */
  60655. MeshBuilder.CreateGround = function (name, options, scene) {
  60656. var ground = new BABYLON.GroundMesh(name, scene);
  60657. ground._setReady(false);
  60658. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60659. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60660. ground._width = options.width || 1;
  60661. ground._height = options.height || 1;
  60662. ground._maxX = ground._width / 2;
  60663. ground._maxZ = ground._height / 2;
  60664. ground._minX = -ground._maxX;
  60665. ground._minZ = -ground._maxZ;
  60666. var vertexData = BABYLON.VertexData.CreateGround(options);
  60667. vertexData.applyToMesh(ground, options.updatable);
  60668. ground._setReady(true);
  60669. return ground;
  60670. };
  60671. /**
  60672. * Creates a tiled ground mesh
  60673. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60674. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60675. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  60676. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  60677. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60678. * @param name defines the name of the mesh
  60679. * @param options defines the options used to create the mesh
  60680. * @param scene defines the hosting scene
  60681. * @returns the tiled ground mesh
  60682. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60683. */
  60684. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60685. var tiledGround = new BABYLON.Mesh(name, scene);
  60686. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60687. vertexData.applyToMesh(tiledGround, options.updatable);
  60688. return tiledGround;
  60689. };
  60690. /**
  60691. * Creates a ground mesh from a height map
  60692. * * The parameter `url` sets the URL of the height map image resource.
  60693. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60694. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60695. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60696. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60697. * * 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.
  60698. * * 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).
  60699. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60700. * @param name defines the name of the mesh
  60701. * @param url defines the url to the height map
  60702. * @param options defines the options used to create the mesh
  60703. * @param scene defines the hosting scene
  60704. * @returns the ground mesh
  60705. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  60706. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60707. */
  60708. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60709. var width = options.width || 10.0;
  60710. var height = options.height || 10.0;
  60711. var subdivisions = options.subdivisions || 1 | 0;
  60712. var minHeight = options.minHeight || 0.0;
  60713. var maxHeight = options.maxHeight || 1.0;
  60714. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60715. var updatable = options.updatable;
  60716. var onReady = options.onReady;
  60717. var ground = new BABYLON.GroundMesh(name, scene);
  60718. ground._subdivisionsX = subdivisions;
  60719. ground._subdivisionsY = subdivisions;
  60720. ground._width = width;
  60721. ground._height = height;
  60722. ground._maxX = ground._width / 2.0;
  60723. ground._maxZ = ground._height / 2.0;
  60724. ground._minX = -ground._maxX;
  60725. ground._minZ = -ground._maxZ;
  60726. ground._setReady(false);
  60727. var onload = function (img) {
  60728. // Getting height map data
  60729. var canvas = document.createElement("canvas");
  60730. var context = canvas.getContext("2d");
  60731. if (!context) {
  60732. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60733. }
  60734. if (scene.isDisposed) {
  60735. return;
  60736. }
  60737. var bufferWidth = img.width;
  60738. var bufferHeight = img.height;
  60739. canvas.width = bufferWidth;
  60740. canvas.height = bufferHeight;
  60741. context.drawImage(img, 0, 0);
  60742. // Create VertexData from map data
  60743. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60744. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60745. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60746. width: width, height: height,
  60747. subdivisions: subdivisions,
  60748. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60749. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60750. });
  60751. vertexData.applyToMesh(ground, updatable);
  60752. //execute ready callback, if set
  60753. if (onReady) {
  60754. onReady(ground);
  60755. }
  60756. ground._setReady(true);
  60757. };
  60758. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60759. return ground;
  60760. };
  60761. /**
  60762. * Creates a polygon mesh
  60763. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60764. * * 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
  60765. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60766. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60767. * * 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)
  60768. * * Remember you can only change the shape positions, not their number when updating a polygon
  60769. * @param name defines the name of the mesh
  60770. * @param options defines the options used to create the mesh
  60771. * @param scene defines the hosting scene
  60772. * @returns the polygon mesh
  60773. */
  60774. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60775. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60776. var shape = options.shape;
  60777. var holes = options.holes || [];
  60778. var depth = options.depth || 0;
  60779. var contours = [];
  60780. var hole = [];
  60781. for (var i = 0; i < shape.length; i++) {
  60782. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60783. }
  60784. var epsilon = 0.00000001;
  60785. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60786. contours.pop();
  60787. }
  60788. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60789. for (var hNb = 0; hNb < holes.length; hNb++) {
  60790. hole = [];
  60791. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60792. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60793. }
  60794. polygonTriangulation.addHole(hole);
  60795. }
  60796. var polygon = polygonTriangulation.build(options.updatable, depth);
  60797. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60798. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60799. vertexData.applyToMesh(polygon, options.updatable);
  60800. return polygon;
  60801. };
  60802. ;
  60803. /**
  60804. * Creates an extruded polygon mesh, with depth in the Y direction.
  60805. * * 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)
  60806. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60807. * @param name defines the name of the mesh
  60808. * @param options defines the options used to create the mesh
  60809. * @param scene defines the hosting scene
  60810. * @returns the polygon mesh
  60811. */
  60812. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60813. return MeshBuilder.CreatePolygon(name, options, scene);
  60814. };
  60815. ;
  60816. /**
  60817. * Creates a tube mesh.
  60818. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60819. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60820. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60821. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60822. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60823. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  60824. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60825. * * 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
  60826. * * 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
  60827. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60828. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60829. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60830. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60831. * @param name defines the name of the mesh
  60832. * @param options defines the options used to create the mesh
  60833. * @param scene defines the hosting scene
  60834. * @returns the tube mesh
  60835. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60836. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60837. */
  60838. MeshBuilder.CreateTube = function (name, options, scene) {
  60839. var path = options.path;
  60840. var instance = options.instance;
  60841. var radius = 1.0;
  60842. if (instance) {
  60843. radius = instance.radius;
  60844. }
  60845. if (options.radius !== undefined) {
  60846. radius = options.radius;
  60847. }
  60848. ;
  60849. var tessellation = options.tessellation || 64 | 0;
  60850. var radiusFunction = options.radiusFunction || null;
  60851. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60852. var invertUV = options.invertUV || false;
  60853. var updatable = options.updatable;
  60854. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60855. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60856. // tube geometry
  60857. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60858. var tangents = path3D.getTangents();
  60859. var normals = path3D.getNormals();
  60860. var distances = path3D.getDistances();
  60861. var pi2 = Math.PI * 2;
  60862. var step = pi2 / tessellation * arc;
  60863. var returnRadius = function () { return radius; };
  60864. var radiusFunctionFinal = radiusFunction || returnRadius;
  60865. var circlePath;
  60866. var rad;
  60867. var normal;
  60868. var rotated;
  60869. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60870. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60871. for (var i = 0; i < path.length; i++) {
  60872. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60873. circlePath = Array(); // current circle array
  60874. normal = normals[i]; // current normal
  60875. for (var t = 0; t < tessellation; t++) {
  60876. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60877. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60878. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60879. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60880. circlePath[t] = rotated;
  60881. }
  60882. circlePaths[index] = circlePath;
  60883. index++;
  60884. }
  60885. // cap
  60886. var capPath = function (nbPoints, pathIndex) {
  60887. var pointCap = Array();
  60888. for (var i = 0; i < nbPoints; i++) {
  60889. pointCap.push(path[pathIndex]);
  60890. }
  60891. return pointCap;
  60892. };
  60893. switch (cap) {
  60894. case BABYLON.Mesh.NO_CAP:
  60895. break;
  60896. case BABYLON.Mesh.CAP_START:
  60897. circlePaths[0] = capPath(tessellation, 0);
  60898. circlePaths[1] = circlePaths[2].slice(0);
  60899. break;
  60900. case BABYLON.Mesh.CAP_END:
  60901. circlePaths[index] = circlePaths[index - 1].slice(0);
  60902. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60903. break;
  60904. case BABYLON.Mesh.CAP_ALL:
  60905. circlePaths[0] = capPath(tessellation, 0);
  60906. circlePaths[1] = circlePaths[2].slice(0);
  60907. circlePaths[index] = circlePaths[index - 1].slice(0);
  60908. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60909. break;
  60910. default:
  60911. break;
  60912. }
  60913. return circlePaths;
  60914. };
  60915. var path3D;
  60916. var pathArray;
  60917. if (instance) { // tube update
  60918. var arc = options.arc || instance.arc;
  60919. path3D = (instance.path3D).update(path);
  60920. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60921. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60922. instance.path3D = path3D;
  60923. instance.pathArray = pathArray;
  60924. instance.arc = arc;
  60925. instance.radius = radius;
  60926. return instance;
  60927. }
  60928. // tube creation
  60929. path3D = new BABYLON.Path3D(path);
  60930. var newPathArray = new Array();
  60931. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60932. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60933. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60934. tube.pathArray = pathArray;
  60935. tube.path3D = path3D;
  60936. tube.tessellation = tessellation;
  60937. tube.cap = cap;
  60938. tube.arc = options.arc;
  60939. tube.radius = radius;
  60940. return tube;
  60941. };
  60942. /**
  60943. * Creates a polyhedron mesh
  60944. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  60945. * * The parameter `size` (positive float, default 1) sets the polygon size
  60946. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60947. * * 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`
  60948. * * 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
  60949. * * 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)`)
  60950. * * 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
  60951. * * 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
  60952. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60953. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60954. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60955. * @param name defines the name of the mesh
  60956. * @param options defines the options used to create the mesh
  60957. * @param scene defines the hosting scene
  60958. * @returns the polyhedron mesh
  60959. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  60960. */
  60961. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60962. var polyhedron = new BABYLON.Mesh(name, scene);
  60963. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60964. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60965. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60966. vertexData.applyToMesh(polyhedron, options.updatable);
  60967. return polyhedron;
  60968. };
  60969. /**
  60970. * Creates a decal mesh.
  60971. * 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
  60972. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60973. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60974. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60975. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60976. * @param name defines the name of the mesh
  60977. * @param sourceMesh defines the mesh where the decal must be applied
  60978. * @param options defines the options used to create the mesh
  60979. * @param scene defines the hosting scene
  60980. * @returns the decal mesh
  60981. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60982. */
  60983. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60984. var indices = sourceMesh.getIndices();
  60985. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60986. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60987. var position = options.position || BABYLON.Vector3.Zero();
  60988. var normal = options.normal || BABYLON.Vector3.Up();
  60989. var size = options.size || BABYLON.Vector3.One();
  60990. var angle = options.angle || 0;
  60991. // Getting correct rotation
  60992. if (!normal) {
  60993. var target = new BABYLON.Vector3(0, 0, 1);
  60994. var camera = sourceMesh.getScene().activeCamera;
  60995. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60996. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60997. }
  60998. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60999. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61000. var pitch = Math.atan2(normal.y, len);
  61001. // Matrix
  61002. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61003. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61004. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61005. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61006. var vertexData = new BABYLON.VertexData();
  61007. vertexData.indices = [];
  61008. vertexData.positions = [];
  61009. vertexData.normals = [];
  61010. vertexData.uvs = [];
  61011. var currentVertexDataIndex = 0;
  61012. var extractDecalVector3 = function (indexId) {
  61013. var result = new BABYLON.PositionNormalVertex();
  61014. if (!indices || !positions || !normals) {
  61015. return result;
  61016. }
  61017. var vertexId = indices[indexId];
  61018. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61019. // Send vector to decal local world
  61020. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61021. // Get normal
  61022. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61023. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61024. return result;
  61025. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61026. var clip = function (vertices, axis) {
  61027. if (vertices.length === 0) {
  61028. return vertices;
  61029. }
  61030. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61031. var clipVertices = function (v0, v1) {
  61032. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61033. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61034. };
  61035. var result = new Array();
  61036. for (var index = 0; index < vertices.length; index += 3) {
  61037. var v1Out;
  61038. var v2Out;
  61039. var v3Out;
  61040. var total = 0;
  61041. var nV1 = null;
  61042. var nV2 = null;
  61043. var nV3 = null;
  61044. var nV4 = null;
  61045. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61046. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61047. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61048. v1Out = d1 > 0;
  61049. v2Out = d2 > 0;
  61050. v3Out = d3 > 0;
  61051. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61052. switch (total) {
  61053. case 0:
  61054. result.push(vertices[index]);
  61055. result.push(vertices[index + 1]);
  61056. result.push(vertices[index + 2]);
  61057. break;
  61058. case 1:
  61059. if (v1Out) {
  61060. nV1 = vertices[index + 1];
  61061. nV2 = vertices[index + 2];
  61062. nV3 = clipVertices(vertices[index], nV1);
  61063. nV4 = clipVertices(vertices[index], nV2);
  61064. }
  61065. if (v2Out) {
  61066. nV1 = vertices[index];
  61067. nV2 = vertices[index + 2];
  61068. nV3 = clipVertices(vertices[index + 1], nV1);
  61069. nV4 = clipVertices(vertices[index + 1], nV2);
  61070. result.push(nV3);
  61071. result.push(nV2.clone());
  61072. result.push(nV1.clone());
  61073. result.push(nV2.clone());
  61074. result.push(nV3.clone());
  61075. result.push(nV4);
  61076. break;
  61077. }
  61078. if (v3Out) {
  61079. nV1 = vertices[index];
  61080. nV2 = vertices[index + 1];
  61081. nV3 = clipVertices(vertices[index + 2], nV1);
  61082. nV4 = clipVertices(vertices[index + 2], nV2);
  61083. }
  61084. if (nV1 && nV2 && nV3 && nV4) {
  61085. result.push(nV1.clone());
  61086. result.push(nV2.clone());
  61087. result.push(nV3);
  61088. result.push(nV4);
  61089. result.push(nV3.clone());
  61090. result.push(nV2.clone());
  61091. }
  61092. break;
  61093. case 2:
  61094. if (!v1Out) {
  61095. nV1 = vertices[index].clone();
  61096. nV2 = clipVertices(nV1, vertices[index + 1]);
  61097. nV3 = clipVertices(nV1, vertices[index + 2]);
  61098. result.push(nV1);
  61099. result.push(nV2);
  61100. result.push(nV3);
  61101. }
  61102. if (!v2Out) {
  61103. nV1 = vertices[index + 1].clone();
  61104. nV2 = clipVertices(nV1, vertices[index + 2]);
  61105. nV3 = clipVertices(nV1, vertices[index]);
  61106. result.push(nV1);
  61107. result.push(nV2);
  61108. result.push(nV3);
  61109. }
  61110. if (!v3Out) {
  61111. nV1 = vertices[index + 2].clone();
  61112. nV2 = clipVertices(nV1, vertices[index]);
  61113. nV3 = clipVertices(nV1, vertices[index + 1]);
  61114. result.push(nV1);
  61115. result.push(nV2);
  61116. result.push(nV3);
  61117. }
  61118. break;
  61119. case 3:
  61120. break;
  61121. }
  61122. }
  61123. return result;
  61124. };
  61125. for (var index = 0; index < indices.length; index += 3) {
  61126. var faceVertices = new Array();
  61127. faceVertices.push(extractDecalVector3(index));
  61128. faceVertices.push(extractDecalVector3(index + 1));
  61129. faceVertices.push(extractDecalVector3(index + 2));
  61130. // Clip
  61131. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61132. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61133. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61134. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61135. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61136. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61137. if (faceVertices.length === 0) {
  61138. continue;
  61139. }
  61140. // Add UVs and get back to world
  61141. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61142. var vertex = faceVertices[vIndex];
  61143. //TODO check for Int32Array | Uint32Array | Uint16Array
  61144. vertexData.indices.push(currentVertexDataIndex);
  61145. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61146. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61147. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61148. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61149. currentVertexDataIndex++;
  61150. }
  61151. }
  61152. // Return mesh
  61153. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61154. vertexData.applyToMesh(decal);
  61155. decal.position = position.clone();
  61156. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61157. return decal;
  61158. };
  61159. // Privates
  61160. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61161. // extrusion geometry
  61162. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61163. var tangents = path3D.getTangents();
  61164. var normals = path3D.getNormals();
  61165. var binormals = path3D.getBinormals();
  61166. var distances = path3D.getDistances();
  61167. var angle = 0;
  61168. var returnScale = function () { return scale !== null ? scale : 1; };
  61169. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61170. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61171. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61172. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61173. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61174. for (var i = 0; i < curve.length; i++) {
  61175. var shapePath = new Array();
  61176. var angleStep = rotate(i, distances[i]);
  61177. var scaleRatio = scl(i, distances[i]);
  61178. for (var p = 0; p < shape.length; p++) {
  61179. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61180. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61181. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61182. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61183. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61184. shapePath[p] = rotated;
  61185. }
  61186. shapePaths[index] = shapePath;
  61187. angle += angleStep;
  61188. index++;
  61189. }
  61190. // cap
  61191. var capPath = function (shapePath) {
  61192. var pointCap = Array();
  61193. var barycenter = BABYLON.Vector3.Zero();
  61194. var i;
  61195. for (i = 0; i < shapePath.length; i++) {
  61196. barycenter.addInPlace(shapePath[i]);
  61197. }
  61198. barycenter.scaleInPlace(1.0 / shapePath.length);
  61199. for (i = 0; i < shapePath.length; i++) {
  61200. pointCap.push(barycenter);
  61201. }
  61202. return pointCap;
  61203. };
  61204. switch (cap) {
  61205. case BABYLON.Mesh.NO_CAP:
  61206. break;
  61207. case BABYLON.Mesh.CAP_START:
  61208. shapePaths[0] = capPath(shapePaths[2]);
  61209. shapePaths[1] = shapePaths[2];
  61210. break;
  61211. case BABYLON.Mesh.CAP_END:
  61212. shapePaths[index] = shapePaths[index - 1];
  61213. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61214. break;
  61215. case BABYLON.Mesh.CAP_ALL:
  61216. shapePaths[0] = capPath(shapePaths[2]);
  61217. shapePaths[1] = shapePaths[2];
  61218. shapePaths[index] = shapePaths[index - 1];
  61219. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61220. break;
  61221. default:
  61222. break;
  61223. }
  61224. return shapePaths;
  61225. };
  61226. var path3D;
  61227. var pathArray;
  61228. if (instance) { // instance update
  61229. path3D = (instance.path3D).update(curve);
  61230. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61231. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61232. return instance;
  61233. }
  61234. // extruded shape creation
  61235. path3D = new BABYLON.Path3D(curve);
  61236. var newShapePaths = new Array();
  61237. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61238. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61239. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61240. extrudedGeneric.pathArray = pathArray;
  61241. extrudedGeneric.path3D = path3D;
  61242. extrudedGeneric.cap = cap;
  61243. return extrudedGeneric;
  61244. };
  61245. return MeshBuilder;
  61246. }());
  61247. BABYLON.MeshBuilder = MeshBuilder;
  61248. })(BABYLON || (BABYLON = {}));
  61249. //# sourceMappingURL=babylon.meshBuilder.js.map
  61250. var BABYLON;
  61251. (function (BABYLON) {
  61252. /**
  61253. * Draco compression (https://google.github.io/draco/)
  61254. */
  61255. var DracoCompression = /** @class */ (function () {
  61256. /**
  61257. * Constructor
  61258. */
  61259. function DracoCompression() {
  61260. }
  61261. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61262. /**
  61263. * Returns true if the decoder is available.
  61264. */
  61265. get: function () {
  61266. if (typeof DracoDecoderModule !== "undefined") {
  61267. return true;
  61268. }
  61269. var decoder = DracoCompression.Configuration.decoder;
  61270. if (decoder) {
  61271. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61272. return true;
  61273. }
  61274. if (decoder.fallbackUrl) {
  61275. return true;
  61276. }
  61277. }
  61278. return false;
  61279. },
  61280. enumerable: true,
  61281. configurable: true
  61282. });
  61283. /**
  61284. * Stop all async operations and release resources.
  61285. */
  61286. DracoCompression.prototype.dispose = function () {
  61287. };
  61288. /**
  61289. * Decode Draco compressed mesh data to vertex data.
  61290. * @param data The array buffer view for the Draco compression data
  61291. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61292. * @returns A promise that resolves with the decoded vertex data
  61293. */
  61294. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61295. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61296. var module = wrappedModule.module;
  61297. var vertexData = new BABYLON.VertexData();
  61298. var buffer = new module.DecoderBuffer();
  61299. buffer.Init(data, data.byteLength);
  61300. var decoder = new module.Decoder();
  61301. var geometry;
  61302. var status;
  61303. try {
  61304. var type = decoder.GetEncodedGeometryType(buffer);
  61305. switch (type) {
  61306. case module.TRIANGULAR_MESH:
  61307. geometry = new module.Mesh();
  61308. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61309. break;
  61310. case module.POINT_CLOUD:
  61311. geometry = new module.PointCloud();
  61312. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61313. break;
  61314. default:
  61315. throw new Error("Invalid geometry type " + type);
  61316. }
  61317. if (!status.ok() || !geometry.ptr) {
  61318. throw new Error(status.error_msg());
  61319. }
  61320. var numPoints = geometry.num_points();
  61321. if (type === module.TRIANGULAR_MESH) {
  61322. var numFaces = geometry.num_faces();
  61323. var faceIndices = new module.DracoInt32Array();
  61324. try {
  61325. var indices = new Uint32Array(numFaces * 3);
  61326. for (var i = 0; i < numFaces; i++) {
  61327. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61328. var offset = i * 3;
  61329. indices[offset + 0] = faceIndices.GetValue(0);
  61330. indices[offset + 1] = faceIndices.GetValue(1);
  61331. indices[offset + 2] = faceIndices.GetValue(2);
  61332. }
  61333. vertexData.indices = indices;
  61334. }
  61335. finally {
  61336. module.destroy(faceIndices);
  61337. }
  61338. }
  61339. for (var kind in attributes) {
  61340. var uniqueId = attributes[kind];
  61341. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61342. var dracoData = new module.DracoFloat32Array();
  61343. try {
  61344. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61345. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61346. for (var i = 0; i < babylonData.length; i++) {
  61347. babylonData[i] = dracoData.GetValue(i);
  61348. }
  61349. vertexData.set(babylonData, kind);
  61350. }
  61351. finally {
  61352. module.destroy(dracoData);
  61353. }
  61354. }
  61355. }
  61356. finally {
  61357. if (geometry) {
  61358. module.destroy(geometry);
  61359. }
  61360. module.destroy(decoder);
  61361. module.destroy(buffer);
  61362. }
  61363. return vertexData;
  61364. });
  61365. };
  61366. DracoCompression._GetDecoderModule = function () {
  61367. if (!DracoCompression._DecoderModulePromise) {
  61368. var promise = null;
  61369. var config_1 = {};
  61370. if (typeof DracoDecoderModule !== "undefined") {
  61371. promise = Promise.resolve();
  61372. }
  61373. else {
  61374. var decoder = DracoCompression.Configuration.decoder;
  61375. if (decoder) {
  61376. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61377. promise = Promise.all([
  61378. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61379. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61380. config_1.wasmBinary = data;
  61381. })
  61382. ]);
  61383. }
  61384. else if (decoder.fallbackUrl) {
  61385. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61386. }
  61387. }
  61388. }
  61389. if (!promise) {
  61390. throw new Error("Draco decoder module is not available");
  61391. }
  61392. DracoCompression._DecoderModulePromise = promise.then(function () {
  61393. return new Promise(function (resolve) {
  61394. config_1.onModuleLoaded = function (decoderModule) {
  61395. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61396. resolve({ module: decoderModule });
  61397. };
  61398. DracoDecoderModule(config_1);
  61399. });
  61400. });
  61401. }
  61402. return DracoCompression._DecoderModulePromise;
  61403. };
  61404. DracoCompression._LoadScriptAsync = function (url) {
  61405. return new Promise(function (resolve, reject) {
  61406. BABYLON.Tools.LoadScript(url, function () {
  61407. resolve();
  61408. }, function (message) {
  61409. reject(new Error(message));
  61410. });
  61411. });
  61412. };
  61413. DracoCompression._LoadFileAsync = function (url) {
  61414. return new Promise(function (resolve, reject) {
  61415. BABYLON.Tools.LoadFile(url, function (data) {
  61416. resolve(data);
  61417. }, undefined, undefined, true, function (request, exception) {
  61418. reject(exception);
  61419. });
  61420. });
  61421. };
  61422. /**
  61423. * The configuration.
  61424. */
  61425. DracoCompression.Configuration = {
  61426. decoder: {
  61427. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61428. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61429. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61430. }
  61431. };
  61432. return DracoCompression;
  61433. }());
  61434. BABYLON.DracoCompression = DracoCompression;
  61435. })(BABYLON || (BABYLON = {}));
  61436. //# sourceMappingURL=babylon.dracoCompression.js.map
  61437. var BABYLON;
  61438. (function (BABYLON) {
  61439. var AudioEngine = /** @class */ (function () {
  61440. function AudioEngine() {
  61441. this._audioContext = null;
  61442. this._audioContextInitialized = false;
  61443. this.canUseWebAudio = false;
  61444. this.WarnedWebAudioUnsupported = false;
  61445. this.unlocked = false;
  61446. this.isMP3supported = false;
  61447. this.isOGGsupported = false;
  61448. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61449. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61450. this.canUseWebAudio = true;
  61451. }
  61452. var audioElem = document.createElement('audio');
  61453. try {
  61454. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61455. this.isMP3supported = true;
  61456. }
  61457. }
  61458. catch (e) {
  61459. // protect error during capability check.
  61460. }
  61461. try {
  61462. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61463. this.isOGGsupported = true;
  61464. }
  61465. }
  61466. catch (e) {
  61467. // protect error during capability check.
  61468. }
  61469. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61470. this._unlockiOSaudio();
  61471. }
  61472. else {
  61473. this.unlocked = true;
  61474. }
  61475. }
  61476. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61477. get: function () {
  61478. if (!this._audioContextInitialized) {
  61479. this._initializeAudioContext();
  61480. }
  61481. return this._audioContext;
  61482. },
  61483. enumerable: true,
  61484. configurable: true
  61485. });
  61486. AudioEngine.prototype._unlockiOSaudio = function () {
  61487. var _this = this;
  61488. var unlockaudio = function () {
  61489. if (!_this.audioContext) {
  61490. return;
  61491. }
  61492. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61493. var source = _this.audioContext.createBufferSource();
  61494. source.buffer = buffer;
  61495. source.connect(_this.audioContext.destination);
  61496. source.start(0);
  61497. setTimeout(function () {
  61498. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61499. _this.unlocked = true;
  61500. window.removeEventListener('touchend', unlockaudio, false);
  61501. if (_this.onAudioUnlocked) {
  61502. _this.onAudioUnlocked();
  61503. }
  61504. }
  61505. }, 0);
  61506. };
  61507. window.addEventListener('touchend', unlockaudio, false);
  61508. };
  61509. AudioEngine.prototype._initializeAudioContext = function () {
  61510. try {
  61511. if (this.canUseWebAudio) {
  61512. this._audioContext = new AudioContext();
  61513. // create a global volume gain node
  61514. this.masterGain = this._audioContext.createGain();
  61515. this.masterGain.gain.value = 1;
  61516. this.masterGain.connect(this._audioContext.destination);
  61517. this._audioContextInitialized = true;
  61518. }
  61519. }
  61520. catch (e) {
  61521. this.canUseWebAudio = false;
  61522. BABYLON.Tools.Error("Web Audio: " + e.message);
  61523. }
  61524. };
  61525. AudioEngine.prototype.dispose = function () {
  61526. if (this.canUseWebAudio && this._audioContextInitialized) {
  61527. if (this._connectedAnalyser && this._audioContext) {
  61528. this._connectedAnalyser.stopDebugCanvas();
  61529. this._connectedAnalyser.dispose();
  61530. this.masterGain.disconnect();
  61531. this.masterGain.connect(this._audioContext.destination);
  61532. this._connectedAnalyser = null;
  61533. }
  61534. this.masterGain.gain.value = 1;
  61535. }
  61536. this.WarnedWebAudioUnsupported = false;
  61537. };
  61538. AudioEngine.prototype.getGlobalVolume = function () {
  61539. if (this.canUseWebAudio && this._audioContextInitialized) {
  61540. return this.masterGain.gain.value;
  61541. }
  61542. else {
  61543. return -1;
  61544. }
  61545. };
  61546. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61547. if (this.canUseWebAudio && this._audioContextInitialized) {
  61548. this.masterGain.gain.value = newVolume;
  61549. }
  61550. };
  61551. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61552. if (this._connectedAnalyser) {
  61553. this._connectedAnalyser.stopDebugCanvas();
  61554. }
  61555. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61556. this._connectedAnalyser = analyser;
  61557. this.masterGain.disconnect();
  61558. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61559. }
  61560. };
  61561. return AudioEngine;
  61562. }());
  61563. BABYLON.AudioEngine = AudioEngine;
  61564. })(BABYLON || (BABYLON = {}));
  61565. //# sourceMappingURL=babylon.audioEngine.js.map
  61566. var BABYLON;
  61567. (function (BABYLON) {
  61568. var Sound = /** @class */ (function () {
  61569. /**
  61570. * Create a sound and attach it to a scene
  61571. * @param name Name of your sound
  61572. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61573. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61574. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61575. */
  61576. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61577. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61578. var _this = this;
  61579. this.autoplay = false;
  61580. this.loop = false;
  61581. this.useCustomAttenuation = false;
  61582. this.spatialSound = false;
  61583. this.refDistance = 1;
  61584. this.rolloffFactor = 1;
  61585. this.maxDistance = 100;
  61586. this.distanceModel = "linear";
  61587. this._panningModel = "equalpower";
  61588. this._playbackRate = 1;
  61589. this._streaming = false;
  61590. this._startTime = 0;
  61591. this._startOffset = 0;
  61592. this._position = BABYLON.Vector3.Zero();
  61593. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61594. this._volume = 1;
  61595. this._isReadyToPlay = false;
  61596. this.isPlaying = false;
  61597. this.isPaused = false;
  61598. this._isDirectional = false;
  61599. // Used if you'd like to create a directional sound.
  61600. // If not set, the sound will be omnidirectional
  61601. this._coneInnerAngle = 360;
  61602. this._coneOuterAngle = 360;
  61603. this._coneOuterGain = 0;
  61604. this._isOutputConnected = false;
  61605. this._urlType = "Unknown";
  61606. this.name = name;
  61607. this._scene = scene;
  61608. this._readyToPlayCallback = readyToPlayCallback;
  61609. // Default custom attenuation function is a linear attenuation
  61610. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61611. if (currentDistance < maxDistance) {
  61612. return currentVolume * (1 - currentDistance / maxDistance);
  61613. }
  61614. else {
  61615. return 0;
  61616. }
  61617. };
  61618. if (options) {
  61619. this.autoplay = options.autoplay || false;
  61620. this.loop = options.loop || false;
  61621. // if volume === 0, we need another way to check this option
  61622. if (options.volume !== undefined) {
  61623. this._volume = options.volume;
  61624. }
  61625. this.spatialSound = options.spatialSound || false;
  61626. this.maxDistance = options.maxDistance || 100;
  61627. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61628. this.rolloffFactor = options.rolloffFactor || 1;
  61629. this.refDistance = options.refDistance || 1;
  61630. this.distanceModel = options.distanceModel || "linear";
  61631. this._playbackRate = options.playbackRate || 1;
  61632. this._streaming = options.streaming || false;
  61633. }
  61634. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61635. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61636. this._soundGain.gain.value = this._volume;
  61637. this._inputAudioNode = this._soundGain;
  61638. this._ouputAudioNode = this._soundGain;
  61639. if (this.spatialSound) {
  61640. this._createSpatialParameters();
  61641. }
  61642. this._scene.mainSoundTrack.AddSound(this);
  61643. var validParameter = true;
  61644. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61645. if (urlOrArrayBuffer) {
  61646. try {
  61647. if (typeof (urlOrArrayBuffer) === "string")
  61648. this._urlType = "String";
  61649. if (Array.isArray(urlOrArrayBuffer))
  61650. this._urlType = "Array";
  61651. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61652. this._urlType = "ArrayBuffer";
  61653. var urls = [];
  61654. var codecSupportedFound = false;
  61655. switch (this._urlType) {
  61656. case "ArrayBuffer":
  61657. if (urlOrArrayBuffer.byteLength > 0) {
  61658. codecSupportedFound = true;
  61659. this._soundLoaded(urlOrArrayBuffer);
  61660. }
  61661. break;
  61662. case "String":
  61663. urls.push(urlOrArrayBuffer);
  61664. case "Array":
  61665. if (urls.length === 0)
  61666. urls = urlOrArrayBuffer;
  61667. // If we found a supported format, we load it immediately and stop the loop
  61668. for (var i = 0; i < urls.length; i++) {
  61669. var url = urls[i];
  61670. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61671. codecSupportedFound = true;
  61672. }
  61673. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61674. codecSupportedFound = true;
  61675. }
  61676. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61677. codecSupportedFound = true;
  61678. }
  61679. if (url.indexOf("blob:") !== -1) {
  61680. codecSupportedFound = true;
  61681. }
  61682. if (codecSupportedFound) {
  61683. // Loading sound using XHR2
  61684. if (!this._streaming) {
  61685. this._scene._loadFile(url, function (data) {
  61686. _this._soundLoaded(data);
  61687. }, undefined, true, true, function (exception) {
  61688. if (exception) {
  61689. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61690. }
  61691. BABYLON.Tools.Error("Sound creation aborted.");
  61692. _this._scene.mainSoundTrack.RemoveSound(_this);
  61693. });
  61694. }
  61695. // Streaming sound using HTML5 Audio tag
  61696. else {
  61697. this._htmlAudioElement = new Audio(url);
  61698. this._htmlAudioElement.controls = false;
  61699. this._htmlAudioElement.loop = this.loop;
  61700. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61701. this._htmlAudioElement.preload = "auto";
  61702. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61703. _this._isReadyToPlay = true;
  61704. if (_this.autoplay) {
  61705. _this.play();
  61706. }
  61707. if (_this._readyToPlayCallback) {
  61708. _this._readyToPlayCallback();
  61709. }
  61710. });
  61711. document.body.appendChild(this._htmlAudioElement);
  61712. }
  61713. break;
  61714. }
  61715. }
  61716. break;
  61717. default:
  61718. validParameter = false;
  61719. break;
  61720. }
  61721. if (!validParameter) {
  61722. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61723. }
  61724. else {
  61725. if (!codecSupportedFound) {
  61726. this._isReadyToPlay = true;
  61727. // Simulating a ready to play event to avoid breaking code path
  61728. if (this._readyToPlayCallback) {
  61729. window.setTimeout(function () {
  61730. if (_this._readyToPlayCallback) {
  61731. _this._readyToPlayCallback();
  61732. }
  61733. }, 1000);
  61734. }
  61735. }
  61736. }
  61737. }
  61738. catch (ex) {
  61739. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61740. this._scene.mainSoundTrack.RemoveSound(this);
  61741. }
  61742. }
  61743. }
  61744. else {
  61745. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61746. this._scene.mainSoundTrack.AddSound(this);
  61747. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61748. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61749. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61750. }
  61751. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61752. if (this._readyToPlayCallback) {
  61753. window.setTimeout(function () {
  61754. if (_this._readyToPlayCallback) {
  61755. _this._readyToPlayCallback();
  61756. }
  61757. }, 1000);
  61758. }
  61759. }
  61760. }
  61761. Sound.prototype.dispose = function () {
  61762. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61763. if (this.isPlaying) {
  61764. this.stop();
  61765. }
  61766. this._isReadyToPlay = false;
  61767. if (this.soundTrackId === -1) {
  61768. this._scene.mainSoundTrack.RemoveSound(this);
  61769. }
  61770. else {
  61771. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61772. }
  61773. if (this._soundGain) {
  61774. this._soundGain.disconnect();
  61775. this._soundGain = null;
  61776. }
  61777. if (this._soundPanner) {
  61778. this._soundPanner.disconnect();
  61779. this._soundPanner = null;
  61780. }
  61781. if (this._soundSource) {
  61782. this._soundSource.disconnect();
  61783. this._soundSource = null;
  61784. }
  61785. this._audioBuffer = null;
  61786. if (this._htmlAudioElement) {
  61787. this._htmlAudioElement.pause();
  61788. this._htmlAudioElement.src = "";
  61789. document.body.removeChild(this._htmlAudioElement);
  61790. }
  61791. if (this._connectedMesh && this._registerFunc) {
  61792. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61793. this._connectedMesh = null;
  61794. }
  61795. }
  61796. };
  61797. Sound.prototype.isReady = function () {
  61798. return this._isReadyToPlay;
  61799. };
  61800. Sound.prototype._soundLoaded = function (audioData) {
  61801. var _this = this;
  61802. if (!BABYLON.Engine.audioEngine.audioContext) {
  61803. return;
  61804. }
  61805. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61806. _this._audioBuffer = buffer;
  61807. _this._isReadyToPlay = true;
  61808. if (_this.autoplay) {
  61809. _this.play();
  61810. }
  61811. if (_this._readyToPlayCallback) {
  61812. _this._readyToPlayCallback();
  61813. }
  61814. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61815. };
  61816. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61817. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61818. this._audioBuffer = audioBuffer;
  61819. this._isReadyToPlay = true;
  61820. }
  61821. };
  61822. Sound.prototype.updateOptions = function (options) {
  61823. if (options) {
  61824. this.loop = options.loop || this.loop;
  61825. this.maxDistance = options.maxDistance || this.maxDistance;
  61826. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61827. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61828. this.refDistance = options.refDistance || this.refDistance;
  61829. this.distanceModel = options.distanceModel || this.distanceModel;
  61830. this._playbackRate = options.playbackRate || this._playbackRate;
  61831. this._updateSpatialParameters();
  61832. if (this.isPlaying) {
  61833. if (this._streaming) {
  61834. this._htmlAudioElement.playbackRate = this._playbackRate;
  61835. }
  61836. else {
  61837. if (this._soundSource) {
  61838. this._soundSource.playbackRate.value = this._playbackRate;
  61839. }
  61840. }
  61841. }
  61842. }
  61843. };
  61844. Sound.prototype._createSpatialParameters = function () {
  61845. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61846. if (this._scene.headphone) {
  61847. this._panningModel = "HRTF";
  61848. }
  61849. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61850. this._updateSpatialParameters();
  61851. this._soundPanner.connect(this._ouputAudioNode);
  61852. this._inputAudioNode = this._soundPanner;
  61853. }
  61854. };
  61855. Sound.prototype._updateSpatialParameters = function () {
  61856. if (this.spatialSound && this._soundPanner) {
  61857. if (this.useCustomAttenuation) {
  61858. // Tricks to disable in a way embedded Web Audio attenuation
  61859. this._soundPanner.distanceModel = "linear";
  61860. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61861. this._soundPanner.refDistance = 1;
  61862. this._soundPanner.rolloffFactor = 1;
  61863. this._soundPanner.panningModel = this._panningModel;
  61864. }
  61865. else {
  61866. this._soundPanner.distanceModel = this.distanceModel;
  61867. this._soundPanner.maxDistance = this.maxDistance;
  61868. this._soundPanner.refDistance = this.refDistance;
  61869. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61870. this._soundPanner.panningModel = this._panningModel;
  61871. }
  61872. }
  61873. };
  61874. Sound.prototype.switchPanningModelToHRTF = function () {
  61875. this._panningModel = "HRTF";
  61876. this._switchPanningModel();
  61877. };
  61878. Sound.prototype.switchPanningModelToEqualPower = function () {
  61879. this._panningModel = "equalpower";
  61880. this._switchPanningModel();
  61881. };
  61882. Sound.prototype._switchPanningModel = function () {
  61883. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61884. this._soundPanner.panningModel = this._panningModel;
  61885. }
  61886. };
  61887. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61888. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61889. if (this._isOutputConnected) {
  61890. this._ouputAudioNode.disconnect();
  61891. }
  61892. this._ouputAudioNode.connect(soundTrackAudioNode);
  61893. this._isOutputConnected = true;
  61894. }
  61895. };
  61896. /**
  61897. * Transform this sound into a directional source
  61898. * @param coneInnerAngle Size of the inner cone in degree
  61899. * @param coneOuterAngle Size of the outer cone in degree
  61900. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61901. */
  61902. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61903. if (coneOuterAngle < coneInnerAngle) {
  61904. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61905. return;
  61906. }
  61907. this._coneInnerAngle = coneInnerAngle;
  61908. this._coneOuterAngle = coneOuterAngle;
  61909. this._coneOuterGain = coneOuterGain;
  61910. this._isDirectional = true;
  61911. if (this.isPlaying && this.loop) {
  61912. this.stop();
  61913. this.play();
  61914. }
  61915. };
  61916. Sound.prototype.setPosition = function (newPosition) {
  61917. this._position = newPosition;
  61918. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61919. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61920. }
  61921. };
  61922. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61923. this._localDirection = newLocalDirection;
  61924. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61925. this._updateDirection();
  61926. }
  61927. };
  61928. Sound.prototype._updateDirection = function () {
  61929. if (!this._connectedMesh || !this._soundPanner) {
  61930. return;
  61931. }
  61932. var mat = this._connectedMesh.getWorldMatrix();
  61933. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61934. direction.normalize();
  61935. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61936. };
  61937. Sound.prototype.updateDistanceFromListener = function () {
  61938. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61939. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61940. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61941. }
  61942. };
  61943. Sound.prototype.setAttenuationFunction = function (callback) {
  61944. this._customAttenuationFunction = callback;
  61945. };
  61946. /**
  61947. * Play the sound
  61948. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61949. * @param offset (optional) Start the sound setting it at a specific time
  61950. */
  61951. Sound.prototype.play = function (time, offset) {
  61952. var _this = this;
  61953. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61954. try {
  61955. if (this._startOffset < 0) {
  61956. time = -this._startOffset;
  61957. this._startOffset = 0;
  61958. }
  61959. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61960. if (!this._soundSource || !this._streamingSource) {
  61961. if (this.spatialSound && this._soundPanner) {
  61962. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61963. if (this._isDirectional) {
  61964. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61965. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61966. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61967. if (this._connectedMesh) {
  61968. this._updateDirection();
  61969. }
  61970. else {
  61971. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61972. }
  61973. }
  61974. }
  61975. }
  61976. if (this._streaming) {
  61977. if (!this._streamingSource) {
  61978. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61979. this._htmlAudioElement.onended = function () { _this._onended(); };
  61980. this._htmlAudioElement.playbackRate = this._playbackRate;
  61981. }
  61982. this._streamingSource.disconnect();
  61983. this._streamingSource.connect(this._inputAudioNode);
  61984. this._htmlAudioElement.play();
  61985. }
  61986. else {
  61987. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61988. this._soundSource.buffer = this._audioBuffer;
  61989. this._soundSource.connect(this._inputAudioNode);
  61990. this._soundSource.loop = this.loop;
  61991. this._soundSource.playbackRate.value = this._playbackRate;
  61992. this._soundSource.onended = function () { _this._onended(); };
  61993. if (this._soundSource.buffer) {
  61994. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61995. }
  61996. }
  61997. this._startTime = startTime;
  61998. this.isPlaying = true;
  61999. this.isPaused = false;
  62000. }
  62001. catch (ex) {
  62002. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62003. }
  62004. }
  62005. };
  62006. Sound.prototype._onended = function () {
  62007. this.isPlaying = false;
  62008. if (this.onended) {
  62009. this.onended();
  62010. }
  62011. };
  62012. /**
  62013. * Stop the sound
  62014. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62015. */
  62016. Sound.prototype.stop = function (time) {
  62017. if (this.isPlaying) {
  62018. if (this._streaming) {
  62019. this._htmlAudioElement.pause();
  62020. // Test needed for Firefox or it will generate an Invalid State Error
  62021. if (this._htmlAudioElement.currentTime > 0) {
  62022. this._htmlAudioElement.currentTime = 0;
  62023. }
  62024. }
  62025. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62026. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62027. this._soundSource.stop(stopTime);
  62028. this._soundSource.onended = function () { };
  62029. if (!this.isPaused) {
  62030. this._startOffset = 0;
  62031. }
  62032. }
  62033. this.isPlaying = false;
  62034. }
  62035. };
  62036. Sound.prototype.pause = function () {
  62037. if (this.isPlaying) {
  62038. this.isPaused = true;
  62039. if (this._streaming) {
  62040. this._htmlAudioElement.pause();
  62041. }
  62042. else if (BABYLON.Engine.audioEngine.audioContext) {
  62043. this.stop(0);
  62044. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62045. }
  62046. }
  62047. };
  62048. Sound.prototype.setVolume = function (newVolume, time) {
  62049. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62050. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62051. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62052. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62053. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62054. }
  62055. else {
  62056. this._soundGain.gain.value = newVolume;
  62057. }
  62058. }
  62059. this._volume = newVolume;
  62060. };
  62061. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62062. this._playbackRate = newPlaybackRate;
  62063. if (this.isPlaying) {
  62064. if (this._streaming) {
  62065. this._htmlAudioElement.playbackRate = this._playbackRate;
  62066. }
  62067. else if (this._soundSource) {
  62068. this._soundSource.playbackRate.value = this._playbackRate;
  62069. }
  62070. }
  62071. };
  62072. Sound.prototype.getVolume = function () {
  62073. return this._volume;
  62074. };
  62075. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62076. var _this = this;
  62077. if (this._connectedMesh && this._registerFunc) {
  62078. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62079. this._registerFunc = null;
  62080. }
  62081. this._connectedMesh = meshToConnectTo;
  62082. if (!this.spatialSound) {
  62083. this.spatialSound = true;
  62084. this._createSpatialParameters();
  62085. if (this.isPlaying && this.loop) {
  62086. this.stop();
  62087. this.play();
  62088. }
  62089. }
  62090. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62091. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62092. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62093. };
  62094. Sound.prototype.detachFromMesh = function () {
  62095. if (this._connectedMesh && this._registerFunc) {
  62096. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62097. this._registerFunc = null;
  62098. this._connectedMesh = null;
  62099. }
  62100. };
  62101. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62102. if (!node.getBoundingInfo) {
  62103. return;
  62104. }
  62105. var mesh = node;
  62106. var boundingInfo = mesh.getBoundingInfo();
  62107. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62108. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62109. this._updateDirection();
  62110. }
  62111. };
  62112. Sound.prototype.clone = function () {
  62113. var _this = this;
  62114. if (!this._streaming) {
  62115. var setBufferAndRun = function () {
  62116. if (_this._isReadyToPlay) {
  62117. clonedSound._audioBuffer = _this.getAudioBuffer();
  62118. clonedSound._isReadyToPlay = true;
  62119. if (clonedSound.autoplay) {
  62120. clonedSound.play();
  62121. }
  62122. }
  62123. else {
  62124. window.setTimeout(setBufferAndRun, 300);
  62125. }
  62126. };
  62127. var currentOptions = {
  62128. autoplay: this.autoplay, loop: this.loop,
  62129. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62130. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62131. refDistance: this.refDistance, distanceModel: this.distanceModel
  62132. };
  62133. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62134. if (this.useCustomAttenuation) {
  62135. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62136. }
  62137. clonedSound.setPosition(this._position);
  62138. clonedSound.setPlaybackRate(this._playbackRate);
  62139. setBufferAndRun();
  62140. return clonedSound;
  62141. }
  62142. // Can't clone a streaming sound
  62143. else {
  62144. return null;
  62145. }
  62146. };
  62147. Sound.prototype.getAudioBuffer = function () {
  62148. return this._audioBuffer;
  62149. };
  62150. Sound.prototype.serialize = function () {
  62151. var serializationObject = {
  62152. name: this.name,
  62153. url: this.name,
  62154. autoplay: this.autoplay,
  62155. loop: this.loop,
  62156. volume: this._volume,
  62157. spatialSound: this.spatialSound,
  62158. maxDistance: this.maxDistance,
  62159. rolloffFactor: this.rolloffFactor,
  62160. refDistance: this.refDistance,
  62161. distanceModel: this.distanceModel,
  62162. playbackRate: this._playbackRate,
  62163. panningModel: this._panningModel,
  62164. soundTrackId: this.soundTrackId
  62165. };
  62166. if (this.spatialSound) {
  62167. if (this._connectedMesh)
  62168. serializationObject.connectedMeshId = this._connectedMesh.id;
  62169. serializationObject.position = this._position.asArray();
  62170. serializationObject.refDistance = this.refDistance;
  62171. serializationObject.distanceModel = this.distanceModel;
  62172. serializationObject.isDirectional = this._isDirectional;
  62173. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62174. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62175. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62176. serializationObject.coneOuterGain = this._coneOuterGain;
  62177. }
  62178. return serializationObject;
  62179. };
  62180. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62181. var soundName = parsedSound.name;
  62182. var soundUrl;
  62183. if (parsedSound.url) {
  62184. soundUrl = rootUrl + parsedSound.url;
  62185. }
  62186. else {
  62187. soundUrl = rootUrl + soundName;
  62188. }
  62189. var options = {
  62190. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62191. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62192. rolloffFactor: parsedSound.rolloffFactor,
  62193. refDistance: parsedSound.refDistance,
  62194. distanceModel: parsedSound.distanceModel,
  62195. playbackRate: parsedSound.playbackRate
  62196. };
  62197. var newSound;
  62198. if (!sourceSound) {
  62199. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62200. scene._addPendingData(newSound);
  62201. }
  62202. else {
  62203. var setBufferAndRun = function () {
  62204. if (sourceSound._isReadyToPlay) {
  62205. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62206. newSound._isReadyToPlay = true;
  62207. if (newSound.autoplay) {
  62208. newSound.play();
  62209. }
  62210. }
  62211. else {
  62212. window.setTimeout(setBufferAndRun, 300);
  62213. }
  62214. };
  62215. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62216. setBufferAndRun();
  62217. }
  62218. if (parsedSound.position) {
  62219. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62220. newSound.setPosition(soundPosition);
  62221. }
  62222. if (parsedSound.isDirectional) {
  62223. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62224. if (parsedSound.localDirectionToMesh) {
  62225. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62226. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62227. }
  62228. }
  62229. if (parsedSound.connectedMeshId) {
  62230. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62231. if (connectedMesh) {
  62232. newSound.attachToMesh(connectedMesh);
  62233. }
  62234. }
  62235. return newSound;
  62236. };
  62237. return Sound;
  62238. }());
  62239. BABYLON.Sound = Sound;
  62240. })(BABYLON || (BABYLON = {}));
  62241. //# sourceMappingURL=babylon.sound.js.map
  62242. var BABYLON;
  62243. (function (BABYLON) {
  62244. var SoundTrack = /** @class */ (function () {
  62245. function SoundTrack(scene, options) {
  62246. this.id = -1;
  62247. this._isMainTrack = false;
  62248. this._isInitialized = false;
  62249. this._scene = scene;
  62250. this.soundCollection = new Array();
  62251. this._options = options;
  62252. if (!this._isMainTrack) {
  62253. this._scene.soundTracks.push(this);
  62254. this.id = this._scene.soundTracks.length - 1;
  62255. }
  62256. }
  62257. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62258. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62259. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62260. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62261. if (this._options) {
  62262. if (this._options.volume) {
  62263. this._outputAudioNode.gain.value = this._options.volume;
  62264. }
  62265. if (this._options.mainTrack) {
  62266. this._isMainTrack = this._options.mainTrack;
  62267. }
  62268. }
  62269. this._isInitialized = true;
  62270. }
  62271. };
  62272. SoundTrack.prototype.dispose = function () {
  62273. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62274. if (this._connectedAnalyser) {
  62275. this._connectedAnalyser.stopDebugCanvas();
  62276. }
  62277. while (this.soundCollection.length) {
  62278. this.soundCollection[0].dispose();
  62279. }
  62280. if (this._outputAudioNode) {
  62281. this._outputAudioNode.disconnect();
  62282. }
  62283. this._outputAudioNode = null;
  62284. }
  62285. };
  62286. SoundTrack.prototype.AddSound = function (sound) {
  62287. if (!this._isInitialized) {
  62288. this._initializeSoundTrackAudioGraph();
  62289. }
  62290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62291. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62292. }
  62293. if (sound.soundTrackId) {
  62294. if (sound.soundTrackId === -1) {
  62295. this._scene.mainSoundTrack.RemoveSound(sound);
  62296. }
  62297. else {
  62298. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62299. }
  62300. }
  62301. this.soundCollection.push(sound);
  62302. sound.soundTrackId = this.id;
  62303. };
  62304. SoundTrack.prototype.RemoveSound = function (sound) {
  62305. var index = this.soundCollection.indexOf(sound);
  62306. if (index !== -1) {
  62307. this.soundCollection.splice(index, 1);
  62308. }
  62309. };
  62310. SoundTrack.prototype.setVolume = function (newVolume) {
  62311. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62312. this._outputAudioNode.gain.value = newVolume;
  62313. }
  62314. };
  62315. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62316. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62317. for (var i = 0; i < this.soundCollection.length; i++) {
  62318. this.soundCollection[i].switchPanningModelToHRTF();
  62319. }
  62320. }
  62321. };
  62322. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62323. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62324. for (var i = 0; i < this.soundCollection.length; i++) {
  62325. this.soundCollection[i].switchPanningModelToEqualPower();
  62326. }
  62327. }
  62328. };
  62329. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62330. if (this._connectedAnalyser) {
  62331. this._connectedAnalyser.stopDebugCanvas();
  62332. }
  62333. this._connectedAnalyser = analyser;
  62334. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62335. this._outputAudioNode.disconnect();
  62336. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62337. }
  62338. };
  62339. return SoundTrack;
  62340. }());
  62341. BABYLON.SoundTrack = SoundTrack;
  62342. })(BABYLON || (BABYLON = {}));
  62343. //# sourceMappingURL=babylon.soundtrack.js.map
  62344. var BABYLON;
  62345. (function (BABYLON) {
  62346. var Analyser = /** @class */ (function () {
  62347. function Analyser(scene) {
  62348. this.SMOOTHING = 0.75;
  62349. this.FFT_SIZE = 512;
  62350. this.BARGRAPHAMPLITUDE = 256;
  62351. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62352. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62353. this._scene = scene;
  62354. this._audioEngine = BABYLON.Engine.audioEngine;
  62355. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62356. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62357. this._webAudioAnalyser.minDecibels = -140;
  62358. this._webAudioAnalyser.maxDecibels = 0;
  62359. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62360. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62361. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62362. }
  62363. }
  62364. Analyser.prototype.getFrequencyBinCount = function () {
  62365. if (this._audioEngine.canUseWebAudio) {
  62366. return this._webAudioAnalyser.frequencyBinCount;
  62367. }
  62368. else {
  62369. return 0;
  62370. }
  62371. };
  62372. Analyser.prototype.getByteFrequencyData = function () {
  62373. if (this._audioEngine.canUseWebAudio) {
  62374. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62375. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62376. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62377. }
  62378. return this._byteFreqs;
  62379. };
  62380. Analyser.prototype.getByteTimeDomainData = function () {
  62381. if (this._audioEngine.canUseWebAudio) {
  62382. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62383. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62384. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62385. }
  62386. return this._byteTime;
  62387. };
  62388. Analyser.prototype.getFloatFrequencyData = function () {
  62389. if (this._audioEngine.canUseWebAudio) {
  62390. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62391. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62392. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62393. }
  62394. return this._floatFreqs;
  62395. };
  62396. Analyser.prototype.drawDebugCanvas = function () {
  62397. var _this = this;
  62398. if (this._audioEngine.canUseWebAudio) {
  62399. if (!this._debugCanvas) {
  62400. this._debugCanvas = document.createElement("canvas");
  62401. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62402. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62403. this._debugCanvas.style.position = "absolute";
  62404. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62405. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62406. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62407. document.body.appendChild(this._debugCanvas);
  62408. this._registerFunc = function () {
  62409. _this.drawDebugCanvas();
  62410. };
  62411. this._scene.registerBeforeRender(this._registerFunc);
  62412. }
  62413. if (this._registerFunc && this._debugCanvasContext) {
  62414. var workingArray = this.getByteFrequencyData();
  62415. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62416. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62417. // Draw the frequency domain chart.
  62418. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62419. var value = workingArray[i];
  62420. var percent = value / this.BARGRAPHAMPLITUDE;
  62421. var height = this.DEBUGCANVASSIZE.height * percent;
  62422. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62423. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62424. var hue = i / this.getFrequencyBinCount() * 360;
  62425. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62426. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62427. }
  62428. }
  62429. }
  62430. };
  62431. Analyser.prototype.stopDebugCanvas = function () {
  62432. if (this._debugCanvas) {
  62433. if (this._registerFunc) {
  62434. this._scene.unregisterBeforeRender(this._registerFunc);
  62435. this._registerFunc = null;
  62436. }
  62437. document.body.removeChild(this._debugCanvas);
  62438. this._debugCanvas = null;
  62439. this._debugCanvasContext = null;
  62440. }
  62441. };
  62442. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62443. if (this._audioEngine.canUseWebAudio) {
  62444. inputAudioNode.connect(this._webAudioAnalyser);
  62445. this._webAudioAnalyser.connect(outputAudioNode);
  62446. }
  62447. };
  62448. Analyser.prototype.dispose = function () {
  62449. if (this._audioEngine.canUseWebAudio) {
  62450. this._webAudioAnalyser.disconnect();
  62451. }
  62452. };
  62453. return Analyser;
  62454. }());
  62455. BABYLON.Analyser = Analyser;
  62456. })(BABYLON || (BABYLON = {}));
  62457. //# sourceMappingURL=babylon.analyser.js.map
  62458. var BABYLON;
  62459. (function (BABYLON) {
  62460. var CubeTexture = /** @class */ (function (_super) {
  62461. __extends(CubeTexture, _super);
  62462. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62463. if (extensions === void 0) { extensions = null; }
  62464. if (noMipmap === void 0) { noMipmap = false; }
  62465. if (files === void 0) { files = null; }
  62466. if (onLoad === void 0) { onLoad = null; }
  62467. if (onError === void 0) { onError = null; }
  62468. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62469. if (prefiltered === void 0) { prefiltered = false; }
  62470. if (forcedExtension === void 0) { forcedExtension = null; }
  62471. var _this = _super.call(this, scene) || this;
  62472. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62473. /**
  62474. * Gets or sets the center of the bounding box associated with the cube texture
  62475. * It must define where the camera used to render the texture was set
  62476. */
  62477. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62478. _this._rotationY = 0;
  62479. _this.name = rootUrl;
  62480. _this.url = rootUrl;
  62481. _this._noMipmap = noMipmap;
  62482. _this.hasAlpha = false;
  62483. _this._format = format;
  62484. _this._prefiltered = prefiltered;
  62485. _this.isCube = true;
  62486. _this._textureMatrix = BABYLON.Matrix.Identity();
  62487. if (prefiltered) {
  62488. _this.gammaSpace = false;
  62489. }
  62490. if (!rootUrl && !files) {
  62491. return _this;
  62492. }
  62493. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62494. var lastDot = rootUrl.lastIndexOf(".");
  62495. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62496. var isDDS = (extension === ".dds");
  62497. if (!files) {
  62498. if (!isDDS && !extensions) {
  62499. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62500. }
  62501. files = [];
  62502. if (extensions) {
  62503. for (var index = 0; index < extensions.length; index++) {
  62504. files.push(rootUrl + extensions[index]);
  62505. }
  62506. }
  62507. }
  62508. _this._files = files;
  62509. if (!_this._texture) {
  62510. if (!scene.useDelayedTextureLoading) {
  62511. if (prefiltered) {
  62512. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62513. }
  62514. else {
  62515. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62516. }
  62517. }
  62518. else {
  62519. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62520. }
  62521. }
  62522. else if (onLoad) {
  62523. if (_this._texture.isReady) {
  62524. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62525. }
  62526. else {
  62527. _this._texture.onLoadedObservable.add(onLoad);
  62528. }
  62529. }
  62530. return _this;
  62531. }
  62532. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62533. get: function () {
  62534. return this._boundingBoxSize;
  62535. },
  62536. /**
  62537. * Gets or sets the size of the bounding box associated with the cube texture
  62538. * When defined, the cubemap will switch to local mode
  62539. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62540. * @example https://www.babylonjs-playground.com/#RNASML
  62541. */
  62542. set: function (value) {
  62543. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62544. return;
  62545. }
  62546. this._boundingBoxSize = value;
  62547. var scene = this.getScene();
  62548. if (scene) {
  62549. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62550. }
  62551. },
  62552. enumerable: true,
  62553. configurable: true
  62554. });
  62555. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62556. /**
  62557. * Gets texture matrix rotation angle around Y axis radians.
  62558. */
  62559. get: function () {
  62560. return this._rotationY;
  62561. },
  62562. /**
  62563. * Sets texture matrix rotation angle around Y axis in radians.
  62564. */
  62565. set: function (value) {
  62566. this._rotationY = value;
  62567. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62568. },
  62569. enumerable: true,
  62570. configurable: true
  62571. });
  62572. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62573. var rootUrlKey = "";
  62574. files.forEach(function (url) { return rootUrlKey += url; });
  62575. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62576. };
  62577. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62578. if (forcedExtension === void 0) { forcedExtension = null; }
  62579. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62580. };
  62581. // Methods
  62582. CubeTexture.prototype.delayLoad = function () {
  62583. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62584. return;
  62585. }
  62586. var scene = this.getScene();
  62587. if (!scene) {
  62588. return;
  62589. }
  62590. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62591. this._texture = this._getFromCache(this.url, this._noMipmap);
  62592. if (!this._texture) {
  62593. if (this._prefiltered) {
  62594. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  62595. }
  62596. else {
  62597. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62598. }
  62599. }
  62600. };
  62601. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62602. return this._textureMatrix;
  62603. };
  62604. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62605. this._textureMatrix = value;
  62606. };
  62607. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62608. var texture = BABYLON.SerializationHelper.Parse(function () {
  62609. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  62610. }, parsedTexture, scene);
  62611. // Local Cubemaps
  62612. if (parsedTexture.boundingBoxPosition) {
  62613. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62614. }
  62615. if (parsedTexture.boundingBoxSize) {
  62616. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62617. }
  62618. // Animations
  62619. if (parsedTexture.animations) {
  62620. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62621. var parsedAnimation = parsedTexture.animations[animationIndex];
  62622. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62623. }
  62624. }
  62625. return texture;
  62626. };
  62627. CubeTexture.prototype.clone = function () {
  62628. var _this = this;
  62629. return BABYLON.SerializationHelper.Clone(function () {
  62630. var scene = _this.getScene();
  62631. if (!scene) {
  62632. return _this;
  62633. }
  62634. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62635. }, this);
  62636. };
  62637. __decorate([
  62638. BABYLON.serialize("rotationY")
  62639. ], CubeTexture.prototype, "_rotationY", void 0);
  62640. return CubeTexture;
  62641. }(BABYLON.BaseTexture));
  62642. BABYLON.CubeTexture = CubeTexture;
  62643. })(BABYLON || (BABYLON = {}));
  62644. //# sourceMappingURL=babylon.cubeTexture.js.map
  62645. var BABYLON;
  62646. (function (BABYLON) {
  62647. var RenderTargetTexture = /** @class */ (function (_super) {
  62648. __extends(RenderTargetTexture, _super);
  62649. /**
  62650. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62651. * or used a shadow, depth texture...
  62652. * @param name The friendly name of the texture
  62653. * @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)
  62654. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62655. * @param generateMipMaps True if mip maps need to be generated after render.
  62656. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62657. * @param type The type of the buffer in the RTT (int, half float, float...)
  62658. * @param isCube True if a cube texture needs to be created
  62659. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62660. * @param generateDepthBuffer True to generate a depth buffer
  62661. * @param generateStencilBuffer True to generate a stencil buffer
  62662. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62663. */
  62664. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62665. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62666. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62667. if (isCube === void 0) { isCube = false; }
  62668. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62669. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62670. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62671. if (isMulti === void 0) { isMulti = false; }
  62672. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62673. _this.isCube = isCube;
  62674. /**
  62675. * Use this list to define the list of mesh you want to render.
  62676. */
  62677. _this.renderList = new Array();
  62678. _this.renderParticles = true;
  62679. _this.renderSprites = false;
  62680. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62681. _this.ignoreCameraViewport = false;
  62682. // Events
  62683. /**
  62684. * An event triggered when the texture is unbind.
  62685. */
  62686. _this.onBeforeBindObservable = new BABYLON.Observable();
  62687. /**
  62688. * An event triggered when the texture is unbind.
  62689. */
  62690. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62691. /**
  62692. * An event triggered before rendering the texture
  62693. */
  62694. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62695. /**
  62696. * An event triggered after rendering the texture
  62697. */
  62698. _this.onAfterRenderObservable = new BABYLON.Observable();
  62699. /**
  62700. * An event triggered after the texture clear
  62701. */
  62702. _this.onClearObservable = new BABYLON.Observable();
  62703. _this._currentRefreshId = -1;
  62704. _this._refreshRate = 1;
  62705. _this._samples = 1;
  62706. /**
  62707. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62708. * It must define where the camera used to render the texture is set
  62709. */
  62710. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62711. scene = _this.getScene();
  62712. if (!scene) {
  62713. return _this;
  62714. }
  62715. _this._engine = scene.getEngine();
  62716. _this.name = name;
  62717. _this.isRenderTarget = true;
  62718. _this._initialSizeParameter = size;
  62719. _this._processSizeParameter(size);
  62720. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62721. });
  62722. _this._generateMipMaps = generateMipMaps ? true : false;
  62723. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62724. // Rendering groups
  62725. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62726. if (isMulti) {
  62727. return _this;
  62728. }
  62729. _this._renderTargetOptions = {
  62730. generateMipMaps: generateMipMaps,
  62731. type: type,
  62732. samplingMode: samplingMode,
  62733. generateDepthBuffer: generateDepthBuffer,
  62734. generateStencilBuffer: generateStencilBuffer
  62735. };
  62736. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62737. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62738. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62739. }
  62740. if (isCube) {
  62741. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62742. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62743. _this._textureMatrix = BABYLON.Matrix.Identity();
  62744. }
  62745. else {
  62746. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62747. }
  62748. return _this;
  62749. }
  62750. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62751. get: function () {
  62752. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62753. },
  62754. enumerable: true,
  62755. configurable: true
  62756. });
  62757. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62758. get: function () {
  62759. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62760. },
  62761. enumerable: true,
  62762. configurable: true
  62763. });
  62764. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62765. get: function () {
  62766. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62767. },
  62768. enumerable: true,
  62769. configurable: true
  62770. });
  62771. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62772. set: function (callback) {
  62773. if (this._onAfterUnbindObserver) {
  62774. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62775. }
  62776. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62777. },
  62778. enumerable: true,
  62779. configurable: true
  62780. });
  62781. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62782. set: function (callback) {
  62783. if (this._onBeforeRenderObserver) {
  62784. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62785. }
  62786. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62787. },
  62788. enumerable: true,
  62789. configurable: true
  62790. });
  62791. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62792. set: function (callback) {
  62793. if (this._onAfterRenderObserver) {
  62794. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62795. }
  62796. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62797. },
  62798. enumerable: true,
  62799. configurable: true
  62800. });
  62801. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62802. set: function (callback) {
  62803. if (this._onClearObserver) {
  62804. this.onClearObservable.remove(this._onClearObserver);
  62805. }
  62806. this._onClearObserver = this.onClearObservable.add(callback);
  62807. },
  62808. enumerable: true,
  62809. configurable: true
  62810. });
  62811. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62812. get: function () {
  62813. return this._renderTargetOptions;
  62814. },
  62815. enumerable: true,
  62816. configurable: true
  62817. });
  62818. RenderTargetTexture.prototype._onRatioRescale = function () {
  62819. if (this._sizeRatio) {
  62820. this.resize(this._initialSizeParameter);
  62821. }
  62822. };
  62823. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62824. get: function () {
  62825. return this._boundingBoxSize;
  62826. },
  62827. /**
  62828. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62829. * When defined, the cubemap will switch to local mode
  62830. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62831. * @example https://www.babylonjs-playground.com/#RNASML
  62832. */
  62833. set: function (value) {
  62834. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62835. return;
  62836. }
  62837. this._boundingBoxSize = value;
  62838. var scene = this.getScene();
  62839. if (scene) {
  62840. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62841. }
  62842. },
  62843. enumerable: true,
  62844. configurable: true
  62845. });
  62846. /**
  62847. * Creates a depth stencil texture.
  62848. * This is only available in WebGL 2 or with the depth texture extension available.
  62849. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62850. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62851. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62852. */
  62853. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62854. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62855. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62856. if (generateStencil === void 0) { generateStencil = false; }
  62857. if (!this.getScene()) {
  62858. return;
  62859. }
  62860. var engine = this.getScene().getEngine();
  62861. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62862. bilinearFiltering: bilinearFiltering,
  62863. comparisonFunction: comparisonFunction,
  62864. generateStencil: generateStencil,
  62865. isCube: this.isCube
  62866. });
  62867. engine.setFrameBufferDepthStencilTexture(this);
  62868. };
  62869. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62870. if (size.ratio) {
  62871. this._sizeRatio = size.ratio;
  62872. this._size = {
  62873. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62874. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62875. };
  62876. }
  62877. else {
  62878. this._size = size;
  62879. }
  62880. };
  62881. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62882. get: function () {
  62883. return this._samples;
  62884. },
  62885. set: function (value) {
  62886. if (this._samples === value) {
  62887. return;
  62888. }
  62889. var scene = this.getScene();
  62890. if (!scene) {
  62891. return;
  62892. }
  62893. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62894. },
  62895. enumerable: true,
  62896. configurable: true
  62897. });
  62898. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62899. this._currentRefreshId = -1;
  62900. };
  62901. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62902. get: function () {
  62903. return this._refreshRate;
  62904. },
  62905. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62906. set: function (value) {
  62907. this._refreshRate = value;
  62908. this.resetRefreshCounter();
  62909. },
  62910. enumerable: true,
  62911. configurable: true
  62912. });
  62913. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62914. if (!this._postProcessManager) {
  62915. var scene = this.getScene();
  62916. if (!scene) {
  62917. return;
  62918. }
  62919. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62920. this._postProcesses = new Array();
  62921. }
  62922. this._postProcesses.push(postProcess);
  62923. this._postProcesses[0].autoClear = false;
  62924. };
  62925. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62926. if (!this._postProcesses) {
  62927. return;
  62928. }
  62929. if (dispose) {
  62930. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62931. var postProcess = _a[_i];
  62932. postProcess.dispose();
  62933. }
  62934. }
  62935. this._postProcesses = [];
  62936. };
  62937. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62938. if (!this._postProcesses) {
  62939. return;
  62940. }
  62941. var index = this._postProcesses.indexOf(postProcess);
  62942. if (index === -1) {
  62943. return;
  62944. }
  62945. this._postProcesses.splice(index, 1);
  62946. if (this._postProcesses.length > 0) {
  62947. this._postProcesses[0].autoClear = false;
  62948. }
  62949. };
  62950. RenderTargetTexture.prototype._shouldRender = function () {
  62951. if (this._currentRefreshId === -1) { // At least render once
  62952. this._currentRefreshId = 1;
  62953. return true;
  62954. }
  62955. if (this.refreshRate === this._currentRefreshId) {
  62956. this._currentRefreshId = 1;
  62957. return true;
  62958. }
  62959. this._currentRefreshId++;
  62960. return false;
  62961. };
  62962. RenderTargetTexture.prototype.getRenderSize = function () {
  62963. if (this._size.width) {
  62964. return this._size.width;
  62965. }
  62966. return this._size;
  62967. };
  62968. RenderTargetTexture.prototype.getRenderWidth = function () {
  62969. if (this._size.width) {
  62970. return this._size.width;
  62971. }
  62972. return this._size;
  62973. };
  62974. RenderTargetTexture.prototype.getRenderHeight = function () {
  62975. if (this._size.width) {
  62976. return this._size.height;
  62977. }
  62978. return this._size;
  62979. };
  62980. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62981. get: function () {
  62982. return true;
  62983. },
  62984. enumerable: true,
  62985. configurable: true
  62986. });
  62987. RenderTargetTexture.prototype.scale = function (ratio) {
  62988. var newSize = this.getRenderSize() * ratio;
  62989. this.resize(newSize);
  62990. };
  62991. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62992. if (this.isCube) {
  62993. return this._textureMatrix;
  62994. }
  62995. return _super.prototype.getReflectionTextureMatrix.call(this);
  62996. };
  62997. RenderTargetTexture.prototype.resize = function (size) {
  62998. this.releaseInternalTexture();
  62999. var scene = this.getScene();
  63000. if (!scene) {
  63001. return;
  63002. }
  63003. this._processSizeParameter(size);
  63004. if (this.isCube) {
  63005. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63006. }
  63007. else {
  63008. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63009. }
  63010. };
  63011. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63012. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63013. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63014. var scene = this.getScene();
  63015. if (!scene) {
  63016. return;
  63017. }
  63018. var engine = scene.getEngine();
  63019. if (this.useCameraPostProcesses !== undefined) {
  63020. useCameraPostProcess = this.useCameraPostProcesses;
  63021. }
  63022. if (this._waitingRenderList) {
  63023. this.renderList = [];
  63024. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63025. var id = this._waitingRenderList[index];
  63026. var mesh_1 = scene.getMeshByID(id);
  63027. if (mesh_1) {
  63028. this.renderList.push(mesh_1);
  63029. }
  63030. }
  63031. delete this._waitingRenderList;
  63032. }
  63033. // Is predicate defined?
  63034. if (this.renderListPredicate) {
  63035. if (this.renderList) {
  63036. this.renderList.splice(0); // Clear previous renderList
  63037. }
  63038. else {
  63039. this.renderList = [];
  63040. }
  63041. var scene = this.getScene();
  63042. if (!scene) {
  63043. return;
  63044. }
  63045. var sceneMeshes = scene.meshes;
  63046. for (var index = 0; index < sceneMeshes.length; index++) {
  63047. var mesh = sceneMeshes[index];
  63048. if (this.renderListPredicate(mesh)) {
  63049. this.renderList.push(mesh);
  63050. }
  63051. }
  63052. }
  63053. this.onBeforeBindObservable.notifyObservers(this);
  63054. // Set custom projection.
  63055. // Needs to be before binding to prevent changing the aspect ratio.
  63056. var camera;
  63057. if (this.activeCamera) {
  63058. camera = this.activeCamera;
  63059. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63060. if (this.activeCamera !== scene.activeCamera) {
  63061. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63062. }
  63063. }
  63064. else {
  63065. camera = scene.activeCamera;
  63066. if (camera) {
  63067. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63068. }
  63069. }
  63070. // Prepare renderingManager
  63071. this._renderingManager.reset();
  63072. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63073. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63074. var sceneRenderId = scene.getRenderId();
  63075. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63076. var mesh = currentRenderList[meshIndex];
  63077. if (mesh) {
  63078. if (!mesh.isReady(this.refreshRate === 0)) {
  63079. this.resetRefreshCounter();
  63080. continue;
  63081. }
  63082. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63083. var isMasked = void 0;
  63084. if (!this.renderList && camera) {
  63085. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63086. }
  63087. else {
  63088. isMasked = false;
  63089. }
  63090. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63091. mesh._activate(sceneRenderId);
  63092. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63093. var subMesh = mesh.subMeshes[subIndex];
  63094. scene._activeIndices.addCount(subMesh.indexCount, false);
  63095. this._renderingManager.dispatch(subMesh, mesh);
  63096. }
  63097. }
  63098. }
  63099. }
  63100. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63101. var particleSystem = scene.particleSystems[particleIndex];
  63102. var emitter = particleSystem.emitter;
  63103. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63104. continue;
  63105. }
  63106. if (currentRenderList.indexOf(emitter) >= 0) {
  63107. this._renderingManager.dispatchParticles(particleSystem);
  63108. }
  63109. }
  63110. if (this.isCube) {
  63111. for (var face = 0; face < 6; face++) {
  63112. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63113. scene.incrementRenderId();
  63114. scene.resetCachedMaterial();
  63115. }
  63116. }
  63117. else {
  63118. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63119. }
  63120. this.onAfterUnbindObservable.notifyObservers(this);
  63121. if (scene.activeCamera) {
  63122. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63123. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63124. }
  63125. engine.setViewport(scene.activeCamera.viewport);
  63126. }
  63127. scene.resetCachedMaterial();
  63128. };
  63129. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63130. var minimum = 128;
  63131. var x = renderDimension * scale;
  63132. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63133. // Ensure we don't exceed the render dimension (while staying POT)
  63134. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63135. };
  63136. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63137. var _this = this;
  63138. if (!this._texture) {
  63139. return;
  63140. }
  63141. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63142. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63143. });
  63144. };
  63145. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63146. var scene = this.getScene();
  63147. if (!scene) {
  63148. return;
  63149. }
  63150. var engine = scene.getEngine();
  63151. if (!this._texture) {
  63152. return;
  63153. }
  63154. // Bind
  63155. if (this._postProcessManager) {
  63156. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63157. }
  63158. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63159. if (this._texture) {
  63160. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63161. }
  63162. }
  63163. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63164. // Clear
  63165. if (this.onClearObservable.hasObservers()) {
  63166. this.onClearObservable.notifyObservers(engine);
  63167. }
  63168. else {
  63169. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63170. }
  63171. if (!this._doNotChangeAspectRatio) {
  63172. scene.updateTransformMatrix(true);
  63173. }
  63174. // Render
  63175. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63176. if (this._postProcessManager) {
  63177. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63178. }
  63179. else if (useCameraPostProcess) {
  63180. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63181. }
  63182. if (!this._doNotChangeAspectRatio) {
  63183. scene.updateTransformMatrix(true);
  63184. }
  63185. // Dump ?
  63186. if (dumpForDebug) {
  63187. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63188. }
  63189. // Unbind
  63190. if (!this.isCube || faceIndex === 5) {
  63191. if (this.isCube) {
  63192. if (faceIndex === 5) {
  63193. engine.generateMipMapsForCubemap(this._texture);
  63194. }
  63195. }
  63196. this.unbindFrameBuffer(engine, faceIndex);
  63197. }
  63198. else {
  63199. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63200. }
  63201. };
  63202. /**
  63203. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63204. * This allowed control for front to back rendering or reversly depending of the special needs.
  63205. *
  63206. * @param renderingGroupId The rendering group id corresponding to its index
  63207. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63208. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63209. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63210. */
  63211. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63212. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63213. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63214. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63215. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63216. };
  63217. /**
  63218. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63219. *
  63220. * @param renderingGroupId The rendering group id corresponding to its index
  63221. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63222. */
  63223. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63224. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63225. };
  63226. RenderTargetTexture.prototype.clone = function () {
  63227. var textureSize = this.getSize();
  63228. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63229. // Base texture
  63230. newTexture.hasAlpha = this.hasAlpha;
  63231. newTexture.level = this.level;
  63232. // RenderTarget Texture
  63233. newTexture.coordinatesMode = this.coordinatesMode;
  63234. if (this.renderList) {
  63235. newTexture.renderList = this.renderList.slice(0);
  63236. }
  63237. return newTexture;
  63238. };
  63239. RenderTargetTexture.prototype.serialize = function () {
  63240. if (!this.name) {
  63241. return null;
  63242. }
  63243. var serializationObject = _super.prototype.serialize.call(this);
  63244. serializationObject.renderTargetSize = this.getRenderSize();
  63245. serializationObject.renderList = [];
  63246. if (this.renderList) {
  63247. for (var index = 0; index < this.renderList.length; index++) {
  63248. serializationObject.renderList.push(this.renderList[index].id);
  63249. }
  63250. }
  63251. return serializationObject;
  63252. };
  63253. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63254. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63255. var objBuffer = this.getInternalTexture();
  63256. var scene = this.getScene();
  63257. if (objBuffer && scene) {
  63258. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63259. }
  63260. };
  63261. RenderTargetTexture.prototype.dispose = function () {
  63262. if (this._postProcessManager) {
  63263. this._postProcessManager.dispose();
  63264. this._postProcessManager = null;
  63265. }
  63266. this.clearPostProcesses(true);
  63267. if (this._resizeObserver) {
  63268. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63269. this._resizeObserver = null;
  63270. }
  63271. this.renderList = null;
  63272. // Remove from custom render targets
  63273. var scene = this.getScene();
  63274. if (!scene) {
  63275. return;
  63276. }
  63277. var index = scene.customRenderTargets.indexOf(this);
  63278. if (index >= 0) {
  63279. scene.customRenderTargets.splice(index, 1);
  63280. }
  63281. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63282. var camera = _a[_i];
  63283. index = camera.customRenderTargets.indexOf(this);
  63284. if (index >= 0) {
  63285. camera.customRenderTargets.splice(index, 1);
  63286. }
  63287. }
  63288. _super.prototype.dispose.call(this);
  63289. };
  63290. RenderTargetTexture.prototype._rebuild = function () {
  63291. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63292. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63293. }
  63294. if (this._postProcessManager) {
  63295. this._postProcessManager._rebuild();
  63296. }
  63297. };
  63298. /**
  63299. * Clear the info related to rendering groups preventing retention point in material dispose.
  63300. */
  63301. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63302. if (this._renderingManager) {
  63303. this._renderingManager.freeRenderingGroups();
  63304. }
  63305. };
  63306. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63307. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63308. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63309. return RenderTargetTexture;
  63310. }(BABYLON.Texture));
  63311. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63312. })(BABYLON || (BABYLON = {}));
  63313. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63314. var BABYLON;
  63315. (function (BABYLON) {
  63316. ;
  63317. var MultiRenderTarget = /** @class */ (function (_super) {
  63318. __extends(MultiRenderTarget, _super);
  63319. function MultiRenderTarget(name, size, count, scene, options) {
  63320. var _this = this;
  63321. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63322. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63323. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63324. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63325. _this._engine = scene.getEngine();
  63326. if (!_this.isSupported) {
  63327. _this.dispose();
  63328. return;
  63329. }
  63330. var types = [];
  63331. var samplingModes = [];
  63332. for (var i = 0; i < count; i++) {
  63333. if (options && options.types && options.types[i] !== undefined) {
  63334. types.push(options.types[i]);
  63335. }
  63336. else {
  63337. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63338. }
  63339. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63340. samplingModes.push(options.samplingModes[i]);
  63341. }
  63342. else {
  63343. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63344. }
  63345. }
  63346. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63347. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63348. _this._size = size;
  63349. _this._multiRenderTargetOptions = {
  63350. samplingModes: samplingModes,
  63351. generateMipMaps: generateMipMaps,
  63352. generateDepthBuffer: generateDepthBuffer,
  63353. generateStencilBuffer: generateStencilBuffer,
  63354. generateDepthTexture: generateDepthTexture,
  63355. types: types,
  63356. textureCount: count
  63357. };
  63358. _this._createInternalTextures();
  63359. _this._createTextures();
  63360. return _this;
  63361. }
  63362. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63363. get: function () {
  63364. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63365. },
  63366. enumerable: true,
  63367. configurable: true
  63368. });
  63369. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63370. get: function () {
  63371. return this._textures;
  63372. },
  63373. enumerable: true,
  63374. configurable: true
  63375. });
  63376. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63377. get: function () {
  63378. return this._textures[this._textures.length - 1];
  63379. },
  63380. enumerable: true,
  63381. configurable: true
  63382. });
  63383. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63384. set: function (wrap) {
  63385. if (this._textures) {
  63386. for (var i = 0; i < this._textures.length; i++) {
  63387. this._textures[i].wrapU = wrap;
  63388. }
  63389. }
  63390. },
  63391. enumerable: true,
  63392. configurable: true
  63393. });
  63394. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63395. set: function (wrap) {
  63396. if (this._textures) {
  63397. for (var i = 0; i < this._textures.length; i++) {
  63398. this._textures[i].wrapV = wrap;
  63399. }
  63400. }
  63401. },
  63402. enumerable: true,
  63403. configurable: true
  63404. });
  63405. MultiRenderTarget.prototype._rebuild = function () {
  63406. this.releaseInternalTextures();
  63407. this._createInternalTextures();
  63408. for (var i = 0; i < this._internalTextures.length; i++) {
  63409. var texture = this._textures[i];
  63410. texture._texture = this._internalTextures[i];
  63411. }
  63412. // Keeps references to frame buffer and stencil/depth buffer
  63413. this._texture = this._internalTextures[0];
  63414. };
  63415. MultiRenderTarget.prototype._createInternalTextures = function () {
  63416. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63417. };
  63418. MultiRenderTarget.prototype._createTextures = function () {
  63419. this._textures = [];
  63420. for (var i = 0; i < this._internalTextures.length; i++) {
  63421. var texture = new BABYLON.Texture(null, this.getScene());
  63422. texture._texture = this._internalTextures[i];
  63423. this._textures.push(texture);
  63424. }
  63425. // Keeps references to frame buffer and stencil/depth buffer
  63426. this._texture = this._internalTextures[0];
  63427. };
  63428. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63429. get: function () {
  63430. return this._samples;
  63431. },
  63432. set: function (value) {
  63433. if (this._samples === value) {
  63434. return;
  63435. }
  63436. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63437. },
  63438. enumerable: true,
  63439. configurable: true
  63440. });
  63441. MultiRenderTarget.prototype.resize = function (size) {
  63442. this.releaseInternalTextures();
  63443. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63444. this._createInternalTextures();
  63445. };
  63446. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63447. var _this = this;
  63448. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63449. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63450. });
  63451. };
  63452. MultiRenderTarget.prototype.dispose = function () {
  63453. this.releaseInternalTextures();
  63454. _super.prototype.dispose.call(this);
  63455. };
  63456. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63457. if (!this._internalTextures) {
  63458. return;
  63459. }
  63460. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63461. if (this._internalTextures[i] !== undefined) {
  63462. this._internalTextures[i].dispose();
  63463. this._internalTextures.splice(i, 1);
  63464. }
  63465. }
  63466. };
  63467. return MultiRenderTarget;
  63468. }(BABYLON.RenderTargetTexture));
  63469. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63470. })(BABYLON || (BABYLON = {}));
  63471. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63472. var BABYLON;
  63473. (function (BABYLON) {
  63474. var MirrorTexture = /** @class */ (function (_super) {
  63475. __extends(MirrorTexture, _super);
  63476. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63477. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63478. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63479. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63480. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63481. _this.scene = scene;
  63482. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63483. _this._transformMatrix = BABYLON.Matrix.Zero();
  63484. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63485. _this._adaptiveBlurKernel = 0;
  63486. _this._blurKernelX = 0;
  63487. _this._blurKernelY = 0;
  63488. _this._blurRatio = 1.0;
  63489. _this.ignoreCameraViewport = true;
  63490. _this._updateGammaSpace();
  63491. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63492. _this._updateGammaSpace;
  63493. });
  63494. _this.onBeforeRenderObservable.add(function () {
  63495. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63496. _this._savedViewMatrix = scene.getViewMatrix();
  63497. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63498. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63499. scene.clipPlane = _this.mirrorPlane;
  63500. scene.getEngine().cullBackFaces = false;
  63501. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63502. });
  63503. _this.onAfterRenderObservable.add(function () {
  63504. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63505. scene.getEngine().cullBackFaces = true;
  63506. scene._mirroredCameraPosition = null;
  63507. delete scene.clipPlane;
  63508. });
  63509. return _this;
  63510. }
  63511. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63512. get: function () {
  63513. return this._blurRatio;
  63514. },
  63515. set: function (value) {
  63516. if (this._blurRatio === value) {
  63517. return;
  63518. }
  63519. this._blurRatio = value;
  63520. this._preparePostProcesses();
  63521. },
  63522. enumerable: true,
  63523. configurable: true
  63524. });
  63525. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63526. set: function (value) {
  63527. this._adaptiveBlurKernel = value;
  63528. this._autoComputeBlurKernel();
  63529. },
  63530. enumerable: true,
  63531. configurable: true
  63532. });
  63533. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63534. set: function (value) {
  63535. this.blurKernelX = value;
  63536. this.blurKernelY = value;
  63537. },
  63538. enumerable: true,
  63539. configurable: true
  63540. });
  63541. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63542. get: function () {
  63543. return this._blurKernelX;
  63544. },
  63545. set: function (value) {
  63546. if (this._blurKernelX === value) {
  63547. return;
  63548. }
  63549. this._blurKernelX = value;
  63550. this._preparePostProcesses();
  63551. },
  63552. enumerable: true,
  63553. configurable: true
  63554. });
  63555. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63556. get: function () {
  63557. return this._blurKernelY;
  63558. },
  63559. set: function (value) {
  63560. if (this._blurKernelY === value) {
  63561. return;
  63562. }
  63563. this._blurKernelY = value;
  63564. this._preparePostProcesses();
  63565. },
  63566. enumerable: true,
  63567. configurable: true
  63568. });
  63569. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63570. var engine = this.getScene().getEngine();
  63571. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63572. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63573. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63574. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63575. };
  63576. MirrorTexture.prototype._onRatioRescale = function () {
  63577. if (this._sizeRatio) {
  63578. this.resize(this._initialSizeParameter);
  63579. if (!this._adaptiveBlurKernel) {
  63580. this._preparePostProcesses();
  63581. }
  63582. }
  63583. if (this._adaptiveBlurKernel) {
  63584. this._autoComputeBlurKernel();
  63585. }
  63586. };
  63587. MirrorTexture.prototype._updateGammaSpace = function () {
  63588. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63589. };
  63590. MirrorTexture.prototype._preparePostProcesses = function () {
  63591. this.clearPostProcesses(true);
  63592. if (this._blurKernelX && this._blurKernelY) {
  63593. var engine = this.getScene().getEngine();
  63594. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63595. 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);
  63596. this._blurX.autoClear = false;
  63597. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63598. this._blurX.inputTexture = this._texture;
  63599. }
  63600. else {
  63601. this._blurX.alwaysForcePOT = true;
  63602. }
  63603. 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);
  63604. this._blurY.autoClear = false;
  63605. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63606. this.addPostProcess(this._blurX);
  63607. this.addPostProcess(this._blurY);
  63608. }
  63609. else {
  63610. if (this._blurY) {
  63611. this.removePostProcess(this._blurY);
  63612. this._blurY.dispose();
  63613. this._blurY = null;
  63614. }
  63615. if (this._blurX) {
  63616. this.removePostProcess(this._blurX);
  63617. this._blurX.dispose();
  63618. this._blurX = null;
  63619. }
  63620. }
  63621. };
  63622. MirrorTexture.prototype.clone = function () {
  63623. var scene = this.getScene();
  63624. if (!scene) {
  63625. return this;
  63626. }
  63627. var textureSize = this.getSize();
  63628. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63629. // Base texture
  63630. newTexture.hasAlpha = this.hasAlpha;
  63631. newTexture.level = this.level;
  63632. // Mirror Texture
  63633. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63634. if (this.renderList) {
  63635. newTexture.renderList = this.renderList.slice(0);
  63636. }
  63637. return newTexture;
  63638. };
  63639. MirrorTexture.prototype.serialize = function () {
  63640. if (!this.name) {
  63641. return null;
  63642. }
  63643. var serializationObject = _super.prototype.serialize.call(this);
  63644. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63645. return serializationObject;
  63646. };
  63647. MirrorTexture.prototype.dispose = function () {
  63648. _super.prototype.dispose.call(this);
  63649. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63650. };
  63651. return MirrorTexture;
  63652. }(BABYLON.RenderTargetTexture));
  63653. BABYLON.MirrorTexture = MirrorTexture;
  63654. })(BABYLON || (BABYLON = {}));
  63655. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63656. var BABYLON;
  63657. (function (BABYLON) {
  63658. /**
  63659. * Creates a refraction texture used by refraction channel of the standard material.
  63660. * @param name the texture name
  63661. * @param size size of the underlying texture
  63662. * @param scene root scene
  63663. */
  63664. var RefractionTexture = /** @class */ (function (_super) {
  63665. __extends(RefractionTexture, _super);
  63666. function RefractionTexture(name, size, scene, generateMipMaps) {
  63667. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63668. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63669. _this.depth = 2.0;
  63670. _this.onBeforeRenderObservable.add(function () {
  63671. scene.clipPlane = _this.refractionPlane;
  63672. });
  63673. _this.onAfterRenderObservable.add(function () {
  63674. delete scene.clipPlane;
  63675. });
  63676. return _this;
  63677. }
  63678. RefractionTexture.prototype.clone = function () {
  63679. var scene = this.getScene();
  63680. if (!scene) {
  63681. return this;
  63682. }
  63683. var textureSize = this.getSize();
  63684. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63685. // Base texture
  63686. newTexture.hasAlpha = this.hasAlpha;
  63687. newTexture.level = this.level;
  63688. // Refraction Texture
  63689. newTexture.refractionPlane = this.refractionPlane.clone();
  63690. if (this.renderList) {
  63691. newTexture.renderList = this.renderList.slice(0);
  63692. }
  63693. newTexture.depth = this.depth;
  63694. return newTexture;
  63695. };
  63696. RefractionTexture.prototype.serialize = function () {
  63697. if (!this.name) {
  63698. return null;
  63699. }
  63700. var serializationObject = _super.prototype.serialize.call(this);
  63701. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63702. serializationObject.depth = this.depth;
  63703. return serializationObject;
  63704. };
  63705. return RefractionTexture;
  63706. }(BABYLON.RenderTargetTexture));
  63707. BABYLON.RefractionTexture = RefractionTexture;
  63708. })(BABYLON || (BABYLON = {}));
  63709. //# sourceMappingURL=babylon.refractionTexture.js.map
  63710. var BABYLON;
  63711. (function (BABYLON) {
  63712. /**
  63713. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63714. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63715. */
  63716. var DynamicTexture = /** @class */ (function (_super) {
  63717. __extends(DynamicTexture, _super);
  63718. /**
  63719. * Creates a {BABYLON.DynamicTexture}
  63720. * @param name defines the name of the texture
  63721. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  63722. * @param scene defines the scene where you want the texture
  63723. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63724. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63725. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63726. */
  63727. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63728. if (scene === void 0) { scene = null; }
  63729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63730. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63731. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63732. _this.name = name;
  63733. _this._engine = _this.getScene().getEngine();
  63734. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63735. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63736. _this._generateMipMaps = generateMipMaps;
  63737. if (options.getContext) {
  63738. _this._canvas = options;
  63739. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63740. }
  63741. else {
  63742. _this._canvas = document.createElement("canvas");
  63743. if (options.width) {
  63744. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63745. }
  63746. else {
  63747. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63748. }
  63749. }
  63750. var textureSize = _this.getSize();
  63751. _this._canvas.width = textureSize.width;
  63752. _this._canvas.height = textureSize.height;
  63753. _this._context = _this._canvas.getContext("2d");
  63754. return _this;
  63755. }
  63756. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63757. /**
  63758. * Gets the current state of canRescale
  63759. */
  63760. get: function () {
  63761. return true;
  63762. },
  63763. enumerable: true,
  63764. configurable: true
  63765. });
  63766. DynamicTexture.prototype._recreate = function (textureSize) {
  63767. this._canvas.width = textureSize.width;
  63768. this._canvas.height = textureSize.height;
  63769. this.releaseInternalTexture();
  63770. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63771. };
  63772. /**
  63773. * Scales the texture
  63774. * @param ratio the scale factor to apply to both width and height
  63775. */
  63776. DynamicTexture.prototype.scale = function (ratio) {
  63777. var textureSize = this.getSize();
  63778. textureSize.width *= ratio;
  63779. textureSize.height *= ratio;
  63780. this._recreate(textureSize);
  63781. };
  63782. /**
  63783. * Resizes the texture
  63784. * @param width the new width
  63785. * @param height the new height
  63786. */
  63787. DynamicTexture.prototype.scaleTo = function (width, height) {
  63788. var textureSize = this.getSize();
  63789. textureSize.width = width;
  63790. textureSize.height = height;
  63791. this._recreate(textureSize);
  63792. };
  63793. /**
  63794. * Gets the context of the canvas used by the texture
  63795. * @returns the canvas context of the dynamic texture
  63796. */
  63797. DynamicTexture.prototype.getContext = function () {
  63798. return this._context;
  63799. };
  63800. /**
  63801. * Clears the texture
  63802. */
  63803. DynamicTexture.prototype.clear = function () {
  63804. var size = this.getSize();
  63805. this._context.fillRect(0, 0, size.width, size.height);
  63806. };
  63807. /**
  63808. * Updates the texture
  63809. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63810. */
  63811. DynamicTexture.prototype.update = function (invertY) {
  63812. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  63813. };
  63814. /**
  63815. * Draws text onto the texture
  63816. * @param text defines the text to be drawn
  63817. * @param x defines the placement of the text from the left
  63818. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63819. * @param font defines the font to be used with font-style, font-size, font-name
  63820. * @param color defines the color used for the text
  63821. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63822. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63823. * @param update defines whether texture is immediately update (default is true)
  63824. */
  63825. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63826. if (update === void 0) { update = true; }
  63827. var size = this.getSize();
  63828. if (clearColor) {
  63829. this._context.fillStyle = clearColor;
  63830. this._context.fillRect(0, 0, size.width, size.height);
  63831. }
  63832. this._context.font = font;
  63833. if (x === null || x === undefined) {
  63834. var textSize = this._context.measureText(text);
  63835. x = (size.width - textSize.width) / 2;
  63836. }
  63837. if (y === null || y === undefined) {
  63838. var fontSize = parseInt((font.replace(/\D/g, '')));
  63839. ;
  63840. y = (size.height / 2) + (fontSize / 3.65);
  63841. }
  63842. this._context.fillStyle = color;
  63843. this._context.fillText(text, x, y);
  63844. if (update) {
  63845. this.update(invertY);
  63846. }
  63847. };
  63848. /**
  63849. * Clones the texture
  63850. * @returns the clone of the texture.
  63851. */
  63852. DynamicTexture.prototype.clone = function () {
  63853. var scene = this.getScene();
  63854. if (!scene) {
  63855. return this;
  63856. }
  63857. var textureSize = this.getSize();
  63858. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63859. // Base texture
  63860. newTexture.hasAlpha = this.hasAlpha;
  63861. newTexture.level = this.level;
  63862. // Dynamic Texture
  63863. newTexture.wrapU = this.wrapU;
  63864. newTexture.wrapV = this.wrapV;
  63865. return newTexture;
  63866. };
  63867. /** @ignore */
  63868. DynamicTexture.prototype._rebuild = function () {
  63869. this.update();
  63870. };
  63871. return DynamicTexture;
  63872. }(BABYLON.Texture));
  63873. BABYLON.DynamicTexture = DynamicTexture;
  63874. })(BABYLON || (BABYLON = {}));
  63875. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63876. var BABYLON;
  63877. (function (BABYLON) {
  63878. var VideoTexture = /** @class */ (function (_super) {
  63879. __extends(VideoTexture, _super);
  63880. /**
  63881. * Creates a video texture.
  63882. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63883. * @param {string | null} name optional name, will detect from video source, if not defined
  63884. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63885. * @param {BABYLON.Scene} scene is obviously the current scene.
  63886. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63887. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63888. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63889. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63890. */
  63891. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63892. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63893. if (invertY === void 0) { invertY = false; }
  63894. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63895. if (settings === void 0) { settings = {
  63896. autoPlay: true,
  63897. loop: true,
  63898. autoUpdateTexture: true,
  63899. }; }
  63900. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63901. _this._createInternalTexture = function () {
  63902. if (_this._texture != null) {
  63903. return;
  63904. }
  63905. if (!_this._engine.needPOTTextures ||
  63906. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63907. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63908. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63909. }
  63910. else {
  63911. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63912. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63913. _this._generateMipMaps = false;
  63914. }
  63915. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63916. _this._texture.isReady = true;
  63917. _this._updateInternalTexture();
  63918. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63919. _this.onLoadObservable.notifyObservers(_this);
  63920. }
  63921. };
  63922. _this.reset = function () {
  63923. if (_this._texture == null) {
  63924. return;
  63925. }
  63926. _this._texture.dispose();
  63927. _this._texture = null;
  63928. };
  63929. _this._updateInternalTexture = function (e) {
  63930. if (_this._texture == null || !_this._texture.isReady) {
  63931. return;
  63932. }
  63933. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63934. return;
  63935. }
  63936. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63937. };
  63938. _this._engine = _this.getScene().getEngine();
  63939. _this._generateMipMaps = generateMipMaps;
  63940. _this._samplingMode = samplingMode;
  63941. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63942. _this.name = name || _this._getName(src);
  63943. _this.video = _this._getVideo(src);
  63944. if (settings.autoPlay !== undefined) {
  63945. _this.video.autoplay = settings.autoPlay;
  63946. }
  63947. if (settings.loop !== undefined) {
  63948. _this.video.loop = settings.loop;
  63949. }
  63950. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63951. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63952. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63953. _this.video.addEventListener("emptied", _this.reset);
  63954. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63955. _this._createInternalTexture();
  63956. }
  63957. return _this;
  63958. }
  63959. VideoTexture.prototype._getName = function (src) {
  63960. if (src instanceof HTMLVideoElement) {
  63961. return src.currentSrc;
  63962. }
  63963. if (typeof src === "object") {
  63964. return src.toString();
  63965. }
  63966. return src;
  63967. };
  63968. ;
  63969. VideoTexture.prototype._getVideo = function (src) {
  63970. if (src instanceof HTMLVideoElement) {
  63971. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63972. return src;
  63973. }
  63974. var video = document.createElement("video");
  63975. if (typeof src === "string") {
  63976. BABYLON.Tools.SetCorsBehavior(src, video);
  63977. video.src = src;
  63978. }
  63979. else {
  63980. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63981. src.forEach(function (url) {
  63982. var source = document.createElement("source");
  63983. source.src = url;
  63984. video.appendChild(source);
  63985. });
  63986. }
  63987. return video;
  63988. };
  63989. ;
  63990. /**
  63991. * Internal method to initiate `update`.
  63992. */
  63993. VideoTexture.prototype._rebuild = function () {
  63994. this.update();
  63995. };
  63996. /**
  63997. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63998. */
  63999. VideoTexture.prototype.update = function () {
  64000. if (!this.autoUpdateTexture) {
  64001. // Expecting user to call `updateTexture` manually
  64002. return;
  64003. }
  64004. this.updateTexture(true);
  64005. };
  64006. /**
  64007. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64008. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64009. */
  64010. VideoTexture.prototype.updateTexture = function (isVisible) {
  64011. if (!isVisible) {
  64012. return;
  64013. }
  64014. if (this.video.paused) {
  64015. return;
  64016. }
  64017. this._updateInternalTexture();
  64018. };
  64019. /**
  64020. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64021. * @param url New url.
  64022. */
  64023. VideoTexture.prototype.updateURL = function (url) {
  64024. this.video.src = url;
  64025. };
  64026. VideoTexture.prototype.dispose = function () {
  64027. _super.prototype.dispose.call(this);
  64028. this.video.removeEventListener("canplay", this._createInternalTexture);
  64029. this.video.removeEventListener("paused", this._updateInternalTexture);
  64030. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64031. this.video.removeEventListener("emptied", this.reset);
  64032. this.video.pause();
  64033. };
  64034. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64035. var video = document.createElement("video");
  64036. var constraintsDeviceId;
  64037. if (constraints && constraints.deviceId) {
  64038. constraintsDeviceId = {
  64039. exact: constraints.deviceId,
  64040. };
  64041. }
  64042. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64043. if (navigator.mediaDevices) {
  64044. navigator.mediaDevices.getUserMedia({ video: constraints })
  64045. .then(function (stream) {
  64046. if (video.mozSrcObject !== undefined) {
  64047. // hack for Firefox < 19
  64048. video.mozSrcObject = stream;
  64049. }
  64050. else {
  64051. video.srcObject = stream;
  64052. }
  64053. var onPlaying = function () {
  64054. if (onReady) {
  64055. onReady(new VideoTexture("video", video, scene, true, true));
  64056. }
  64057. video.removeEventListener("playing", onPlaying);
  64058. };
  64059. video.addEventListener("playing", onPlaying);
  64060. video.play();
  64061. })
  64062. .catch(function (err) {
  64063. BABYLON.Tools.Error(err.name);
  64064. });
  64065. }
  64066. else {
  64067. navigator.getUserMedia =
  64068. navigator.getUserMedia ||
  64069. navigator.webkitGetUserMedia ||
  64070. navigator.mozGetUserMedia ||
  64071. navigator.msGetUserMedia;
  64072. if (navigator.getUserMedia) {
  64073. navigator.getUserMedia({
  64074. video: {
  64075. deviceId: constraintsDeviceId,
  64076. width: {
  64077. min: (constraints && constraints.minWidth) || 256,
  64078. max: (constraints && constraints.maxWidth) || 640,
  64079. },
  64080. height: {
  64081. min: (constraints && constraints.minHeight) || 256,
  64082. max: (constraints && constraints.maxHeight) || 480,
  64083. },
  64084. },
  64085. }, function (stream) {
  64086. if (video.mozSrcObject !== undefined) {
  64087. // hack for Firefox < 19
  64088. video.mozSrcObject = stream;
  64089. }
  64090. else {
  64091. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64092. }
  64093. video.play();
  64094. if (onReady) {
  64095. onReady(new VideoTexture("video", video, scene, true, true));
  64096. }
  64097. }, function (e) {
  64098. BABYLON.Tools.Error(e.name);
  64099. });
  64100. }
  64101. }
  64102. };
  64103. return VideoTexture;
  64104. }(BABYLON.Texture));
  64105. BABYLON.VideoTexture = VideoTexture;
  64106. })(BABYLON || (BABYLON = {}));
  64107. //# sourceMappingURL=babylon.videoTexture.js.map
  64108. var BABYLON;
  64109. (function (BABYLON) {
  64110. var RawTexture = /** @class */ (function (_super) {
  64111. __extends(RawTexture, _super);
  64112. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64113. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64114. if (invertY === void 0) { invertY = false; }
  64115. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64116. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64117. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64118. _this.format = format;
  64119. _this._engine = scene.getEngine();
  64120. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64121. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64122. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64123. return _this;
  64124. }
  64125. RawTexture.prototype.update = function (data) {
  64126. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64127. };
  64128. // Statics
  64129. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64130. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64131. if (invertY === void 0) { invertY = false; }
  64132. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64133. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64134. };
  64135. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64136. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64137. if (invertY === void 0) { invertY = false; }
  64138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64139. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64140. };
  64141. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64142. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64143. if (invertY === void 0) { invertY = false; }
  64144. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64145. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64146. };
  64147. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64148. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64149. if (invertY === void 0) { invertY = false; }
  64150. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64151. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64152. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64153. };
  64154. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64155. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64156. if (invertY === void 0) { invertY = false; }
  64157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64158. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64159. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64160. };
  64161. return RawTexture;
  64162. }(BABYLON.Texture));
  64163. BABYLON.RawTexture = RawTexture;
  64164. })(BABYLON || (BABYLON = {}));
  64165. //# sourceMappingURL=babylon.rawTexture.js.map
  64166. var BABYLON;
  64167. (function (BABYLON) {
  64168. /**
  64169. * Class used to store 3D textures containing user data
  64170. */
  64171. var RawTexture3D = /** @class */ (function (_super) {
  64172. __extends(RawTexture3D, _super);
  64173. /**
  64174. * Create a new RawTexture3D
  64175. * @param data defines the data of the texture
  64176. * @param width defines the width of the texture
  64177. * @param height defines the height of the texture
  64178. * @param depth defines the depth of the texture
  64179. * @param format defines the texture format to use
  64180. * @param scene defines the hosting scene
  64181. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64182. * @param invertY defines if texture must be stored with Y axis inverted
  64183. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64184. */
  64185. function RawTexture3D(data, width, height, depth,
  64186. /** Gets or sets the texture format to use*/
  64187. format, scene, generateMipMaps, invertY, samplingMode) {
  64188. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64189. if (invertY === void 0) { invertY = false; }
  64190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64191. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64192. _this.format = format;
  64193. _this._engine = scene.getEngine();
  64194. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64195. _this.is3D = true;
  64196. return _this;
  64197. }
  64198. /**
  64199. * Update the texture with new data
  64200. * @param data defines the data to store in the texture
  64201. */
  64202. RawTexture3D.prototype.update = function (data) {
  64203. if (!this._texture) {
  64204. return;
  64205. }
  64206. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64207. };
  64208. return RawTexture3D;
  64209. }(BABYLON.Texture));
  64210. BABYLON.RawTexture3D = RawTexture3D;
  64211. })(BABYLON || (BABYLON = {}));
  64212. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64213. var BABYLON;
  64214. (function (BABYLON) {
  64215. /**
  64216. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64217. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64218. */
  64219. var PostProcess = /** @class */ (function () {
  64220. /**
  64221. * Creates a new instance PostProcess
  64222. * @param name The name of the PostProcess.
  64223. * @param fragmentUrl The url of the fragment shader to be used.
  64224. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64225. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64226. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64227. * @param camera The camera to apply the render pass to.
  64228. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64229. * @param engine The engine which the post process will be applied. (default: current engine)
  64230. * @param reusable If the post process can be reused on the same frame. (default: false)
  64231. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64232. * @param textureType Type of textures used when performing the post process. (default: 0)
  64233. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64234. * @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
  64235. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64236. */
  64237. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64239. if (defines === void 0) { defines = null; }
  64240. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64241. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64242. if (blockCompilation === void 0) { blockCompilation = false; }
  64243. this.name = name;
  64244. /**
  64245. * Width of the texture to apply the post process on
  64246. */
  64247. this.width = -1;
  64248. /**
  64249. * Height of the texture to apply the post process on
  64250. */
  64251. this.height = -1;
  64252. /**
  64253. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64254. */
  64255. this._outputTexture = null;
  64256. /**
  64257. * If the buffer needs to be cleared before applying the post process. (default: true)
  64258. * Should be set to false if shader will overwrite all previous pixels.
  64259. */
  64260. this.autoClear = true;
  64261. /**
  64262. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64263. */
  64264. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64265. /**
  64266. * Animations to be used for the post processing
  64267. */
  64268. this.animations = new Array();
  64269. /**
  64270. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64271. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64272. */
  64273. this.enablePixelPerfectMode = false;
  64274. /**
  64275. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64276. */
  64277. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64278. /**
  64279. * Force textures to be a power of two (default: false)
  64280. */
  64281. this.alwaysForcePOT = false;
  64282. /**
  64283. * Number of sample textures (default: 1)
  64284. */
  64285. this.samples = 1;
  64286. /**
  64287. * Modify the scale of the post process to be the same as the viewport (default: false)
  64288. */
  64289. this.adaptScaleToCurrentViewport = false;
  64290. this._reusable = false;
  64291. /**
  64292. * Smart array of input and output textures for the post process.
  64293. */
  64294. this._textures = new BABYLON.SmartArray(2);
  64295. /**
  64296. * The index in _textures that corresponds to the output texture.
  64297. */
  64298. this._currentRenderTextureInd = 0;
  64299. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64300. this._texelSize = BABYLON.Vector2.Zero();
  64301. // Events
  64302. /**
  64303. * An event triggered when the postprocess is activated.
  64304. */
  64305. this.onActivateObservable = new BABYLON.Observable();
  64306. /**
  64307. * An event triggered when the postprocess changes its size.
  64308. */
  64309. this.onSizeChangedObservable = new BABYLON.Observable();
  64310. /**
  64311. * An event triggered when the postprocess applies its effect.
  64312. */
  64313. this.onApplyObservable = new BABYLON.Observable();
  64314. /**
  64315. * An event triggered before rendering the postprocess
  64316. */
  64317. this.onBeforeRenderObservable = new BABYLON.Observable();
  64318. /**
  64319. * An event triggered after rendering the postprocess
  64320. */
  64321. this.onAfterRenderObservable = new BABYLON.Observable();
  64322. if (camera != null) {
  64323. this._camera = camera;
  64324. this._scene = camera.getScene();
  64325. camera.attachPostProcess(this);
  64326. this._engine = this._scene.getEngine();
  64327. this._scene.postProcesses.push(this);
  64328. }
  64329. else if (engine) {
  64330. this._engine = engine;
  64331. this._engine.postProcesses.push(this);
  64332. }
  64333. this._options = options;
  64334. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64335. this._reusable = reusable || false;
  64336. this._textureType = textureType;
  64337. this._samplers = samplers || [];
  64338. this._samplers.push("textureSampler");
  64339. this._fragmentUrl = fragmentUrl;
  64340. this._vertexUrl = vertexUrl;
  64341. this._parameters = parameters || [];
  64342. this._parameters.push("scale");
  64343. this._indexParameters = indexParameters;
  64344. if (!blockCompilation) {
  64345. this.updateEffect(defines);
  64346. }
  64347. }
  64348. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64349. /**
  64350. * A function that is added to the onActivateObservable
  64351. */
  64352. set: function (callback) {
  64353. if (this._onActivateObserver) {
  64354. this.onActivateObservable.remove(this._onActivateObserver);
  64355. }
  64356. if (callback) {
  64357. this._onActivateObserver = this.onActivateObservable.add(callback);
  64358. }
  64359. },
  64360. enumerable: true,
  64361. configurable: true
  64362. });
  64363. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64364. /**
  64365. * A function that is added to the onSizeChangedObservable
  64366. */
  64367. set: function (callback) {
  64368. if (this._onSizeChangedObserver) {
  64369. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64370. }
  64371. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64372. },
  64373. enumerable: true,
  64374. configurable: true
  64375. });
  64376. Object.defineProperty(PostProcess.prototype, "onApply", {
  64377. /**
  64378. * A function that is added to the onApplyObservable
  64379. */
  64380. set: function (callback) {
  64381. if (this._onApplyObserver) {
  64382. this.onApplyObservable.remove(this._onApplyObserver);
  64383. }
  64384. this._onApplyObserver = this.onApplyObservable.add(callback);
  64385. },
  64386. enumerable: true,
  64387. configurable: true
  64388. });
  64389. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64390. /**
  64391. * A function that is added to the onBeforeRenderObservable
  64392. */
  64393. set: function (callback) {
  64394. if (this._onBeforeRenderObserver) {
  64395. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64396. }
  64397. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64398. },
  64399. enumerable: true,
  64400. configurable: true
  64401. });
  64402. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64403. /**
  64404. * A function that is added to the onAfterRenderObservable
  64405. */
  64406. set: function (callback) {
  64407. if (this._onAfterRenderObserver) {
  64408. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64409. }
  64410. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64411. },
  64412. enumerable: true,
  64413. configurable: true
  64414. });
  64415. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64416. /**
  64417. * 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
  64418. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64419. */
  64420. get: function () {
  64421. return this._textures.data[this._currentRenderTextureInd];
  64422. },
  64423. set: function (value) {
  64424. this._forcedOutputTexture = value;
  64425. },
  64426. enumerable: true,
  64427. configurable: true
  64428. });
  64429. /**
  64430. * Gets the camera which post process is applied to.
  64431. * @returns The camera the post process is applied to.
  64432. */
  64433. PostProcess.prototype.getCamera = function () {
  64434. return this._camera;
  64435. };
  64436. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64437. /**
  64438. * Gets the texel size of the postprocess.
  64439. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64440. */
  64441. get: function () {
  64442. if (this._shareOutputWithPostProcess) {
  64443. return this._shareOutputWithPostProcess.texelSize;
  64444. }
  64445. if (this._forcedOutputTexture) {
  64446. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64447. }
  64448. return this._texelSize;
  64449. },
  64450. enumerable: true,
  64451. configurable: true
  64452. });
  64453. /**
  64454. * Gets the engine which this post process belongs to.
  64455. * @returns The engine the post process was enabled with.
  64456. */
  64457. PostProcess.prototype.getEngine = function () {
  64458. return this._engine;
  64459. };
  64460. /**
  64461. * The effect that is created when initializing the post process.
  64462. * @returns The created effect corrisponding the the postprocess.
  64463. */
  64464. PostProcess.prototype.getEffect = function () {
  64465. return this._effect;
  64466. };
  64467. /**
  64468. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64469. * @param postProcess The post process to share the output with.
  64470. * @returns This post process.
  64471. */
  64472. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64473. this._disposeTextures();
  64474. this._shareOutputWithPostProcess = postProcess;
  64475. return this;
  64476. };
  64477. /**
  64478. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64479. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64480. */
  64481. PostProcess.prototype.useOwnOutput = function () {
  64482. if (this._textures.length == 0) {
  64483. this._textures = new BABYLON.SmartArray(2);
  64484. }
  64485. this._shareOutputWithPostProcess = null;
  64486. };
  64487. /**
  64488. * Updates the effect with the current post process compile time values and recompiles the shader.
  64489. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64490. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64491. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64492. * @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
  64493. * @param onCompiled Called when the shader has been compiled.
  64494. * @param onError Called if there is an error when compiling a shader.
  64495. */
  64496. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64497. if (defines === void 0) { defines = null; }
  64498. if (uniforms === void 0) { uniforms = null; }
  64499. if (samplers === void 0) { samplers = null; }
  64500. 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);
  64501. };
  64502. /**
  64503. * The post process is reusable if it can be used multiple times within one frame.
  64504. * @returns If the post process is reusable
  64505. */
  64506. PostProcess.prototype.isReusable = function () {
  64507. return this._reusable;
  64508. };
  64509. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64510. PostProcess.prototype.markTextureDirty = function () {
  64511. this.width = -1;
  64512. };
  64513. /**
  64514. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64515. * 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.
  64516. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64517. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64518. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64519. * @returns The target texture that was bound to be written to.
  64520. */
  64521. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64522. var _this = this;
  64523. if (sourceTexture === void 0) { sourceTexture = null; }
  64524. camera = camera || this._camera;
  64525. var scene = camera.getScene();
  64526. var engine = scene.getEngine();
  64527. var maxSize = engine.getCaps().maxTextureSize;
  64528. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64529. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64530. // 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
  64531. var webVRCamera = camera.parent;
  64532. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64533. requiredWidth /= 2;
  64534. }
  64535. var desiredWidth = (this._options.width || requiredWidth);
  64536. var desiredHeight = this._options.height || requiredHeight;
  64537. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64538. if (this.adaptScaleToCurrentViewport) {
  64539. var currentViewport = engine.currentViewport;
  64540. if (currentViewport) {
  64541. desiredWidth *= currentViewport.width;
  64542. desiredHeight *= currentViewport.height;
  64543. }
  64544. }
  64545. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64546. if (!this._options.width) {
  64547. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64548. }
  64549. if (!this._options.height) {
  64550. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64551. }
  64552. }
  64553. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64554. if (this._textures.length > 0) {
  64555. for (var i = 0; i < this._textures.length; i++) {
  64556. this._engine._releaseTexture(this._textures.data[i]);
  64557. }
  64558. this._textures.reset();
  64559. }
  64560. this.width = desiredWidth;
  64561. this.height = desiredHeight;
  64562. var textureSize = { width: this.width, height: this.height };
  64563. var textureOptions = {
  64564. generateMipMaps: false,
  64565. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64566. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64567. samplingMode: this.renderTargetSamplingMode,
  64568. type: this._textureType
  64569. };
  64570. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64571. if (this._reusable) {
  64572. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64573. }
  64574. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64575. this.onSizeChangedObservable.notifyObservers(this);
  64576. }
  64577. this._textures.forEach(function (texture) {
  64578. if (texture.samples !== _this.samples) {
  64579. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64580. }
  64581. });
  64582. }
  64583. var target;
  64584. if (this._shareOutputWithPostProcess) {
  64585. target = this._shareOutputWithPostProcess.inputTexture;
  64586. }
  64587. else if (this._forcedOutputTexture) {
  64588. target = this._forcedOutputTexture;
  64589. this.width = this._forcedOutputTexture.width;
  64590. this.height = this._forcedOutputTexture.height;
  64591. }
  64592. else {
  64593. target = this.inputTexture;
  64594. }
  64595. // Bind the input of this post process to be used as the output of the previous post process.
  64596. if (this.enablePixelPerfectMode) {
  64597. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64598. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  64599. }
  64600. else {
  64601. this._scaleRatio.copyFromFloats(1, 1);
  64602. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  64603. }
  64604. this.onActivateObservable.notifyObservers(camera);
  64605. // Clear
  64606. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64607. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64608. }
  64609. if (this._reusable) {
  64610. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64611. }
  64612. return target;
  64613. };
  64614. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64615. /**
  64616. * If the post process is supported.
  64617. */
  64618. get: function () {
  64619. return this._effect.isSupported;
  64620. },
  64621. enumerable: true,
  64622. configurable: true
  64623. });
  64624. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64625. /**
  64626. * The aspect ratio of the output texture.
  64627. */
  64628. get: function () {
  64629. if (this._shareOutputWithPostProcess) {
  64630. return this._shareOutputWithPostProcess.aspectRatio;
  64631. }
  64632. if (this._forcedOutputTexture) {
  64633. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64634. }
  64635. return this.width / this.height;
  64636. },
  64637. enumerable: true,
  64638. configurable: true
  64639. });
  64640. /**
  64641. * Get a value indicating if the post-process is ready to be used
  64642. * @returns true if the post-process is ready (shader is compiled)
  64643. */
  64644. PostProcess.prototype.isReady = function () {
  64645. return this._effect && this._effect.isReady();
  64646. };
  64647. /**
  64648. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64649. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64650. */
  64651. PostProcess.prototype.apply = function () {
  64652. // Check
  64653. if (!this._effect || !this._effect.isReady())
  64654. return null;
  64655. // States
  64656. this._engine.enableEffect(this._effect);
  64657. this._engine.setState(false);
  64658. this._engine.setDepthBuffer(false);
  64659. this._engine.setDepthWrite(false);
  64660. // Alpha
  64661. this._engine.setAlphaMode(this.alphaMode);
  64662. if (this.alphaConstants) {
  64663. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64664. }
  64665. // Bind the output texture of the preivous post process as the input to this post process.
  64666. var source;
  64667. if (this._shareOutputWithPostProcess) {
  64668. source = this._shareOutputWithPostProcess.inputTexture;
  64669. }
  64670. else if (this._forcedOutputTexture) {
  64671. source = this._forcedOutputTexture;
  64672. }
  64673. else {
  64674. source = this.inputTexture;
  64675. }
  64676. this._effect._bindTexture("textureSampler", source);
  64677. // Parameters
  64678. this._effect.setVector2("scale", this._scaleRatio);
  64679. this.onApplyObservable.notifyObservers(this._effect);
  64680. return this._effect;
  64681. };
  64682. PostProcess.prototype._disposeTextures = function () {
  64683. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64684. return;
  64685. }
  64686. if (this._textures.length > 0) {
  64687. for (var i = 0; i < this._textures.length; i++) {
  64688. this._engine._releaseTexture(this._textures.data[i]);
  64689. }
  64690. }
  64691. this._textures.dispose();
  64692. };
  64693. /**
  64694. * Disposes the post process.
  64695. * @param camera The camera to dispose the post process on.
  64696. */
  64697. PostProcess.prototype.dispose = function (camera) {
  64698. camera = camera || this._camera;
  64699. this._disposeTextures();
  64700. if (this._scene) {
  64701. var index_1 = this._scene.postProcesses.indexOf(this);
  64702. if (index_1 !== -1) {
  64703. this._scene.postProcesses.splice(index_1, 1);
  64704. }
  64705. }
  64706. else {
  64707. var index_2 = this._engine.postProcesses.indexOf(this);
  64708. if (index_2 !== -1) {
  64709. this._engine.postProcesses.splice(index_2, 1);
  64710. }
  64711. }
  64712. if (!camera) {
  64713. return;
  64714. }
  64715. camera.detachPostProcess(this);
  64716. var index = camera._postProcesses.indexOf(this);
  64717. if (index === 0 && camera._postProcesses.length > 0) {
  64718. var firstPostProcess = this._camera._getFirstPostProcess();
  64719. if (firstPostProcess) {
  64720. firstPostProcess.markTextureDirty();
  64721. }
  64722. }
  64723. this.onActivateObservable.clear();
  64724. this.onAfterRenderObservable.clear();
  64725. this.onApplyObservable.clear();
  64726. this.onBeforeRenderObservable.clear();
  64727. this.onSizeChangedObservable.clear();
  64728. };
  64729. return PostProcess;
  64730. }());
  64731. BABYLON.PostProcess = PostProcess;
  64732. })(BABYLON || (BABYLON = {}));
  64733. //# sourceMappingURL=babylon.postProcess.js.map
  64734. var BABYLON;
  64735. (function (BABYLON) {
  64736. var PassPostProcess = /** @class */ (function (_super) {
  64737. __extends(PassPostProcess, _super);
  64738. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64739. if (camera === void 0) { camera = null; }
  64740. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64741. if (blockCompilation === void 0) { blockCompilation = false; }
  64742. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64743. }
  64744. return PassPostProcess;
  64745. }(BABYLON.PostProcess));
  64746. BABYLON.PassPostProcess = PassPostProcess;
  64747. })(BABYLON || (BABYLON = {}));
  64748. //# sourceMappingURL=babylon.passPostProcess.js.map
  64749. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64750. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64751. s = arguments[i];
  64752. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64753. t[p] = s[p];
  64754. }
  64755. return t;
  64756. };
  64757. var BABYLON;
  64758. (function (BABYLON) {
  64759. /**
  64760. * Default implementation IShadowGenerator.
  64761. * This is the main object responsible of generating shadows in the framework.
  64762. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64763. */
  64764. var ShadowGenerator = /** @class */ (function () {
  64765. /**
  64766. * Creates a ShadowGenerator object.
  64767. * A ShadowGenerator is the required tool to use the shadows.
  64768. * Each light casting shadows needs to use its own ShadowGenerator.
  64769. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64770. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64771. * @param light The light object generating the shadows.
  64772. * @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.
  64773. */
  64774. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64775. this._bias = 0.00005;
  64776. this._normalBias = 0;
  64777. this._blurBoxOffset = 1;
  64778. this._blurScale = 2;
  64779. this._blurKernel = 1;
  64780. this._useKernelBlur = false;
  64781. this._filter = ShadowGenerator.FILTER_NONE;
  64782. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64783. this._contactHardeningLightSizeUVRatio = 0.1;
  64784. this._darkness = 0;
  64785. this._transparencyShadow = false;
  64786. /**
  64787. * Controls the extent to which the shadows fade out at the edge of the frustum
  64788. * Used only by directionals and spots
  64789. */
  64790. this.frustumEdgeFalloff = 0;
  64791. /**
  64792. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64793. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64794. * It might on the other hand introduce peter panning.
  64795. */
  64796. this.forceBackFacesOnly = false;
  64797. this._lightDirection = BABYLON.Vector3.Zero();
  64798. this._viewMatrix = BABYLON.Matrix.Zero();
  64799. this._projectionMatrix = BABYLON.Matrix.Zero();
  64800. this._transformMatrix = BABYLON.Matrix.Zero();
  64801. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64802. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64803. this._currentFaceIndex = 0;
  64804. this._currentFaceIndexCache = 0;
  64805. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64806. this._mapSize = mapSize;
  64807. this._light = light;
  64808. this._scene = light.getScene();
  64809. light._shadowGenerator = this;
  64810. // Texture type fallback from float to int if not supported.
  64811. var caps = this._scene.getEngine().getCaps();
  64812. if (!useFullFloatFirst) {
  64813. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64814. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64815. }
  64816. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64817. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64818. }
  64819. else {
  64820. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64821. }
  64822. }
  64823. else {
  64824. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64825. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64826. }
  64827. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64828. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64829. }
  64830. else {
  64831. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64832. }
  64833. }
  64834. this._initializeGenerator();
  64835. this._applyFilterValues();
  64836. }
  64837. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64838. /**
  64839. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64840. */
  64841. get: function () {
  64842. return this._bias;
  64843. },
  64844. /**
  64845. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64846. */
  64847. set: function (bias) {
  64848. this._bias = bias;
  64849. },
  64850. enumerable: true,
  64851. configurable: true
  64852. });
  64853. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64854. /**
  64855. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64856. */
  64857. get: function () {
  64858. return this._normalBias;
  64859. },
  64860. /**
  64861. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64862. */
  64863. set: function (normalBias) {
  64864. this._normalBias = normalBias;
  64865. },
  64866. enumerable: true,
  64867. configurable: true
  64868. });
  64869. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64870. /**
  64871. * Gets the blur box offset: offset applied during the blur pass.
  64872. * Only usefull if useKernelBlur = false
  64873. */
  64874. get: function () {
  64875. return this._blurBoxOffset;
  64876. },
  64877. /**
  64878. * Sets the blur box offset: offset applied during the blur pass.
  64879. * Only usefull if useKernelBlur = false
  64880. */
  64881. set: function (value) {
  64882. if (this._blurBoxOffset === value) {
  64883. return;
  64884. }
  64885. this._blurBoxOffset = value;
  64886. this._disposeBlurPostProcesses();
  64887. },
  64888. enumerable: true,
  64889. configurable: true
  64890. });
  64891. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64892. /**
  64893. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64894. * 2 means half of the size.
  64895. */
  64896. get: function () {
  64897. return this._blurScale;
  64898. },
  64899. /**
  64900. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64901. * 2 means half of the size.
  64902. */
  64903. set: function (value) {
  64904. if (this._blurScale === value) {
  64905. return;
  64906. }
  64907. this._blurScale = value;
  64908. this._disposeBlurPostProcesses();
  64909. },
  64910. enumerable: true,
  64911. configurable: true
  64912. });
  64913. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64914. /**
  64915. * Gets the blur kernel: kernel size of the blur pass.
  64916. * Only usefull if useKernelBlur = true
  64917. */
  64918. get: function () {
  64919. return this._blurKernel;
  64920. },
  64921. /**
  64922. * Sets the blur kernel: kernel size of the blur pass.
  64923. * Only usefull if useKernelBlur = true
  64924. */
  64925. set: function (value) {
  64926. if (this._blurKernel === value) {
  64927. return;
  64928. }
  64929. this._blurKernel = value;
  64930. this._disposeBlurPostProcesses();
  64931. },
  64932. enumerable: true,
  64933. configurable: true
  64934. });
  64935. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64936. /**
  64937. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64938. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64939. */
  64940. get: function () {
  64941. return this._useKernelBlur;
  64942. },
  64943. /**
  64944. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64945. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64946. */
  64947. set: function (value) {
  64948. if (this._useKernelBlur === value) {
  64949. return;
  64950. }
  64951. this._useKernelBlur = value;
  64952. this._disposeBlurPostProcesses();
  64953. },
  64954. enumerable: true,
  64955. configurable: true
  64956. });
  64957. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  64958. /**
  64959. * Gets the depth scale used in ESM mode.
  64960. */
  64961. get: function () {
  64962. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  64963. },
  64964. /**
  64965. * Sets the depth scale used in ESM mode.
  64966. * This can override the scale stored on the light.
  64967. */
  64968. set: function (value) {
  64969. this._depthScale = value;
  64970. },
  64971. enumerable: true,
  64972. configurable: true
  64973. });
  64974. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  64975. /**
  64976. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  64977. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64978. */
  64979. get: function () {
  64980. return this._filter;
  64981. },
  64982. /**
  64983. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64984. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64985. */
  64986. set: function (value) {
  64987. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64988. if (this._light.needCube()) {
  64989. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64990. this.useExponentialShadowMap = true;
  64991. return;
  64992. }
  64993. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64994. this.useCloseExponentialShadowMap = true;
  64995. return;
  64996. }
  64997. // PCF on cubemap would also be expensive
  64998. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64999. this.usePoissonSampling = true;
  65000. return;
  65001. }
  65002. }
  65003. // Weblg1 fallback for PCF.
  65004. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65005. if (this._scene.getEngine().webGLVersion === 1) {
  65006. this.usePoissonSampling = true;
  65007. return;
  65008. }
  65009. }
  65010. if (this._filter === value) {
  65011. return;
  65012. }
  65013. this._filter = value;
  65014. this._disposeBlurPostProcesses();
  65015. this._applyFilterValues();
  65016. this._light._markMeshesAsLightDirty();
  65017. },
  65018. enumerable: true,
  65019. configurable: true
  65020. });
  65021. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65022. /**
  65023. * Gets if the current filter is set to Poisson Sampling.
  65024. */
  65025. get: function () {
  65026. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65027. },
  65028. /**
  65029. * Sets the current filter to Poisson Sampling.
  65030. */
  65031. set: function (value) {
  65032. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65033. return;
  65034. }
  65035. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65036. },
  65037. enumerable: true,
  65038. configurable: true
  65039. });
  65040. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65041. /**
  65042. * Gets if the current filter is set to VSM.
  65043. * DEPRECATED. Should use useExponentialShadowMap instead.
  65044. */
  65045. get: function () {
  65046. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65047. return this.useExponentialShadowMap;
  65048. },
  65049. /**
  65050. * Sets the current filter is to VSM.
  65051. * DEPRECATED. Should use useExponentialShadowMap instead.
  65052. */
  65053. set: function (value) {
  65054. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65055. this.useExponentialShadowMap = value;
  65056. },
  65057. enumerable: true,
  65058. configurable: true
  65059. });
  65060. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65061. /**
  65062. * Gets if the current filter is set to blurred VSM.
  65063. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65064. */
  65065. get: function () {
  65066. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65067. return this.useBlurExponentialShadowMap;
  65068. },
  65069. /**
  65070. * Sets the current filter is to blurred VSM.
  65071. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65072. */
  65073. set: function (value) {
  65074. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65075. this.useBlurExponentialShadowMap = value;
  65076. },
  65077. enumerable: true,
  65078. configurable: true
  65079. });
  65080. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65081. /**
  65082. * Gets if the current filter is set to ESM.
  65083. */
  65084. get: function () {
  65085. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65086. },
  65087. /**
  65088. * Sets the current filter is to ESM.
  65089. */
  65090. set: function (value) {
  65091. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65092. return;
  65093. }
  65094. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65095. },
  65096. enumerable: true,
  65097. configurable: true
  65098. });
  65099. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65100. /**
  65101. * Gets if the current filter is set to filtered ESM.
  65102. */
  65103. get: function () {
  65104. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65105. },
  65106. /**
  65107. * Gets if the current filter is set to filtered ESM.
  65108. */
  65109. set: function (value) {
  65110. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65111. return;
  65112. }
  65113. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65114. },
  65115. enumerable: true,
  65116. configurable: true
  65117. });
  65118. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65119. /**
  65120. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65121. * exponential to prevent steep falloff artifacts).
  65122. */
  65123. get: function () {
  65124. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65125. },
  65126. /**
  65127. * Sets the current filter to "close ESM" (using the inverse of the
  65128. * exponential to prevent steep falloff artifacts).
  65129. */
  65130. set: function (value) {
  65131. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65132. return;
  65133. }
  65134. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65135. },
  65136. enumerable: true,
  65137. configurable: true
  65138. });
  65139. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65140. /**
  65141. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65142. * exponential to prevent steep falloff artifacts).
  65143. */
  65144. get: function () {
  65145. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65146. },
  65147. /**
  65148. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65149. * exponential to prevent steep falloff artifacts).
  65150. */
  65151. set: function (value) {
  65152. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65153. return;
  65154. }
  65155. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65156. },
  65157. enumerable: true,
  65158. configurable: true
  65159. });
  65160. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65161. /**
  65162. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65163. */
  65164. get: function () {
  65165. return this.filter === ShadowGenerator.FILTER_PCF;
  65166. },
  65167. /**
  65168. * Sets the current filter to "PCF" (percentage closer filtering).
  65169. */
  65170. set: function (value) {
  65171. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65172. return;
  65173. }
  65174. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65175. },
  65176. enumerable: true,
  65177. configurable: true
  65178. });
  65179. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65180. /**
  65181. * Gets the PCF or PCSS Quality.
  65182. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65183. */
  65184. get: function () {
  65185. return this._filteringQuality;
  65186. },
  65187. /**
  65188. * Sets the PCF or PCSS Quality.
  65189. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65190. */
  65191. set: function (filteringQuality) {
  65192. this._filteringQuality = filteringQuality;
  65193. },
  65194. enumerable: true,
  65195. configurable: true
  65196. });
  65197. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65198. /**
  65199. * Gets if the current filter is set to "PCSS" (contact hardening).
  65200. */
  65201. get: function () {
  65202. return this.filter === ShadowGenerator.FILTER_PCSS;
  65203. },
  65204. /**
  65205. * Sets the current filter to "PCSS" (contact hardening).
  65206. */
  65207. set: function (value) {
  65208. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65209. return;
  65210. }
  65211. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65212. },
  65213. enumerable: true,
  65214. configurable: true
  65215. });
  65216. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65217. /**
  65218. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65219. * Using a ratio helps keeping shape stability independently of the map size.
  65220. *
  65221. * It does not account for the light projection as it was having too much
  65222. * instability during the light setup or during light position changes.
  65223. *
  65224. * Only valid if useContactHardeningShadow is true.
  65225. */
  65226. get: function () {
  65227. return this._contactHardeningLightSizeUVRatio;
  65228. },
  65229. /**
  65230. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65231. * Using a ratio helps keeping shape stability independently of the map size.
  65232. *
  65233. * It does not account for the light projection as it was having too much
  65234. * instability during the light setup or during light position changes.
  65235. *
  65236. * Only valid if useContactHardeningShadow is true.
  65237. */
  65238. set: function (contactHardeningLightSizeUVRatio) {
  65239. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65240. },
  65241. enumerable: true,
  65242. configurable: true
  65243. });
  65244. /**
  65245. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65246. * 0 means strongest and 1 would means no shadow.
  65247. * @returns the darkness.
  65248. */
  65249. ShadowGenerator.prototype.getDarkness = function () {
  65250. return this._darkness;
  65251. };
  65252. /**
  65253. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65254. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65255. * @returns the shadow generator allowing fluent coding.
  65256. */
  65257. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65258. if (darkness >= 1.0)
  65259. this._darkness = 1.0;
  65260. else if (darkness <= 0.0)
  65261. this._darkness = 0.0;
  65262. else
  65263. this._darkness = darkness;
  65264. return this;
  65265. };
  65266. /**
  65267. * Sets the ability to have transparent shadow (boolean).
  65268. * @param transparent True if transparent else False
  65269. * @returns the shadow generator allowing fluent coding
  65270. */
  65271. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65272. this._transparencyShadow = transparent;
  65273. return this;
  65274. };
  65275. /**
  65276. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65277. * @returns The render target texture if present otherwise, null
  65278. */
  65279. ShadowGenerator.prototype.getShadowMap = function () {
  65280. return this._shadowMap;
  65281. };
  65282. /**
  65283. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65284. * @returns The render target texture if the shadow map is present otherwise, null
  65285. */
  65286. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65287. if (this._shadowMap2) {
  65288. return this._shadowMap2;
  65289. }
  65290. return this._shadowMap;
  65291. };
  65292. /**
  65293. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65294. * @param mesh Mesh to add
  65295. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65296. * @returns the Shadow Generator itself
  65297. */
  65298. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65299. if (includeDescendants === void 0) { includeDescendants = true; }
  65300. if (!this._shadowMap) {
  65301. return this;
  65302. }
  65303. if (!this._shadowMap.renderList) {
  65304. this._shadowMap.renderList = [];
  65305. }
  65306. this._shadowMap.renderList.push(mesh);
  65307. if (includeDescendants) {
  65308. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65309. }
  65310. return this;
  65311. var _a;
  65312. };
  65313. /**
  65314. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65315. * @param mesh Mesh to remove
  65316. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65317. * @returns the Shadow Generator itself
  65318. */
  65319. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65320. if (includeDescendants === void 0) { includeDescendants = true; }
  65321. if (!this._shadowMap || !this._shadowMap.renderList) {
  65322. return this;
  65323. }
  65324. var index = this._shadowMap.renderList.indexOf(mesh);
  65325. if (index !== -1) {
  65326. this._shadowMap.renderList.splice(index, 1);
  65327. }
  65328. if (includeDescendants) {
  65329. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65330. var child = _a[_i];
  65331. this.removeShadowCaster(child);
  65332. }
  65333. }
  65334. return this;
  65335. };
  65336. /**
  65337. * Returns the associated light object.
  65338. * @returns the light generating the shadow
  65339. */
  65340. ShadowGenerator.prototype.getLight = function () {
  65341. return this._light;
  65342. };
  65343. ShadowGenerator.prototype._initializeGenerator = function () {
  65344. this._light._markMeshesAsLightDirty();
  65345. this._initializeShadowMap();
  65346. };
  65347. ShadowGenerator.prototype._initializeShadowMap = function () {
  65348. var _this = this;
  65349. // Render target
  65350. var engine = this._scene.getEngine();
  65351. if (engine.webGLVersion > 1) {
  65352. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65353. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65354. }
  65355. else {
  65356. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65357. }
  65358. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65359. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65360. this._shadowMap.anisotropicFilteringLevel = 1;
  65361. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65362. this._shadowMap.renderParticles = false;
  65363. this._shadowMap.ignoreCameraViewport = true;
  65364. // Record Face Index before render.
  65365. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65366. _this._currentFaceIndex = faceIndex;
  65367. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65368. engine.setColorWrite(false);
  65369. }
  65370. });
  65371. // Custom render function.
  65372. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65373. // Blur if required afer render.
  65374. this._shadowMap.onAfterUnbindObservable.add(function () {
  65375. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65376. engine.setColorWrite(true);
  65377. }
  65378. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65379. return;
  65380. }
  65381. var shadowMap = _this.getShadowMapForRendering();
  65382. if (shadowMap) {
  65383. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65384. }
  65385. });
  65386. // Clear according to the chosen filter.
  65387. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65388. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65389. this._shadowMap.onClearObservable.add(function (engine) {
  65390. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65391. engine.clear(clearOne, false, true, false);
  65392. }
  65393. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65394. engine.clear(clearZero, true, true, false);
  65395. }
  65396. else {
  65397. engine.clear(clearOne, true, true, false);
  65398. }
  65399. });
  65400. };
  65401. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65402. var _this = this;
  65403. var engine = this._scene.getEngine();
  65404. var targetSize = this._mapSize / this.blurScale;
  65405. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65406. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65407. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65408. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65409. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65410. }
  65411. if (this.useKernelBlur) {
  65412. 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);
  65413. this._kernelBlurXPostprocess.width = targetSize;
  65414. this._kernelBlurXPostprocess.height = targetSize;
  65415. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65416. effect.setTexture("textureSampler", _this._shadowMap);
  65417. });
  65418. 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);
  65419. this._kernelBlurXPostprocess.autoClear = false;
  65420. this._kernelBlurYPostprocess.autoClear = false;
  65421. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65422. this._kernelBlurXPostprocess.packedFloat = true;
  65423. this._kernelBlurYPostprocess.packedFloat = true;
  65424. }
  65425. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65426. }
  65427. else {
  65428. 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);
  65429. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65430. effect.setFloat2("screenSize", targetSize, targetSize);
  65431. effect.setTexture("textureSampler", _this._shadowMap);
  65432. });
  65433. this._boxBlurPostprocess.autoClear = false;
  65434. this._blurPostProcesses = [this._boxBlurPostprocess];
  65435. }
  65436. };
  65437. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65438. var index;
  65439. var engine = this._scene.getEngine();
  65440. if (depthOnlySubMeshes.length) {
  65441. engine.setColorWrite(false);
  65442. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65443. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65444. }
  65445. engine.setColorWrite(true);
  65446. }
  65447. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65448. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65449. }
  65450. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65451. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65452. }
  65453. if (this._transparencyShadow) {
  65454. for (index = 0; index < transparentSubMeshes.length; index++) {
  65455. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65456. }
  65457. }
  65458. };
  65459. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65460. var _this = this;
  65461. var mesh = subMesh.getRenderingMesh();
  65462. var scene = this._scene;
  65463. var engine = scene.getEngine();
  65464. var material = subMesh.getMaterial();
  65465. if (!material) {
  65466. return;
  65467. }
  65468. // Culling
  65469. engine.setState(material.backFaceCulling);
  65470. // Managing instances
  65471. var batch = mesh._getInstancesRenderList(subMesh._id);
  65472. if (batch.mustReturn) {
  65473. return;
  65474. }
  65475. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65476. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65477. engine.enableEffect(this._effect);
  65478. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65479. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65480. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65481. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65482. this._effect.setVector3("lightData", this._cachedDirection);
  65483. }
  65484. else {
  65485. this._effect.setVector3("lightData", this._cachedPosition);
  65486. }
  65487. if (scene.activeCamera) {
  65488. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65489. }
  65490. // Alpha test
  65491. if (material && material.needAlphaTesting()) {
  65492. var alphaTexture = material.getAlphaTestTexture();
  65493. if (alphaTexture) {
  65494. this._effect.setTexture("diffuseSampler", alphaTexture);
  65495. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65496. }
  65497. }
  65498. // Bones
  65499. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65500. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65501. }
  65502. // Morph targets
  65503. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65504. if (this.forceBackFacesOnly) {
  65505. engine.setState(true, 0, false, true);
  65506. }
  65507. // Draw
  65508. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65509. if (this.forceBackFacesOnly) {
  65510. engine.setState(true, 0, false, false);
  65511. }
  65512. }
  65513. else {
  65514. // Need to reset refresh rate of the shadowMap
  65515. if (this._shadowMap) {
  65516. this._shadowMap.resetRefreshCounter();
  65517. }
  65518. }
  65519. };
  65520. ShadowGenerator.prototype._applyFilterValues = function () {
  65521. if (!this._shadowMap) {
  65522. return;
  65523. }
  65524. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65525. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65526. }
  65527. else {
  65528. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65529. }
  65530. };
  65531. /**
  65532. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65533. * @param onCompiled Callback triggered at the and of the effects compilation
  65534. * @param options Sets of optional options forcing the compilation with different modes
  65535. */
  65536. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65537. var _this = this;
  65538. var localOptions = __assign({ useInstances: false }, options);
  65539. var shadowMap = this.getShadowMap();
  65540. if (!shadowMap) {
  65541. if (onCompiled) {
  65542. onCompiled(this);
  65543. }
  65544. return;
  65545. }
  65546. var renderList = shadowMap.renderList;
  65547. if (!renderList) {
  65548. if (onCompiled) {
  65549. onCompiled(this);
  65550. }
  65551. return;
  65552. }
  65553. var subMeshes = new Array();
  65554. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65555. var mesh = renderList_1[_i];
  65556. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65557. }
  65558. if (subMeshes.length === 0) {
  65559. if (onCompiled) {
  65560. onCompiled(this);
  65561. }
  65562. return;
  65563. }
  65564. var currentIndex = 0;
  65565. var checkReady = function () {
  65566. if (!_this._scene || !_this._scene.getEngine()) {
  65567. return;
  65568. }
  65569. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65570. currentIndex++;
  65571. if (currentIndex >= subMeshes.length) {
  65572. if (onCompiled) {
  65573. onCompiled(_this);
  65574. }
  65575. return;
  65576. }
  65577. }
  65578. setTimeout(checkReady, 16);
  65579. };
  65580. checkReady();
  65581. };
  65582. /**
  65583. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65584. * @param options Sets of optional options forcing the compilation with different modes
  65585. * @returns A promise that resolves when the compilation completes
  65586. */
  65587. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65588. var _this = this;
  65589. return new Promise(function (resolve) {
  65590. _this.forceCompilation(function () {
  65591. resolve();
  65592. }, options);
  65593. });
  65594. };
  65595. /**
  65596. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65597. * @param subMesh The submesh we want to render in the shadow map
  65598. * @param useInstances Defines wether will draw in the map using instances
  65599. * @returns true if ready otherwise, false
  65600. */
  65601. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65602. var defines = [];
  65603. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65604. defines.push("#define FLOAT");
  65605. }
  65606. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65607. defines.push("#define ESM");
  65608. }
  65609. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65610. defines.push("#define DEPTHTEXTURE");
  65611. }
  65612. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65613. var mesh = subMesh.getMesh();
  65614. var material = subMesh.getMaterial();
  65615. // Normal bias.
  65616. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65617. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65618. defines.push("#define NORMAL");
  65619. if (mesh.nonUniformScaling) {
  65620. defines.push("#define NONUNIFORMSCALING");
  65621. }
  65622. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65623. defines.push("#define DIRECTIONINLIGHTDATA");
  65624. }
  65625. }
  65626. // Alpha test
  65627. if (material && material.needAlphaTesting()) {
  65628. var alphaTexture = material.getAlphaTestTexture();
  65629. if (alphaTexture) {
  65630. defines.push("#define ALPHATEST");
  65631. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65632. attribs.push(BABYLON.VertexBuffer.UVKind);
  65633. defines.push("#define UV1");
  65634. }
  65635. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65636. if (alphaTexture.coordinatesIndex === 1) {
  65637. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65638. defines.push("#define UV2");
  65639. }
  65640. }
  65641. }
  65642. }
  65643. // Bones
  65644. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65645. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65646. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65647. if (mesh.numBoneInfluencers > 4) {
  65648. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65649. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65650. }
  65651. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65652. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65653. }
  65654. else {
  65655. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65656. }
  65657. // Morph targets
  65658. var manager = mesh.morphTargetManager;
  65659. var morphInfluencers = 0;
  65660. if (manager) {
  65661. if (manager.numInfluencers > 0) {
  65662. defines.push("#define MORPHTARGETS");
  65663. morphInfluencers = manager.numInfluencers;
  65664. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65665. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65666. }
  65667. }
  65668. // Instances
  65669. if (useInstances) {
  65670. defines.push("#define INSTANCES");
  65671. attribs.push("world0");
  65672. attribs.push("world1");
  65673. attribs.push("world2");
  65674. attribs.push("world3");
  65675. }
  65676. // Get correct effect
  65677. var join = defines.join("\n");
  65678. if (this._cachedDefines !== join) {
  65679. this._cachedDefines = join;
  65680. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65681. }
  65682. if (!this._effect.isReady()) {
  65683. return false;
  65684. }
  65685. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65686. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65687. this._initializeBlurRTTAndPostProcesses();
  65688. }
  65689. }
  65690. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65691. return false;
  65692. }
  65693. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65694. return false;
  65695. }
  65696. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65697. return false;
  65698. }
  65699. return true;
  65700. };
  65701. /**
  65702. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65703. * @param defines Defines of the material we want to update
  65704. * @param lightIndex Index of the light in the enabled light list of the material
  65705. */
  65706. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65707. var scene = this._scene;
  65708. var light = this._light;
  65709. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65710. return;
  65711. }
  65712. defines["SHADOW" + lightIndex] = true;
  65713. if (this.useContactHardeningShadow) {
  65714. defines["SHADOWPCSS" + lightIndex] = true;
  65715. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65716. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65717. }
  65718. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65719. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65720. }
  65721. // else default to high.
  65722. }
  65723. if (this.usePercentageCloserFiltering) {
  65724. defines["SHADOWPCF" + lightIndex] = true;
  65725. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65726. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65727. }
  65728. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65729. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65730. }
  65731. // else default to high.
  65732. }
  65733. else if (this.usePoissonSampling) {
  65734. defines["SHADOWPOISSON" + lightIndex] = true;
  65735. }
  65736. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65737. defines["SHADOWESM" + lightIndex] = true;
  65738. }
  65739. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65740. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65741. }
  65742. if (light.needCube()) {
  65743. defines["SHADOWCUBE" + lightIndex] = true;
  65744. }
  65745. };
  65746. /**
  65747. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65748. * defined in the generator but impacting the effect).
  65749. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65750. * @param effect The effect we are binfing the information for
  65751. */
  65752. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65753. var light = this._light;
  65754. var scene = this._scene;
  65755. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65756. return;
  65757. }
  65758. var camera = scene.activeCamera;
  65759. if (!camera) {
  65760. return;
  65761. }
  65762. var shadowMap = this.getShadowMap();
  65763. if (!shadowMap) {
  65764. return;
  65765. }
  65766. if (!light.needCube()) {
  65767. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65768. }
  65769. // Only PCF uses depth stencil texture.
  65770. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65771. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65772. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65773. }
  65774. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65775. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65776. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65777. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65778. }
  65779. else {
  65780. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65781. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65782. }
  65783. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65784. };
  65785. /**
  65786. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65787. * (eq to shadow prjection matrix * light transform matrix)
  65788. * @returns The transform matrix used to create the shadow map
  65789. */
  65790. ShadowGenerator.prototype.getTransformMatrix = function () {
  65791. var scene = this._scene;
  65792. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65793. return this._transformMatrix;
  65794. }
  65795. this._currentRenderID = scene.getRenderId();
  65796. this._currentFaceIndexCache = this._currentFaceIndex;
  65797. var lightPosition = this._light.position;
  65798. if (this._light.computeTransformedInformation()) {
  65799. lightPosition = this._light.transformedPosition;
  65800. }
  65801. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65802. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65803. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65804. }
  65805. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65806. this._cachedPosition.copyFrom(lightPosition);
  65807. this._cachedDirection.copyFrom(this._lightDirection);
  65808. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65809. var shadowMap = this.getShadowMap();
  65810. if (shadowMap) {
  65811. var renderList = shadowMap.renderList;
  65812. if (renderList) {
  65813. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65814. }
  65815. }
  65816. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65817. }
  65818. return this._transformMatrix;
  65819. };
  65820. /**
  65821. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65822. * Cube and 2D textures for instance.
  65823. */
  65824. ShadowGenerator.prototype.recreateShadowMap = function () {
  65825. var shadowMap = this._shadowMap;
  65826. if (!shadowMap) {
  65827. return;
  65828. }
  65829. // Track render list.
  65830. var renderList = shadowMap.renderList;
  65831. // Clean up existing data.
  65832. this._disposeRTTandPostProcesses();
  65833. // Reinitializes.
  65834. this._initializeGenerator();
  65835. // Reaffect the filter to ensure a correct fallback if necessary.
  65836. this.filter = this.filter;
  65837. // Reaffect the filter.
  65838. this._applyFilterValues();
  65839. // Reaffect Render List.
  65840. this._shadowMap.renderList = renderList;
  65841. };
  65842. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65843. if (this._shadowMap2) {
  65844. this._shadowMap2.dispose();
  65845. this._shadowMap2 = null;
  65846. }
  65847. if (this._boxBlurPostprocess) {
  65848. this._boxBlurPostprocess.dispose();
  65849. this._boxBlurPostprocess = null;
  65850. }
  65851. if (this._kernelBlurXPostprocess) {
  65852. this._kernelBlurXPostprocess.dispose();
  65853. this._kernelBlurXPostprocess = null;
  65854. }
  65855. if (this._kernelBlurYPostprocess) {
  65856. this._kernelBlurYPostprocess.dispose();
  65857. this._kernelBlurYPostprocess = null;
  65858. }
  65859. this._blurPostProcesses = [];
  65860. };
  65861. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65862. if (this._shadowMap) {
  65863. this._shadowMap.dispose();
  65864. this._shadowMap = null;
  65865. }
  65866. this._disposeBlurPostProcesses();
  65867. };
  65868. /**
  65869. * Disposes the ShadowGenerator.
  65870. * Returns nothing.
  65871. */
  65872. ShadowGenerator.prototype.dispose = function () {
  65873. this._disposeRTTandPostProcesses();
  65874. if (this._light) {
  65875. this._light._shadowGenerator = null;
  65876. this._light._markMeshesAsLightDirty();
  65877. }
  65878. };
  65879. /**
  65880. * Serializes the shadow generator setup to a json object.
  65881. * @returns The serialized JSON object
  65882. */
  65883. ShadowGenerator.prototype.serialize = function () {
  65884. var serializationObject = {};
  65885. var shadowMap = this.getShadowMap();
  65886. if (!shadowMap) {
  65887. return serializationObject;
  65888. }
  65889. serializationObject.lightId = this._light.id;
  65890. serializationObject.mapSize = shadowMap.getRenderSize();
  65891. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65892. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65893. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65894. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65895. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65896. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65897. serializationObject.depthScale = this.depthScale;
  65898. serializationObject.darkness = this.getDarkness();
  65899. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65900. serializationObject.blurKernel = this.blurKernel;
  65901. serializationObject.blurScale = this.blurScale;
  65902. serializationObject.useKernelBlur = this.useKernelBlur;
  65903. serializationObject.transparencyShadow = this._transparencyShadow;
  65904. serializationObject.bias = this.bias;
  65905. serializationObject.normalBias = this.normalBias;
  65906. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65907. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65908. serializationObject.filteringQuality = this.filteringQuality;
  65909. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65910. serializationObject.renderList = [];
  65911. if (shadowMap.renderList) {
  65912. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65913. var mesh = shadowMap.renderList[meshIndex];
  65914. serializationObject.renderList.push(mesh.id);
  65915. }
  65916. }
  65917. return serializationObject;
  65918. };
  65919. /**
  65920. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65921. * @param parsedShadowGenerator The JSON object to parse
  65922. * @param scene The scene to create the shadow map for
  65923. * @returns The parsed shadow generator
  65924. */
  65925. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65926. //casting to point light, as light is missing the position attr and typescript complains.
  65927. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65928. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65929. var shadowMap = shadowGenerator.getShadowMap();
  65930. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65931. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65932. meshes.forEach(function (mesh) {
  65933. if (!shadowMap) {
  65934. return;
  65935. }
  65936. if (!shadowMap.renderList) {
  65937. shadowMap.renderList = [];
  65938. }
  65939. shadowMap.renderList.push(mesh);
  65940. });
  65941. }
  65942. if (parsedShadowGenerator.usePoissonSampling) {
  65943. shadowGenerator.usePoissonSampling = true;
  65944. }
  65945. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65946. shadowGenerator.useExponentialShadowMap = true;
  65947. }
  65948. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65949. shadowGenerator.useBlurExponentialShadowMap = true;
  65950. }
  65951. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65952. shadowGenerator.useCloseExponentialShadowMap = true;
  65953. }
  65954. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  65955. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  65956. }
  65957. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  65958. shadowGenerator.usePercentageCloserFiltering = true;
  65959. }
  65960. else if (parsedShadowGenerator.useContactHardeningShadow) {
  65961. shadowGenerator.useContactHardeningShadow = true;
  65962. }
  65963. if (parsedShadowGenerator.filteringQuality) {
  65964. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  65965. }
  65966. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  65967. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  65968. }
  65969. // Backward compat
  65970. else if (parsedShadowGenerator.useVarianceShadowMap) {
  65971. shadowGenerator.useExponentialShadowMap = true;
  65972. }
  65973. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  65974. shadowGenerator.useBlurExponentialShadowMap = true;
  65975. }
  65976. if (parsedShadowGenerator.depthScale) {
  65977. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  65978. }
  65979. if (parsedShadowGenerator.blurScale) {
  65980. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65981. }
  65982. if (parsedShadowGenerator.blurBoxOffset) {
  65983. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65984. }
  65985. if (parsedShadowGenerator.useKernelBlur) {
  65986. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65987. }
  65988. if (parsedShadowGenerator.blurKernel) {
  65989. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65990. }
  65991. if (parsedShadowGenerator.bias !== undefined) {
  65992. shadowGenerator.bias = parsedShadowGenerator.bias;
  65993. }
  65994. if (parsedShadowGenerator.normalBias !== undefined) {
  65995. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65996. }
  65997. if (parsedShadowGenerator.darkness) {
  65998. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  65999. }
  66000. if (parsedShadowGenerator.transparencyShadow) {
  66001. shadowGenerator.setTransparencyShadow(true);
  66002. }
  66003. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66004. return shadowGenerator;
  66005. };
  66006. /**
  66007. * Shadow generator mode None: no filtering applied.
  66008. */
  66009. ShadowGenerator.FILTER_NONE = 0;
  66010. /**
  66011. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66012. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66013. */
  66014. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66015. /**
  66016. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66017. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66018. */
  66019. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66020. /**
  66021. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66022. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66023. */
  66024. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66025. /**
  66026. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66027. * edge artifacts on steep falloff.
  66028. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66029. */
  66030. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66031. /**
  66032. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66033. * edge artifacts on steep falloff.
  66034. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66035. */
  66036. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66037. /**
  66038. * Shadow generator mode PCF: Percentage Closer Filtering
  66039. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66040. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66041. */
  66042. ShadowGenerator.FILTER_PCF = 6;
  66043. /**
  66044. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66045. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66046. * Contact Hardening
  66047. */
  66048. ShadowGenerator.FILTER_PCSS = 7;
  66049. /**
  66050. * Reserved for PCF and PCSS
  66051. * Highest Quality.
  66052. *
  66053. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66054. *
  66055. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66056. */
  66057. ShadowGenerator.QUALITY_HIGH = 0;
  66058. /**
  66059. * Reserved for PCF and PCSS
  66060. * Good tradeoff for quality/perf cross devices
  66061. *
  66062. * Execute PCF on a 3*3 kernel.
  66063. *
  66064. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66065. */
  66066. ShadowGenerator.QUALITY_MEDIUM = 1;
  66067. /**
  66068. * Reserved for PCF and PCSS
  66069. * The lowest quality but the fastest.
  66070. *
  66071. * Execute PCF on a 1*1 kernel.
  66072. *
  66073. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66074. */
  66075. ShadowGenerator.QUALITY_LOW = 2;
  66076. return ShadowGenerator;
  66077. }());
  66078. BABYLON.ShadowGenerator = ShadowGenerator;
  66079. })(BABYLON || (BABYLON = {}));
  66080. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66081. var BABYLON;
  66082. (function (BABYLON) {
  66083. var DefaultLoadingScreen = /** @class */ (function () {
  66084. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66085. if (_loadingText === void 0) { _loadingText = ""; }
  66086. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66087. var _this = this;
  66088. this._renderingCanvas = _renderingCanvas;
  66089. this._loadingText = _loadingText;
  66090. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66091. // Resize
  66092. this._resizeLoadingUI = function () {
  66093. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66094. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66095. if (!_this._loadingDiv) {
  66096. return;
  66097. }
  66098. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66099. _this._loadingDiv.style.left = canvasRect.left + "px";
  66100. _this._loadingDiv.style.top = canvasRect.top + "px";
  66101. _this._loadingDiv.style.width = canvasRect.width + "px";
  66102. _this._loadingDiv.style.height = canvasRect.height + "px";
  66103. };
  66104. }
  66105. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66106. if (this._loadingDiv) {
  66107. // Do not add a loading screen if there is already one
  66108. return;
  66109. }
  66110. this._loadingDiv = document.createElement("div");
  66111. this._loadingDiv.id = "babylonjsLoadingDiv";
  66112. this._loadingDiv.style.opacity = "0";
  66113. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66114. this._loadingDiv.style.pointerEvents = "none";
  66115. // Loading text
  66116. this._loadingTextDiv = document.createElement("div");
  66117. this._loadingTextDiv.style.position = "absolute";
  66118. this._loadingTextDiv.style.left = "0";
  66119. this._loadingTextDiv.style.top = "50%";
  66120. this._loadingTextDiv.style.marginTop = "80px";
  66121. this._loadingTextDiv.style.width = "100%";
  66122. this._loadingTextDiv.style.height = "20px";
  66123. this._loadingTextDiv.style.fontFamily = "Arial";
  66124. this._loadingTextDiv.style.fontSize = "14px";
  66125. this._loadingTextDiv.style.color = "white";
  66126. this._loadingTextDiv.style.textAlign = "center";
  66127. this._loadingTextDiv.innerHTML = "Loading";
  66128. this._loadingDiv.appendChild(this._loadingTextDiv);
  66129. //set the predefined text
  66130. this._loadingTextDiv.innerHTML = this._loadingText;
  66131. // Generating keyframes
  66132. var style = document.createElement('style');
  66133. style.type = 'text/css';
  66134. 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 }";
  66135. style.innerHTML = keyFrames;
  66136. document.getElementsByTagName('head')[0].appendChild(style);
  66137. // Loading img
  66138. var imgBack = new Image();
  66139. 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";
  66140. imgBack.style.position = "absolute";
  66141. imgBack.style.left = "50%";
  66142. imgBack.style.top = "50%";
  66143. imgBack.style.marginLeft = "-60px";
  66144. imgBack.style.marginTop = "-60px";
  66145. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66146. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66147. imgBack.style.transformOrigin = "50% 50%";
  66148. imgBack.style.webkitTransformOrigin = "50% 50%";
  66149. this._loadingDiv.appendChild(imgBack);
  66150. this._resizeLoadingUI();
  66151. window.addEventListener("resize", this._resizeLoadingUI);
  66152. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66153. document.body.appendChild(this._loadingDiv);
  66154. this._loadingDiv.style.opacity = "1";
  66155. };
  66156. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66157. var _this = this;
  66158. if (!this._loadingDiv) {
  66159. return;
  66160. }
  66161. var onTransitionEnd = function () {
  66162. if (!_this._loadingDiv) {
  66163. return;
  66164. }
  66165. document.body.removeChild(_this._loadingDiv);
  66166. window.removeEventListener("resize", _this._resizeLoadingUI);
  66167. _this._loadingDiv = null;
  66168. };
  66169. this._loadingDiv.style.opacity = "0";
  66170. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66171. };
  66172. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66173. set: function (text) {
  66174. this._loadingText = text;
  66175. if (this._loadingTextDiv) {
  66176. this._loadingTextDiv.innerHTML = this._loadingText;
  66177. }
  66178. },
  66179. enumerable: true,
  66180. configurable: true
  66181. });
  66182. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66183. get: function () {
  66184. return this._loadingDivBackgroundColor;
  66185. },
  66186. set: function (color) {
  66187. this._loadingDivBackgroundColor = color;
  66188. if (!this._loadingDiv) {
  66189. return;
  66190. }
  66191. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66192. },
  66193. enumerable: true,
  66194. configurable: true
  66195. });
  66196. return DefaultLoadingScreen;
  66197. }());
  66198. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66199. })(BABYLON || (BABYLON = {}));
  66200. //# sourceMappingURL=babylon.loadingScreen.js.map
  66201. var BABYLON;
  66202. (function (BABYLON) {
  66203. var SceneLoaderProgressEvent = /** @class */ (function () {
  66204. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66205. this.lengthComputable = lengthComputable;
  66206. this.loaded = loaded;
  66207. this.total = total;
  66208. }
  66209. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66210. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66211. };
  66212. return SceneLoaderProgressEvent;
  66213. }());
  66214. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66215. var SceneLoader = /** @class */ (function () {
  66216. function SceneLoader() {
  66217. }
  66218. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66219. get: function () {
  66220. return 0;
  66221. },
  66222. enumerable: true,
  66223. configurable: true
  66224. });
  66225. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66226. get: function () {
  66227. return 1;
  66228. },
  66229. enumerable: true,
  66230. configurable: true
  66231. });
  66232. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66233. get: function () {
  66234. return 2;
  66235. },
  66236. enumerable: true,
  66237. configurable: true
  66238. });
  66239. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66240. get: function () {
  66241. return 3;
  66242. },
  66243. enumerable: true,
  66244. configurable: true
  66245. });
  66246. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66247. get: function () {
  66248. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66249. },
  66250. set: function (value) {
  66251. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66252. },
  66253. enumerable: true,
  66254. configurable: true
  66255. });
  66256. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66257. get: function () {
  66258. return SceneLoader._ShowLoadingScreen;
  66259. },
  66260. set: function (value) {
  66261. SceneLoader._ShowLoadingScreen = value;
  66262. },
  66263. enumerable: true,
  66264. configurable: true
  66265. });
  66266. Object.defineProperty(SceneLoader, "loggingLevel", {
  66267. get: function () {
  66268. return SceneLoader._loggingLevel;
  66269. },
  66270. set: function (value) {
  66271. SceneLoader._loggingLevel = value;
  66272. },
  66273. enumerable: true,
  66274. configurable: true
  66275. });
  66276. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66277. get: function () {
  66278. return SceneLoader._CleanBoneMatrixWeights;
  66279. },
  66280. set: function (value) {
  66281. SceneLoader._CleanBoneMatrixWeights = value;
  66282. },
  66283. enumerable: true,
  66284. configurable: true
  66285. });
  66286. SceneLoader._getDefaultPlugin = function () {
  66287. return SceneLoader._registeredPlugins[".babylon"];
  66288. };
  66289. SceneLoader._getPluginForExtension = function (extension) {
  66290. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66291. if (registeredPlugin) {
  66292. return registeredPlugin;
  66293. }
  66294. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66295. return SceneLoader._getDefaultPlugin();
  66296. };
  66297. SceneLoader._getPluginForDirectLoad = function (data) {
  66298. for (var extension in SceneLoader._registeredPlugins) {
  66299. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66300. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66301. return SceneLoader._registeredPlugins[extension];
  66302. }
  66303. }
  66304. return SceneLoader._getDefaultPlugin();
  66305. };
  66306. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66307. if (sceneFilename.name) {
  66308. sceneFilename = sceneFilename.name;
  66309. }
  66310. var queryStringPosition = sceneFilename.indexOf("?");
  66311. if (queryStringPosition !== -1) {
  66312. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66313. }
  66314. var dotPosition = sceneFilename.lastIndexOf(".");
  66315. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66316. return SceneLoader._getPluginForExtension(extension);
  66317. };
  66318. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66319. SceneLoader._getDirectLoad = function (sceneFilename) {
  66320. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66321. return sceneFilename.substr(5);
  66322. }
  66323. return null;
  66324. };
  66325. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66326. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66327. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66328. var plugin;
  66329. if (registeredPlugin.plugin.createPlugin) {
  66330. plugin = registeredPlugin.plugin.createPlugin();
  66331. }
  66332. else {
  66333. plugin = registeredPlugin.plugin;
  66334. }
  66335. var useArrayBuffer = registeredPlugin.isBinary;
  66336. var database;
  66337. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66338. var dataCallback = function (data, responseURL) {
  66339. if (scene.isDisposed) {
  66340. onError("Scene has been disposed");
  66341. return;
  66342. }
  66343. scene.database = database;
  66344. onSuccess(plugin, data, responseURL);
  66345. };
  66346. var request = null;
  66347. var pluginDisposed = false;
  66348. var onDisposeObservable = plugin.onDisposeObservable;
  66349. if (onDisposeObservable) {
  66350. onDisposeObservable.add(function () {
  66351. pluginDisposed = true;
  66352. if (request) {
  66353. request.abort();
  66354. request = null;
  66355. }
  66356. onDispose();
  66357. });
  66358. }
  66359. var manifestChecked = function () {
  66360. if (pluginDisposed) {
  66361. return;
  66362. }
  66363. var url = rootUrl + sceneFilename;
  66364. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66365. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66366. } : undefined, database, useArrayBuffer, function (request, exception) {
  66367. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66368. });
  66369. };
  66370. if (directLoad) {
  66371. dataCallback(directLoad);
  66372. return plugin;
  66373. }
  66374. if (rootUrl.indexOf("file:") === -1) {
  66375. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  66376. if (canUseOfflineSupport) {
  66377. // Also check for exceptions
  66378. var exceptionFound = false;
  66379. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66380. var regex = _a[_i];
  66381. if (regex.test(rootUrl + sceneFilename)) {
  66382. exceptionFound = true;
  66383. break;
  66384. }
  66385. }
  66386. canUseOfflineSupport = !exceptionFound;
  66387. }
  66388. if (canUseOfflineSupport) {
  66389. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66390. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  66391. }
  66392. else {
  66393. manifestChecked();
  66394. }
  66395. }
  66396. // Loading file from disk via input file or drag'n'drop
  66397. else {
  66398. var fileOrString = sceneFilename;
  66399. if (fileOrString.name) { // File
  66400. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66401. }
  66402. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66403. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66404. }
  66405. else {
  66406. onError("Unable to find file named " + sceneFilename);
  66407. }
  66408. }
  66409. return plugin;
  66410. };
  66411. // Public functions
  66412. SceneLoader.GetPluginForExtension = function (extension) {
  66413. return SceneLoader._getPluginForExtension(extension).plugin;
  66414. };
  66415. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66416. return !!SceneLoader._registeredPlugins[extension];
  66417. };
  66418. SceneLoader.RegisterPlugin = function (plugin) {
  66419. if (typeof plugin.extensions === "string") {
  66420. var extension = plugin.extensions;
  66421. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66422. plugin: plugin,
  66423. isBinary: false
  66424. };
  66425. }
  66426. else {
  66427. var extensions = plugin.extensions;
  66428. Object.keys(extensions).forEach(function (extension) {
  66429. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66430. plugin: plugin,
  66431. isBinary: extensions[extension].isBinary
  66432. };
  66433. });
  66434. }
  66435. };
  66436. /**
  66437. * Import meshes into a scene
  66438. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66439. * @param rootUrl a string that defines the root url for scene and resources
  66440. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66441. * @param scene the instance of BABYLON.Scene to append to
  66442. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66443. * @param onProgress a callback with a progress event for each file being loaded
  66444. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66445. * @param pluginExtension the extension used to determine the plugin
  66446. * @returns The loaded plugin
  66447. */
  66448. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66449. if (onSuccess === void 0) { onSuccess = null; }
  66450. if (onProgress === void 0) { onProgress = null; }
  66451. if (onError === void 0) { onError = null; }
  66452. if (pluginExtension === void 0) { pluginExtension = null; }
  66453. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66454. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66455. return null;
  66456. }
  66457. var loadingToken = {};
  66458. scene._addPendingData(loadingToken);
  66459. var disposeHandler = function () {
  66460. scene._removePendingData(loadingToken);
  66461. };
  66462. var errorHandler = function (message, exception) {
  66463. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66464. if (onError) {
  66465. onError(scene, errorMessage, exception);
  66466. }
  66467. else {
  66468. BABYLON.Tools.Error(errorMessage);
  66469. // should the exception be thrown?
  66470. }
  66471. disposeHandler();
  66472. };
  66473. var progressHandler = onProgress ? function (event) {
  66474. try {
  66475. onProgress(event);
  66476. }
  66477. catch (e) {
  66478. errorHandler("Error in onProgress callback", e);
  66479. }
  66480. } : undefined;
  66481. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66482. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66483. if (onSuccess) {
  66484. try {
  66485. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66486. }
  66487. catch (e) {
  66488. errorHandler("Error in onSuccess callback", e);
  66489. }
  66490. }
  66491. scene._removePendingData(loadingToken);
  66492. };
  66493. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66494. if (plugin.rewriteRootURL) {
  66495. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66496. }
  66497. if (sceneFilename === "") {
  66498. if (sceneFilename === "") {
  66499. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66500. }
  66501. }
  66502. if (plugin.importMesh) {
  66503. var syncedPlugin = plugin;
  66504. var meshes = new Array();
  66505. var particleSystems = new Array();
  66506. var skeletons = new Array();
  66507. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66508. return;
  66509. }
  66510. scene.loadingPluginName = plugin.name;
  66511. successHandler(meshes, particleSystems, skeletons, []);
  66512. }
  66513. else {
  66514. var asyncedPlugin = plugin;
  66515. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66516. scene.loadingPluginName = plugin.name;
  66517. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66518. }).catch(function (error) {
  66519. errorHandler(error.message, error);
  66520. });
  66521. }
  66522. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66523. };
  66524. /**
  66525. * Import meshes into a scene
  66526. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66527. * @param rootUrl a string that defines the root url for scene and resources
  66528. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66529. * @param scene the instance of BABYLON.Scene to append to
  66530. * @param onProgress a callback with a progress event for each file being loaded
  66531. * @param pluginExtension the extension used to determine the plugin
  66532. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66533. */
  66534. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66535. if (onProgress === void 0) { onProgress = null; }
  66536. if (pluginExtension === void 0) { pluginExtension = null; }
  66537. return new Promise(function (resolve, reject) {
  66538. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66539. resolve({
  66540. meshes: meshes,
  66541. particleSystems: particleSystems,
  66542. skeletons: skeletons,
  66543. animationGroups: animationGroups
  66544. });
  66545. }, onProgress, function (scene, message, exception) {
  66546. reject(exception || new Error(message));
  66547. });
  66548. });
  66549. };
  66550. /**
  66551. * Load a scene
  66552. * @param rootUrl a string that defines the root url for scene and resources
  66553. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66554. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66555. * @param onSuccess a callback with the scene when import succeeds
  66556. * @param onProgress a callback with a progress event for each file being loaded
  66557. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66558. * @param pluginExtension the extension used to determine the plugin
  66559. * @returns The loaded plugin
  66560. */
  66561. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66562. if (onSuccess === void 0) { onSuccess = null; }
  66563. if (onProgress === void 0) { onProgress = null; }
  66564. if (onError === void 0) { onError = null; }
  66565. if (pluginExtension === void 0) { pluginExtension = null; }
  66566. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66567. };
  66568. /**
  66569. * Load a scene
  66570. * @param rootUrl a string that defines the root url for scene and resources
  66571. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66572. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66573. * @param onProgress a callback with a progress event for each file being loaded
  66574. * @param pluginExtension the extension used to determine the plugin
  66575. * @returns The loaded scene
  66576. */
  66577. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66578. if (onProgress === void 0) { onProgress = null; }
  66579. if (pluginExtension === void 0) { pluginExtension = null; }
  66580. return new Promise(function (resolve, reject) {
  66581. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66582. resolve(scene);
  66583. }, onProgress, function (scene, message, exception) {
  66584. reject(exception || new Error(message));
  66585. }, pluginExtension);
  66586. });
  66587. };
  66588. /**
  66589. * Append a scene
  66590. * @param rootUrl a string that defines the root url for scene and resources
  66591. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66592. * @param scene is the instance of BABYLON.Scene to append to
  66593. * @param onSuccess a callback with the scene when import succeeds
  66594. * @param onProgress a callback with a progress event for each file being loaded
  66595. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66596. * @param pluginExtension the extension used to determine the plugin
  66597. * @returns The loaded plugin
  66598. */
  66599. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66600. if (onSuccess === void 0) { onSuccess = null; }
  66601. if (onProgress === void 0) { onProgress = null; }
  66602. if (onError === void 0) { onError = null; }
  66603. if (pluginExtension === void 0) { pluginExtension = null; }
  66604. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66605. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66606. return null;
  66607. }
  66608. if (SceneLoader.ShowLoadingScreen) {
  66609. scene.getEngine().displayLoadingUI();
  66610. }
  66611. var loadingToken = {};
  66612. scene._addPendingData(loadingToken);
  66613. var disposeHandler = function () {
  66614. scene._removePendingData(loadingToken);
  66615. scene.getEngine().hideLoadingUI();
  66616. };
  66617. var errorHandler = function (message, exception) {
  66618. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66619. if (onError) {
  66620. onError(scene, errorMessage, exception);
  66621. }
  66622. else {
  66623. BABYLON.Tools.Error(errorMessage);
  66624. // should the exception be thrown?
  66625. }
  66626. disposeHandler();
  66627. };
  66628. var progressHandler = onProgress ? function (event) {
  66629. try {
  66630. onProgress(event);
  66631. }
  66632. catch (e) {
  66633. errorHandler("Error in onProgress callback", e);
  66634. }
  66635. } : undefined;
  66636. var successHandler = function () {
  66637. if (onSuccess) {
  66638. try {
  66639. onSuccess(scene);
  66640. }
  66641. catch (e) {
  66642. errorHandler("Error in onSuccess callback", e);
  66643. }
  66644. }
  66645. scene._removePendingData(loadingToken);
  66646. };
  66647. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66648. if (sceneFilename === "") {
  66649. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66650. }
  66651. if (plugin.load) {
  66652. var syncedPlugin = plugin;
  66653. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66654. return;
  66655. }
  66656. scene.loadingPluginName = plugin.name;
  66657. successHandler();
  66658. }
  66659. else {
  66660. var asyncedPlugin = plugin;
  66661. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66662. scene.loadingPluginName = plugin.name;
  66663. successHandler();
  66664. }).catch(function (error) {
  66665. errorHandler(error.message, error);
  66666. });
  66667. }
  66668. if (SceneLoader.ShowLoadingScreen) {
  66669. scene.executeWhenReady(function () {
  66670. scene.getEngine().hideLoadingUI();
  66671. });
  66672. }
  66673. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66674. };
  66675. /**
  66676. * Append a scene
  66677. * @param rootUrl a string that defines the root url for scene and resources
  66678. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66679. * @param scene is the instance of BABYLON.Scene to append to
  66680. * @param onProgress a callback with a progress event for each file being loaded
  66681. * @param pluginExtension the extension used to determine the plugin
  66682. * @returns The given scene
  66683. */
  66684. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66685. if (onProgress === void 0) { onProgress = null; }
  66686. if (pluginExtension === void 0) { pluginExtension = null; }
  66687. return new Promise(function (resolve, reject) {
  66688. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66689. resolve(scene);
  66690. }, onProgress, function (scene, message, exception) {
  66691. reject(exception || new Error(message));
  66692. }, pluginExtension);
  66693. });
  66694. };
  66695. /**
  66696. * Load a scene into an asset container
  66697. * @param rootUrl a string that defines the root url for scene and resources
  66698. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66699. * @param scene is the instance of BABYLON.Scene to append to
  66700. * @param onSuccess a callback with the scene when import succeeds
  66701. * @param onProgress a callback with a progress event for each file being loaded
  66702. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66703. * @param pluginExtension the extension used to determine the plugin
  66704. * @returns The loaded plugin
  66705. */
  66706. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66707. if (onSuccess === void 0) { onSuccess = null; }
  66708. if (onProgress === void 0) { onProgress = null; }
  66709. if (onError === void 0) { onError = null; }
  66710. if (pluginExtension === void 0) { pluginExtension = null; }
  66711. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66712. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66713. return null;
  66714. }
  66715. var loadingToken = {};
  66716. scene._addPendingData(loadingToken);
  66717. var disposeHandler = function () {
  66718. scene._removePendingData(loadingToken);
  66719. };
  66720. var errorHandler = function (message, exception) {
  66721. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66722. if (onError) {
  66723. onError(scene, errorMessage, exception);
  66724. }
  66725. else {
  66726. BABYLON.Tools.Error(errorMessage);
  66727. // should the exception be thrown?
  66728. }
  66729. disposeHandler();
  66730. };
  66731. var progressHandler = onProgress ? function (event) {
  66732. try {
  66733. onProgress(event);
  66734. }
  66735. catch (e) {
  66736. errorHandler("Error in onProgress callback", e);
  66737. }
  66738. } : undefined;
  66739. var successHandler = function (assets) {
  66740. if (onSuccess) {
  66741. try {
  66742. onSuccess(assets);
  66743. }
  66744. catch (e) {
  66745. errorHandler("Error in onSuccess callback", e);
  66746. }
  66747. }
  66748. scene._removePendingData(loadingToken);
  66749. };
  66750. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66751. if (plugin.loadAssetContainer) {
  66752. var syncedPlugin = plugin;
  66753. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66754. if (!assetContainer) {
  66755. return;
  66756. }
  66757. scene.loadingPluginName = plugin.name;
  66758. successHandler(assetContainer);
  66759. }
  66760. else if (plugin.loadAssetContainerAsync) {
  66761. var asyncedPlugin = plugin;
  66762. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66763. scene.loadingPluginName = plugin.name;
  66764. successHandler(assetContainer);
  66765. }).catch(function (error) {
  66766. errorHandler(error.message, error);
  66767. });
  66768. }
  66769. else {
  66770. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66771. }
  66772. if (SceneLoader.ShowLoadingScreen) {
  66773. scene.executeWhenReady(function () {
  66774. scene.getEngine().hideLoadingUI();
  66775. });
  66776. }
  66777. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66778. };
  66779. /**
  66780. * Load a scene into an asset container
  66781. * @param rootUrl a string that defines the root url for scene and resources
  66782. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66783. * @param scene is the instance of BABYLON.Scene to append to
  66784. * @param onProgress a callback with a progress event for each file being loaded
  66785. * @param pluginExtension the extension used to determine the plugin
  66786. * @returns The loaded asset container
  66787. */
  66788. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66789. if (onProgress === void 0) { onProgress = null; }
  66790. if (pluginExtension === void 0) { pluginExtension = null; }
  66791. return new Promise(function (resolve, reject) {
  66792. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66793. resolve(assetContainer);
  66794. }, onProgress, function (scene, message, exception) {
  66795. reject(exception || new Error(message));
  66796. }, pluginExtension);
  66797. });
  66798. };
  66799. // Flags
  66800. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66801. SceneLoader._ShowLoadingScreen = true;
  66802. SceneLoader._CleanBoneMatrixWeights = false;
  66803. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66804. // Members
  66805. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66806. SceneLoader._registeredPlugins = {};
  66807. return SceneLoader;
  66808. }());
  66809. BABYLON.SceneLoader = SceneLoader;
  66810. ;
  66811. })(BABYLON || (BABYLON = {}));
  66812. //# sourceMappingURL=babylon.sceneLoader.js.map
  66813. var BABYLON;
  66814. (function (BABYLON) {
  66815. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66816. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66817. var parsedMaterial = parsedData.materials[index];
  66818. if (parsedMaterial.id === id) {
  66819. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66820. }
  66821. }
  66822. return null;
  66823. };
  66824. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66825. for (var i in names) {
  66826. if (mesh.name === names[i]) {
  66827. hierarchyIds.push(mesh.id);
  66828. return true;
  66829. }
  66830. }
  66831. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66832. hierarchyIds.push(mesh.id);
  66833. return true;
  66834. }
  66835. return false;
  66836. };
  66837. var logOperation = function (operation, producer) {
  66838. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66839. };
  66840. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66841. if (addToScene === void 0) { addToScene = false; }
  66842. var container = new BABYLON.AssetContainer(scene);
  66843. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66844. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66845. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66846. // and avoid problems with multiple concurrent .babylon loads.
  66847. var log = "importScene has failed JSON parse";
  66848. try {
  66849. var parsedData = JSON.parse(data);
  66850. log = "";
  66851. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66852. var index;
  66853. var cache;
  66854. // Lights
  66855. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66856. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66857. var parsedLight = parsedData.lights[index];
  66858. var light = BABYLON.Light.Parse(parsedLight, scene);
  66859. if (light) {
  66860. container.lights.push(light);
  66861. log += (index === 0 ? "\n\tLights:" : "");
  66862. log += "\n\t\t" + light.toString(fullDetails);
  66863. }
  66864. }
  66865. }
  66866. // Animations
  66867. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66868. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66869. var parsedAnimation = parsedData.animations[index];
  66870. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66871. scene.animations.push(animation);
  66872. container.animations.push(animation);
  66873. log += (index === 0 ? "\n\tAnimations:" : "");
  66874. log += "\n\t\t" + animation.toString(fullDetails);
  66875. }
  66876. }
  66877. // Materials
  66878. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66879. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66880. var parsedMaterial = parsedData.materials[index];
  66881. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66882. container.materials.push(mat);
  66883. log += (index === 0 ? "\n\tMaterials:" : "");
  66884. log += "\n\t\t" + mat.toString(fullDetails);
  66885. }
  66886. }
  66887. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66888. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66889. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66890. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66891. container.multiMaterials.push(mmat);
  66892. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66893. log += "\n\t\t" + mmat.toString(fullDetails);
  66894. }
  66895. }
  66896. // Morph targets
  66897. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66898. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66899. var managerData = _a[_i];
  66900. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66901. }
  66902. }
  66903. // Skeletons
  66904. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66905. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66906. var parsedSkeleton = parsedData.skeletons[index];
  66907. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66908. container.skeletons.push(skeleton);
  66909. log += (index === 0 ? "\n\tSkeletons:" : "");
  66910. log += "\n\t\t" + skeleton.toString(fullDetails);
  66911. }
  66912. }
  66913. // Geometries
  66914. var geometries = parsedData.geometries;
  66915. if (geometries !== undefined && geometries !== null) {
  66916. var addedGeometry = new Array();
  66917. // Boxes
  66918. var boxes = geometries.boxes;
  66919. if (boxes !== undefined && boxes !== null) {
  66920. for (index = 0, cache = boxes.length; index < cache; index++) {
  66921. var parsedBox = boxes[index];
  66922. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  66923. }
  66924. }
  66925. // Spheres
  66926. var spheres = geometries.spheres;
  66927. if (spheres !== undefined && spheres !== null) {
  66928. for (index = 0, cache = spheres.length; index < cache; index++) {
  66929. var parsedSphere = spheres[index];
  66930. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  66931. }
  66932. }
  66933. // Cylinders
  66934. var cylinders = geometries.cylinders;
  66935. if (cylinders !== undefined && cylinders !== null) {
  66936. for (index = 0, cache = cylinders.length; index < cache; index++) {
  66937. var parsedCylinder = cylinders[index];
  66938. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  66939. }
  66940. }
  66941. // Toruses
  66942. var toruses = geometries.toruses;
  66943. if (toruses !== undefined && toruses !== null) {
  66944. for (index = 0, cache = toruses.length; index < cache; index++) {
  66945. var parsedTorus = toruses[index];
  66946. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  66947. }
  66948. }
  66949. // Grounds
  66950. var grounds = geometries.grounds;
  66951. if (grounds !== undefined && grounds !== null) {
  66952. for (index = 0, cache = grounds.length; index < cache; index++) {
  66953. var parsedGround = grounds[index];
  66954. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  66955. }
  66956. }
  66957. // Planes
  66958. var planes = geometries.planes;
  66959. if (planes !== undefined && planes !== null) {
  66960. for (index = 0, cache = planes.length; index < cache; index++) {
  66961. var parsedPlane = planes[index];
  66962. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  66963. }
  66964. }
  66965. // TorusKnots
  66966. var torusKnots = geometries.torusKnots;
  66967. if (torusKnots !== undefined && torusKnots !== null) {
  66968. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  66969. var parsedTorusKnot = torusKnots[index];
  66970. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  66971. }
  66972. }
  66973. // VertexData
  66974. var vertexData = geometries.vertexData;
  66975. if (vertexData !== undefined && vertexData !== null) {
  66976. for (index = 0, cache = vertexData.length; index < cache; index++) {
  66977. var parsedVertexData = vertexData[index];
  66978. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66979. }
  66980. }
  66981. addedGeometry.forEach(function (g) {
  66982. if (g) {
  66983. container.geometries.push(g);
  66984. }
  66985. });
  66986. }
  66987. // Transform nodes
  66988. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66989. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66990. var parsedTransformNode = parsedData.transformNodes[index];
  66991. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66992. container.transformNodes.push(node);
  66993. }
  66994. }
  66995. // Meshes
  66996. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66997. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66998. var parsedMesh = parsedData.meshes[index];
  66999. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67000. container.meshes.push(mesh);
  67001. log += (index === 0 ? "\n\tMeshes:" : "");
  67002. log += "\n\t\t" + mesh.toString(fullDetails);
  67003. }
  67004. }
  67005. // Cameras
  67006. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67007. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67008. var parsedCamera = parsedData.cameras[index];
  67009. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67010. container.cameras.push(camera);
  67011. log += (index === 0 ? "\n\tCameras:" : "");
  67012. log += "\n\t\t" + camera.toString(fullDetails);
  67013. }
  67014. }
  67015. // Browsing all the graph to connect the dots
  67016. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67017. var camera = scene.cameras[index];
  67018. if (camera._waitingParentId) {
  67019. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67020. camera._waitingParentId = null;
  67021. }
  67022. }
  67023. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67024. var light_1 = scene.lights[index];
  67025. if (light_1 && light_1._waitingParentId) {
  67026. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67027. light_1._waitingParentId = null;
  67028. }
  67029. }
  67030. // Sounds
  67031. // TODO: add sound
  67032. var loadedSounds = [];
  67033. var loadedSound;
  67034. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67035. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67036. var parsedSound = parsedData.sounds[index];
  67037. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67038. if (!parsedSound.url)
  67039. parsedSound.url = parsedSound.name;
  67040. if (!loadedSounds[parsedSound.url]) {
  67041. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67042. loadedSounds[parsedSound.url] = loadedSound;
  67043. container.sounds.push(loadedSound);
  67044. }
  67045. else {
  67046. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67047. }
  67048. }
  67049. else {
  67050. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67051. }
  67052. }
  67053. }
  67054. loadedSounds = [];
  67055. // Connect parents & children and parse actions
  67056. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67057. var transformNode = scene.transformNodes[index];
  67058. if (transformNode._waitingParentId) {
  67059. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67060. transformNode._waitingParentId = null;
  67061. }
  67062. }
  67063. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67064. var mesh = scene.meshes[index];
  67065. if (mesh._waitingParentId) {
  67066. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67067. mesh._waitingParentId = null;
  67068. }
  67069. if (mesh._waitingActions) {
  67070. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67071. mesh._waitingActions = null;
  67072. }
  67073. }
  67074. // freeze world matrix application
  67075. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67076. var currentMesh = scene.meshes[index];
  67077. if (currentMesh._waitingFreezeWorldMatrix) {
  67078. currentMesh.freezeWorldMatrix();
  67079. currentMesh._waitingFreezeWorldMatrix = null;
  67080. }
  67081. else {
  67082. currentMesh.computeWorldMatrix(true);
  67083. }
  67084. }
  67085. // Particles Systems
  67086. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67087. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67088. var parsedParticleSystem = parsedData.particleSystems[index];
  67089. if (parsedParticleSystem.activeParticleCount) {
  67090. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67091. container.particleSystems.push(ps);
  67092. }
  67093. else {
  67094. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67095. container.particleSystems.push(ps);
  67096. }
  67097. }
  67098. }
  67099. // Lens flares
  67100. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67101. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67102. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67103. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67104. container.lensFlareSystems.push(lf);
  67105. }
  67106. }
  67107. // Shadows
  67108. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67109. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67110. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67111. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67112. container.shadowGenerators.push(sg);
  67113. }
  67114. }
  67115. // Lights exclusions / inclusions
  67116. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67117. var light_2 = scene.lights[index];
  67118. // Excluded check
  67119. if (light_2._excludedMeshesIds.length > 0) {
  67120. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67121. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67122. if (excludedMesh) {
  67123. light_2.excludedMeshes.push(excludedMesh);
  67124. }
  67125. }
  67126. light_2._excludedMeshesIds = [];
  67127. }
  67128. // Included check
  67129. if (light_2._includedOnlyMeshesIds.length > 0) {
  67130. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67131. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67132. if (includedOnlyMesh) {
  67133. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67134. }
  67135. }
  67136. light_2._includedOnlyMeshesIds = [];
  67137. }
  67138. }
  67139. // Effect layers
  67140. if (parsedData.effectLayers) {
  67141. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67142. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67143. container.effectLayers.push(effectLayer);
  67144. }
  67145. }
  67146. // Actions (scene)
  67147. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67148. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67149. }
  67150. if (!addToScene) {
  67151. container.removeAllFromScene();
  67152. }
  67153. }
  67154. catch (err) {
  67155. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67156. if (onError) {
  67157. onError(msg, err);
  67158. }
  67159. else {
  67160. BABYLON.Tools.Log(msg);
  67161. throw err;
  67162. }
  67163. }
  67164. finally {
  67165. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67166. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67167. }
  67168. }
  67169. return container;
  67170. };
  67171. BABYLON.SceneLoader.RegisterPlugin({
  67172. name: "babylon.js",
  67173. extensions: ".babylon",
  67174. canDirectLoad: function (data) {
  67175. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67176. return true;
  67177. }
  67178. return false;
  67179. },
  67180. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67181. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67182. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67183. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67184. // and avoid problems with multiple concurrent .babylon loads.
  67185. var log = "importMesh has failed JSON parse";
  67186. try {
  67187. var parsedData = JSON.parse(data);
  67188. log = "";
  67189. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67190. if (!meshesNames) {
  67191. meshesNames = null;
  67192. }
  67193. else if (!Array.isArray(meshesNames)) {
  67194. meshesNames = [meshesNames];
  67195. }
  67196. var hierarchyIds = new Array();
  67197. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67198. var loadedSkeletonsIds = [];
  67199. var loadedMaterialsIds = [];
  67200. var index;
  67201. var cache;
  67202. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67203. var parsedMesh = parsedData.meshes[index];
  67204. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67205. if (meshesNames !== null) {
  67206. // Remove found mesh name from list.
  67207. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67208. }
  67209. //Geometry?
  67210. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67211. //does the file contain geometries?
  67212. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67213. //find the correct geometry and add it to the scene
  67214. var found = false;
  67215. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67216. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67217. return;
  67218. }
  67219. else {
  67220. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67221. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67222. switch (geometryType) {
  67223. case "boxes":
  67224. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67225. break;
  67226. case "spheres":
  67227. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67228. break;
  67229. case "cylinders":
  67230. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67231. break;
  67232. case "toruses":
  67233. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67234. break;
  67235. case "grounds":
  67236. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67237. break;
  67238. case "planes":
  67239. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67240. break;
  67241. case "torusKnots":
  67242. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67243. break;
  67244. case "vertexData":
  67245. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67246. break;
  67247. }
  67248. found = true;
  67249. }
  67250. });
  67251. }
  67252. });
  67253. if (found === false) {
  67254. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67255. }
  67256. }
  67257. }
  67258. // Material ?
  67259. if (parsedMesh.materialId) {
  67260. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67261. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67262. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67263. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67264. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67265. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67266. var subMatId = parsedMultiMaterial.materials[matIndex];
  67267. loadedMaterialsIds.push(subMatId);
  67268. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67269. if (mat) {
  67270. log += "\n\tMaterial " + mat.toString(fullDetails);
  67271. }
  67272. }
  67273. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67274. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67275. if (mmat) {
  67276. materialFound = true;
  67277. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67278. }
  67279. break;
  67280. }
  67281. }
  67282. }
  67283. if (materialFound === false) {
  67284. loadedMaterialsIds.push(parsedMesh.materialId);
  67285. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67286. if (!mat) {
  67287. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67288. }
  67289. else {
  67290. log += "\n\tMaterial " + mat.toString(fullDetails);
  67291. }
  67292. }
  67293. }
  67294. // Skeleton ?
  67295. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67296. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67297. if (skeletonAlreadyLoaded === false) {
  67298. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67299. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67300. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67301. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67302. skeletons.push(skeleton);
  67303. loadedSkeletonsIds.push(parsedSkeleton.id);
  67304. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67305. }
  67306. }
  67307. }
  67308. }
  67309. // Morph targets ?
  67310. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67311. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67312. var managerData = _a[_i];
  67313. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67314. }
  67315. }
  67316. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67317. meshes.push(mesh);
  67318. log += "\n\tMesh " + mesh.toString(fullDetails);
  67319. }
  67320. }
  67321. // Connecting parents
  67322. var currentMesh;
  67323. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67324. currentMesh = scene.meshes[index];
  67325. if (currentMesh._waitingParentId) {
  67326. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67327. currentMesh._waitingParentId = null;
  67328. }
  67329. }
  67330. // freeze and compute world matrix application
  67331. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67332. currentMesh = scene.meshes[index];
  67333. if (currentMesh._waitingFreezeWorldMatrix) {
  67334. currentMesh.freezeWorldMatrix();
  67335. currentMesh._waitingFreezeWorldMatrix = null;
  67336. }
  67337. else {
  67338. currentMesh.computeWorldMatrix(true);
  67339. }
  67340. }
  67341. }
  67342. // Particles
  67343. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67344. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67345. var parsedParticleSystem = parsedData.particleSystems[index];
  67346. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67347. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67348. }
  67349. }
  67350. }
  67351. return true;
  67352. }
  67353. catch (err) {
  67354. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67355. if (onError) {
  67356. onError(msg, err);
  67357. }
  67358. else {
  67359. BABYLON.Tools.Log(msg);
  67360. throw err;
  67361. }
  67362. }
  67363. finally {
  67364. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67365. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67366. }
  67367. }
  67368. return false;
  67369. },
  67370. load: function (scene, data, rootUrl, onError) {
  67371. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67372. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67373. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67374. // and avoid problems with multiple concurrent .babylon loads.
  67375. var log = "importScene has failed JSON parse";
  67376. try {
  67377. var parsedData = JSON.parse(data);
  67378. log = "";
  67379. // Scene
  67380. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67381. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67382. }
  67383. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67384. scene.autoClear = parsedData.autoClear;
  67385. }
  67386. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67387. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67388. }
  67389. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67390. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67391. }
  67392. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67393. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67394. }
  67395. // Fog
  67396. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67397. scene.fogMode = parsedData.fogMode;
  67398. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67399. scene.fogStart = parsedData.fogStart;
  67400. scene.fogEnd = parsedData.fogEnd;
  67401. scene.fogDensity = parsedData.fogDensity;
  67402. log += "\tFog mode for scene: ";
  67403. switch (scene.fogMode) {
  67404. // getters not compiling, so using hardcoded
  67405. case 1:
  67406. log += "exp\n";
  67407. break;
  67408. case 2:
  67409. log += "exp2\n";
  67410. break;
  67411. case 3:
  67412. log += "linear\n";
  67413. break;
  67414. }
  67415. }
  67416. //Physics
  67417. if (parsedData.physicsEnabled) {
  67418. var physicsPlugin;
  67419. if (parsedData.physicsEngine === "cannon") {
  67420. physicsPlugin = new BABYLON.CannonJSPlugin();
  67421. }
  67422. else if (parsedData.physicsEngine === "oimo") {
  67423. physicsPlugin = new BABYLON.OimoJSPlugin();
  67424. }
  67425. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67426. //else - default engine, which is currently oimo
  67427. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67428. scene.enablePhysics(physicsGravity, physicsPlugin);
  67429. }
  67430. // Metadata
  67431. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67432. scene.metadata = parsedData.metadata;
  67433. }
  67434. //collisions, if defined. otherwise, default is true
  67435. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67436. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67437. }
  67438. scene.workerCollisions = !!parsedData.workerCollisions;
  67439. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67440. if (!container) {
  67441. return false;
  67442. }
  67443. if (parsedData.autoAnimate) {
  67444. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67445. }
  67446. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67447. scene.setActiveCameraByID(parsedData.activeCameraID);
  67448. }
  67449. // Environment texture
  67450. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67451. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67452. if (parsedData.createDefaultSkybox === true) {
  67453. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67454. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67455. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67456. }
  67457. }
  67458. // Finish
  67459. return true;
  67460. }
  67461. catch (err) {
  67462. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67463. if (onError) {
  67464. onError(msg, err);
  67465. }
  67466. else {
  67467. BABYLON.Tools.Log(msg);
  67468. throw err;
  67469. }
  67470. }
  67471. finally {
  67472. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67473. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67474. }
  67475. }
  67476. return false;
  67477. },
  67478. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67479. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67480. return container;
  67481. }
  67482. });
  67483. })(BABYLON || (BABYLON = {}));
  67484. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67485. var BABYLON;
  67486. (function (BABYLON) {
  67487. var FilesInput = /** @class */ (function () {
  67488. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67489. this.onProcessFileCallback = function () { return true; };
  67490. this._engine = engine;
  67491. this._currentScene = scene;
  67492. this._sceneLoadedCallback = sceneLoadedCallback;
  67493. this._progressCallback = progressCallback;
  67494. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67495. this._textureLoadingCallback = textureLoadingCallback;
  67496. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67497. this._onReloadCallback = onReloadCallback;
  67498. this._errorCallback = errorCallback;
  67499. }
  67500. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67501. var _this = this;
  67502. if (elementToMonitor) {
  67503. this._elementToMonitor = elementToMonitor;
  67504. this._dragEnterHandler = function (e) { _this.drag(e); };
  67505. this._dragOverHandler = function (e) { _this.drag(e); };
  67506. this._dropHandler = function (e) { _this.drop(e); };
  67507. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67508. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67509. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67510. }
  67511. };
  67512. FilesInput.prototype.dispose = function () {
  67513. if (!this._elementToMonitor) {
  67514. return;
  67515. }
  67516. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67517. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67518. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67519. };
  67520. FilesInput.prototype.renderFunction = function () {
  67521. if (this._additionalRenderLoopLogicCallback) {
  67522. this._additionalRenderLoopLogicCallback();
  67523. }
  67524. if (this._currentScene) {
  67525. if (this._textureLoadingCallback) {
  67526. var remaining = this._currentScene.getWaitingItemsCount();
  67527. if (remaining > 0) {
  67528. this._textureLoadingCallback(remaining);
  67529. }
  67530. }
  67531. this._currentScene.render();
  67532. }
  67533. };
  67534. FilesInput.prototype.drag = function (e) {
  67535. e.stopPropagation();
  67536. e.preventDefault();
  67537. };
  67538. FilesInput.prototype.drop = function (eventDrop) {
  67539. eventDrop.stopPropagation();
  67540. eventDrop.preventDefault();
  67541. this.loadFiles(eventDrop);
  67542. };
  67543. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67544. var _this = this;
  67545. var reader = folder.createReader();
  67546. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67547. reader.readEntries(function (entries) {
  67548. remaining.count += entries.length;
  67549. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67550. var entry = entries_1[_i];
  67551. if (entry.isFile) {
  67552. entry.file(function (file) {
  67553. file.correctName = relativePath + file.name;
  67554. files.push(file);
  67555. if (--remaining.count === 0) {
  67556. callback();
  67557. }
  67558. });
  67559. }
  67560. else if (entry.isDirectory) {
  67561. _this._traverseFolder(entry, files, remaining, callback);
  67562. }
  67563. }
  67564. if (--remaining.count) {
  67565. callback();
  67566. }
  67567. });
  67568. };
  67569. FilesInput.prototype._processFiles = function (files) {
  67570. for (var i = 0; i < files.length; i++) {
  67571. var name = files[i].correctName.toLowerCase();
  67572. var extension = name.split('.').pop();
  67573. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67574. continue;
  67575. }
  67576. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67577. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67578. this._sceneFileToLoad = files[i];
  67579. }
  67580. else {
  67581. FilesInput.FilesToLoad[name] = files[i];
  67582. }
  67583. }
  67584. };
  67585. FilesInput.prototype.loadFiles = function (event) {
  67586. var _this = this;
  67587. if (this._startingProcessingFilesCallback)
  67588. this._startingProcessingFilesCallback();
  67589. // Handling data transfer via drag'n'drop
  67590. if (event && event.dataTransfer && event.dataTransfer.files) {
  67591. this._filesToLoad = event.dataTransfer.files;
  67592. }
  67593. // Handling files from input files
  67594. if (event && event.target && event.target.files) {
  67595. this._filesToLoad = event.target.files;
  67596. }
  67597. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67598. var files_1 = new Array();
  67599. var folders = [];
  67600. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67601. for (var i = 0; i < this._filesToLoad.length; i++) {
  67602. var fileToLoad = this._filesToLoad[i];
  67603. var name_1 = fileToLoad.name.toLowerCase();
  67604. var entry = void 0;
  67605. fileToLoad.correctName = name_1;
  67606. if (items) {
  67607. var item = items[i];
  67608. if (item.getAsEntry) {
  67609. entry = item.getAsEntry();
  67610. }
  67611. else if (item.webkitGetAsEntry) {
  67612. entry = item.webkitGetAsEntry();
  67613. }
  67614. }
  67615. if (!entry) {
  67616. files_1.push(fileToLoad);
  67617. }
  67618. else {
  67619. if (entry.isDirectory) {
  67620. folders.push(entry);
  67621. }
  67622. else {
  67623. files_1.push(fileToLoad);
  67624. }
  67625. }
  67626. }
  67627. if (folders.length === 0) {
  67628. this._processFiles(files_1);
  67629. this._processReload();
  67630. }
  67631. else {
  67632. var remaining = { count: folders.length };
  67633. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67634. var folder = folders_1[_i];
  67635. this._traverseFolder(folder, files_1, remaining, function () {
  67636. _this._processFiles(files_1);
  67637. if (remaining.count === 0) {
  67638. _this._processReload();
  67639. }
  67640. });
  67641. }
  67642. }
  67643. }
  67644. };
  67645. FilesInput.prototype._processReload = function () {
  67646. if (this._onReloadCallback) {
  67647. this._onReloadCallback(this._sceneFileToLoad);
  67648. }
  67649. else {
  67650. this.reload();
  67651. }
  67652. };
  67653. FilesInput.prototype.reload = function () {
  67654. var _this = this;
  67655. // If a scene file has been provided
  67656. if (this._sceneFileToLoad) {
  67657. if (this._currentScene) {
  67658. if (BABYLON.Tools.errorsCount > 0) {
  67659. BABYLON.Tools.ClearLogCache();
  67660. }
  67661. this._engine.stopRenderLoop();
  67662. this._currentScene.dispose();
  67663. }
  67664. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67665. if (_this._progressCallback) {
  67666. _this._progressCallback(progress);
  67667. }
  67668. }).then(function (scene) {
  67669. _this._currentScene = scene;
  67670. if (_this._sceneLoadedCallback) {
  67671. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67672. }
  67673. // Wait for textures and shaders to be ready
  67674. _this._currentScene.executeWhenReady(function () {
  67675. _this._engine.runRenderLoop(function () {
  67676. _this.renderFunction();
  67677. });
  67678. });
  67679. }).catch(function (error) {
  67680. if (_this._errorCallback) {
  67681. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67682. }
  67683. });
  67684. }
  67685. else {
  67686. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67687. }
  67688. };
  67689. FilesInput.FilesToLoad = {};
  67690. return FilesInput;
  67691. }());
  67692. BABYLON.FilesInput = FilesInput;
  67693. })(BABYLON || (BABYLON = {}));
  67694. //# sourceMappingURL=babylon.filesInput.js.map
  67695. var BABYLON;
  67696. (function (BABYLON) {
  67697. /**
  67698. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67699. * The underlying implementation relies on an associative array to ensure the best performances.
  67700. * The value can be anything including 'null' but except 'undefined'
  67701. */
  67702. var StringDictionary = /** @class */ (function () {
  67703. function StringDictionary() {
  67704. this._count = 0;
  67705. this._data = {};
  67706. }
  67707. /**
  67708. * This will clear this dictionary and copy the content from the 'source' one.
  67709. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67710. * @param source the dictionary to take the content from and copy to this dictionary
  67711. */
  67712. StringDictionary.prototype.copyFrom = function (source) {
  67713. var _this = this;
  67714. this.clear();
  67715. source.forEach(function (t, v) { return _this.add(t, v); });
  67716. };
  67717. /**
  67718. * Get a value based from its key
  67719. * @param key the given key to get the matching value from
  67720. * @return the value if found, otherwise undefined is returned
  67721. */
  67722. StringDictionary.prototype.get = function (key) {
  67723. var val = this._data[key];
  67724. if (val !== undefined) {
  67725. return val;
  67726. }
  67727. return undefined;
  67728. };
  67729. /**
  67730. * Get a value from its key or add it if it doesn't exist.
  67731. * This method will ensure you that a given key/data will be present in the dictionary.
  67732. * @param key the given key to get the matching value from
  67733. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67734. * The factory will only be invoked if there's no data for the given key.
  67735. * @return the value corresponding to the key.
  67736. */
  67737. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67738. var val = this.get(key);
  67739. if (val !== undefined) {
  67740. return val;
  67741. }
  67742. val = factory(key);
  67743. if (val) {
  67744. this.add(key, val);
  67745. }
  67746. return val;
  67747. };
  67748. /**
  67749. * Get a value from its key if present in the dictionary otherwise add it
  67750. * @param key the key to get the value from
  67751. * @param val if there's no such key/value pair in the dictionary add it with this value
  67752. * @return the value corresponding to the key
  67753. */
  67754. StringDictionary.prototype.getOrAdd = function (key, val) {
  67755. var curVal = this.get(key);
  67756. if (curVal !== undefined) {
  67757. return curVal;
  67758. }
  67759. this.add(key, val);
  67760. return val;
  67761. };
  67762. /**
  67763. * Check if there's a given key in the dictionary
  67764. * @param key the key to check for
  67765. * @return true if the key is present, false otherwise
  67766. */
  67767. StringDictionary.prototype.contains = function (key) {
  67768. return this._data[key] !== undefined;
  67769. };
  67770. /**
  67771. * Add a new key and its corresponding value
  67772. * @param key the key to add
  67773. * @param value the value corresponding to the key
  67774. * @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
  67775. */
  67776. StringDictionary.prototype.add = function (key, value) {
  67777. if (this._data[key] !== undefined) {
  67778. return false;
  67779. }
  67780. this._data[key] = value;
  67781. ++this._count;
  67782. return true;
  67783. };
  67784. StringDictionary.prototype.set = function (key, value) {
  67785. if (this._data[key] === undefined) {
  67786. return false;
  67787. }
  67788. this._data[key] = value;
  67789. return true;
  67790. };
  67791. /**
  67792. * Get the element of the given key and remove it from the dictionary
  67793. * @param key
  67794. */
  67795. StringDictionary.prototype.getAndRemove = function (key) {
  67796. var val = this.get(key);
  67797. if (val !== undefined) {
  67798. delete this._data[key];
  67799. --this._count;
  67800. return val;
  67801. }
  67802. return null;
  67803. };
  67804. /**
  67805. * Remove a key/value from the dictionary.
  67806. * @param key the key to remove
  67807. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67808. */
  67809. StringDictionary.prototype.remove = function (key) {
  67810. if (this.contains(key)) {
  67811. delete this._data[key];
  67812. --this._count;
  67813. return true;
  67814. }
  67815. return false;
  67816. };
  67817. /**
  67818. * Clear the whole content of the dictionary
  67819. */
  67820. StringDictionary.prototype.clear = function () {
  67821. this._data = {};
  67822. this._count = 0;
  67823. };
  67824. Object.defineProperty(StringDictionary.prototype, "count", {
  67825. get: function () {
  67826. return this._count;
  67827. },
  67828. enumerable: true,
  67829. configurable: true
  67830. });
  67831. /**
  67832. * Execute a callback on each key/val of the dictionary.
  67833. * Note that you can remove any element in this dictionary in the callback implementation
  67834. * @param callback the callback to execute on a given key/value pair
  67835. */
  67836. StringDictionary.prototype.forEach = function (callback) {
  67837. for (var cur in this._data) {
  67838. var val = this._data[cur];
  67839. callback(cur, val);
  67840. }
  67841. };
  67842. /**
  67843. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67844. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67845. * Note that you can remove any element in this dictionary in the callback implementation
  67846. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67847. */
  67848. StringDictionary.prototype.first = function (callback) {
  67849. for (var cur in this._data) {
  67850. var val = this._data[cur];
  67851. var res = callback(cur, val);
  67852. if (res) {
  67853. return res;
  67854. }
  67855. }
  67856. return null;
  67857. };
  67858. return StringDictionary;
  67859. }());
  67860. BABYLON.StringDictionary = StringDictionary;
  67861. })(BABYLON || (BABYLON = {}));
  67862. //# sourceMappingURL=babylon.stringDictionary.js.map
  67863. var BABYLON;
  67864. (function (BABYLON) {
  67865. var Tags = /** @class */ (function () {
  67866. function Tags() {
  67867. }
  67868. Tags.EnableFor = function (obj) {
  67869. obj._tags = obj._tags || {};
  67870. obj.hasTags = function () {
  67871. return Tags.HasTags(obj);
  67872. };
  67873. obj.addTags = function (tagsString) {
  67874. return Tags.AddTagsTo(obj, tagsString);
  67875. };
  67876. obj.removeTags = function (tagsString) {
  67877. return Tags.RemoveTagsFrom(obj, tagsString);
  67878. };
  67879. obj.matchesTagsQuery = function (tagsQuery) {
  67880. return Tags.MatchesQuery(obj, tagsQuery);
  67881. };
  67882. };
  67883. Tags.DisableFor = function (obj) {
  67884. delete obj._tags;
  67885. delete obj.hasTags;
  67886. delete obj.addTags;
  67887. delete obj.removeTags;
  67888. delete obj.matchesTagsQuery;
  67889. };
  67890. Tags.HasTags = function (obj) {
  67891. if (!obj._tags) {
  67892. return false;
  67893. }
  67894. return !BABYLON.Tools.IsEmpty(obj._tags);
  67895. };
  67896. Tags.GetTags = function (obj, asString) {
  67897. if (asString === void 0) { asString = true; }
  67898. if (!obj._tags) {
  67899. return null;
  67900. }
  67901. if (asString) {
  67902. var tagsArray = [];
  67903. for (var tag in obj._tags) {
  67904. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  67905. tagsArray.push(tag);
  67906. }
  67907. }
  67908. return tagsArray.join(" ");
  67909. }
  67910. else {
  67911. return obj._tags;
  67912. }
  67913. };
  67914. // the tags 'true' and 'false' are reserved and cannot be used as tags
  67915. // a tag cannot start with '||', '&&', and '!'
  67916. // it cannot contain whitespaces
  67917. Tags.AddTagsTo = function (obj, tagsString) {
  67918. if (!tagsString) {
  67919. return;
  67920. }
  67921. if (typeof tagsString !== "string") {
  67922. return;
  67923. }
  67924. var tags = tagsString.split(" ");
  67925. tags.forEach(function (tag, index, array) {
  67926. Tags._AddTagTo(obj, tag);
  67927. });
  67928. };
  67929. Tags._AddTagTo = function (obj, tag) {
  67930. tag = tag.trim();
  67931. if (tag === "" || tag === "true" || tag === "false") {
  67932. return;
  67933. }
  67934. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  67935. return;
  67936. }
  67937. Tags.EnableFor(obj);
  67938. obj._tags[tag] = true;
  67939. };
  67940. Tags.RemoveTagsFrom = function (obj, tagsString) {
  67941. if (!Tags.HasTags(obj)) {
  67942. return;
  67943. }
  67944. var tags = tagsString.split(" ");
  67945. for (var t in tags) {
  67946. Tags._RemoveTagFrom(obj, tags[t]);
  67947. }
  67948. };
  67949. Tags._RemoveTagFrom = function (obj, tag) {
  67950. delete obj._tags[tag];
  67951. };
  67952. Tags.MatchesQuery = function (obj, tagsQuery) {
  67953. if (tagsQuery === undefined) {
  67954. return true;
  67955. }
  67956. if (tagsQuery === "") {
  67957. return Tags.HasTags(obj);
  67958. }
  67959. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  67960. };
  67961. return Tags;
  67962. }());
  67963. BABYLON.Tags = Tags;
  67964. })(BABYLON || (BABYLON = {}));
  67965. //# sourceMappingURL=babylon.tags.js.map
  67966. var BABYLON;
  67967. (function (BABYLON) {
  67968. var AndOrNotEvaluator = /** @class */ (function () {
  67969. function AndOrNotEvaluator() {
  67970. }
  67971. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  67972. if (!query.match(/\([^\(\)]*\)/g)) {
  67973. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  67974. }
  67975. else {
  67976. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  67977. // remove parenthesis
  67978. r = r.slice(1, r.length - 1);
  67979. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  67980. });
  67981. }
  67982. if (query === "true") {
  67983. return true;
  67984. }
  67985. if (query === "false") {
  67986. return false;
  67987. }
  67988. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67989. };
  67990. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67991. evaluateCallback = evaluateCallback || (function (r) {
  67992. return r === "true" ? true : false;
  67993. });
  67994. var result;
  67995. var or = parenthesisContent.split("||");
  67996. for (var i in or) {
  67997. if (or.hasOwnProperty(i)) {
  67998. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  67999. var and = ori.split("&&");
  68000. if (and.length > 1) {
  68001. for (var j = 0; j < and.length; ++j) {
  68002. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68003. if (andj !== "true" && andj !== "false") {
  68004. if (andj[0] === "!") {
  68005. result = !evaluateCallback(andj.substring(1));
  68006. }
  68007. else {
  68008. result = evaluateCallback(andj);
  68009. }
  68010. }
  68011. else {
  68012. result = andj === "true" ? true : false;
  68013. }
  68014. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68015. ori = "false";
  68016. break;
  68017. }
  68018. }
  68019. }
  68020. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68021. result = true;
  68022. break;
  68023. }
  68024. // result equals false (or undefined)
  68025. if (ori !== "true" && ori !== "false") {
  68026. if (ori[0] === "!") {
  68027. result = !evaluateCallback(ori.substring(1));
  68028. }
  68029. else {
  68030. result = evaluateCallback(ori);
  68031. }
  68032. }
  68033. else {
  68034. result = ori === "true" ? true : false;
  68035. }
  68036. }
  68037. }
  68038. // the whole parenthesis scope is replaced by 'true' or 'false'
  68039. return result ? "true" : "false";
  68040. };
  68041. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68042. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68043. // remove whitespaces
  68044. r = r.replace(/[\s]/g, function () { return ""; });
  68045. return r.length % 2 ? "!" : "";
  68046. });
  68047. booleanString = booleanString.trim();
  68048. if (booleanString === "!true") {
  68049. booleanString = "false";
  68050. }
  68051. else if (booleanString === "!false") {
  68052. booleanString = "true";
  68053. }
  68054. return booleanString;
  68055. };
  68056. return AndOrNotEvaluator;
  68057. }());
  68058. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68059. })(BABYLON || (BABYLON = {}));
  68060. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68061. var BABYLON;
  68062. (function (BABYLON) {
  68063. var Database = /** @class */ (function () {
  68064. function Database(urlToScene, callbackManifestChecked) {
  68065. // Handling various flavors of prefixed version of IndexedDB
  68066. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68067. this.callbackManifestChecked = callbackManifestChecked;
  68068. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  68069. this.db = null;
  68070. this._enableSceneOffline = false;
  68071. this._enableTexturesOffline = false;
  68072. this.manifestVersionFound = 0;
  68073. this.mustUpdateRessources = false;
  68074. this.hasReachedQuota = false;
  68075. if (!Database.IDBStorageEnabled) {
  68076. this.callbackManifestChecked(true);
  68077. }
  68078. else {
  68079. this.checkManifestFile();
  68080. }
  68081. }
  68082. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68083. get: function () {
  68084. return this._enableSceneOffline;
  68085. },
  68086. enumerable: true,
  68087. configurable: true
  68088. });
  68089. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68090. get: function () {
  68091. return this._enableTexturesOffline;
  68092. },
  68093. enumerable: true,
  68094. configurable: true
  68095. });
  68096. Database.prototype.checkManifestFile = function () {
  68097. var _this = this;
  68098. var noManifestFile = function () {
  68099. _this._enableSceneOffline = false;
  68100. _this._enableTexturesOffline = false;
  68101. _this.callbackManifestChecked(false);
  68102. };
  68103. var timeStampUsed = false;
  68104. var manifestURL = this.currentSceneUrl + ".manifest";
  68105. var xhr = new XMLHttpRequest();
  68106. if (navigator.onLine) {
  68107. // Adding a timestamp to by-pass browsers' cache
  68108. timeStampUsed = true;
  68109. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  68110. }
  68111. xhr.open("GET", manifestURL, true);
  68112. xhr.addEventListener("load", function () {
  68113. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68114. try {
  68115. var manifestFile = JSON.parse(xhr.response);
  68116. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68117. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68118. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68119. _this.manifestVersionFound = manifestFile.version;
  68120. }
  68121. if (_this.callbackManifestChecked) {
  68122. _this.callbackManifestChecked(true);
  68123. }
  68124. }
  68125. catch (ex) {
  68126. noManifestFile();
  68127. }
  68128. }
  68129. else {
  68130. noManifestFile();
  68131. }
  68132. }, false);
  68133. xhr.addEventListener("error", function (event) {
  68134. if (timeStampUsed) {
  68135. timeStampUsed = false;
  68136. // Let's retry without the timeStamp
  68137. // It could fail when coupled with HTML5 Offline API
  68138. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68139. xhr.open("GET", retryManifestURL, true);
  68140. xhr.send();
  68141. }
  68142. else {
  68143. noManifestFile();
  68144. }
  68145. }, false);
  68146. try {
  68147. xhr.send();
  68148. }
  68149. catch (ex) {
  68150. BABYLON.Tools.Error("Error on XHR send request.");
  68151. this.callbackManifestChecked(false);
  68152. }
  68153. };
  68154. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68155. var _this = this;
  68156. var handleError = function () {
  68157. _this.isSupported = false;
  68158. if (errorCallback)
  68159. errorCallback();
  68160. };
  68161. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68162. // Your browser doesn't support IndexedDB
  68163. this.isSupported = false;
  68164. if (errorCallback)
  68165. errorCallback();
  68166. }
  68167. else {
  68168. // If the DB hasn't been opened or created yet
  68169. if (!this.db) {
  68170. this.hasReachedQuota = false;
  68171. this.isSupported = true;
  68172. var request = this.idbFactory.open("babylonjs", 1);
  68173. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68174. request.onerror = function (event) {
  68175. handleError();
  68176. };
  68177. // executes when a version change transaction cannot complete due to other active transactions
  68178. request.onblocked = function (event) {
  68179. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68180. handleError();
  68181. };
  68182. // DB has been opened successfully
  68183. request.onsuccess = function (event) {
  68184. _this.db = request.result;
  68185. successCallback();
  68186. };
  68187. // Initialization of the DB. Creating Scenes & Textures stores
  68188. request.onupgradeneeded = function (event) {
  68189. _this.db = (event.target).result;
  68190. if (_this.db) {
  68191. try {
  68192. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68193. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68194. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68195. }
  68196. catch (ex) {
  68197. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68198. handleError();
  68199. }
  68200. }
  68201. };
  68202. }
  68203. // DB has already been created and opened
  68204. else {
  68205. if (successCallback)
  68206. successCallback();
  68207. }
  68208. }
  68209. };
  68210. Database.prototype.loadImageFromDB = function (url, image) {
  68211. var _this = this;
  68212. var completeURL = Database.ReturnFullUrlLocation(url);
  68213. var saveAndLoadImage = function () {
  68214. if (!_this.hasReachedQuota && _this.db !== null) {
  68215. // the texture is not yet in the DB, let's try to save it
  68216. _this._saveImageIntoDBAsync(completeURL, image);
  68217. }
  68218. // If the texture is not in the DB and we've reached the DB quota limit
  68219. // let's load it directly from the web
  68220. else {
  68221. image.src = url;
  68222. }
  68223. };
  68224. if (!this.mustUpdateRessources) {
  68225. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68226. }
  68227. // First time we're download the images or update requested in the manifest file by a version change
  68228. else {
  68229. saveAndLoadImage();
  68230. }
  68231. };
  68232. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68233. if (this.isSupported && this.db !== null) {
  68234. var texture;
  68235. var transaction = this.db.transaction(["textures"]);
  68236. transaction.onabort = function (event) {
  68237. image.src = url;
  68238. };
  68239. transaction.oncomplete = function (event) {
  68240. var blobTextureURL;
  68241. if (texture) {
  68242. var URL = window.URL || window.webkitURL;
  68243. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68244. image.onerror = function () {
  68245. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68246. image.src = url;
  68247. };
  68248. image.src = blobTextureURL;
  68249. }
  68250. else {
  68251. notInDBCallback();
  68252. }
  68253. };
  68254. var getRequest = transaction.objectStore("textures").get(url);
  68255. getRequest.onsuccess = function (event) {
  68256. texture = (event.target).result;
  68257. };
  68258. getRequest.onerror = function (event) {
  68259. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68260. image.src = url;
  68261. };
  68262. }
  68263. else {
  68264. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68265. image.src = url;
  68266. }
  68267. };
  68268. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68269. var _this = this;
  68270. if (this.isSupported) {
  68271. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68272. var generateBlobUrl = function () {
  68273. var blobTextureURL;
  68274. if (blob) {
  68275. var URL = window.URL || window.webkitURL;
  68276. try {
  68277. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68278. }
  68279. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68280. catch (ex) {
  68281. blobTextureURL = URL.createObjectURL(blob);
  68282. }
  68283. }
  68284. if (blobTextureURL) {
  68285. image.src = blobTextureURL;
  68286. }
  68287. };
  68288. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68289. var xhr = new XMLHttpRequest(), blob;
  68290. xhr.open("GET", url, true);
  68291. xhr.responseType = "blob";
  68292. xhr.addEventListener("load", function () {
  68293. if (xhr.status === 200 && _this.db) {
  68294. // Blob as response (XHR2)
  68295. blob = xhr.response;
  68296. var transaction = _this.db.transaction(["textures"], "readwrite");
  68297. // the transaction could abort because of a QuotaExceededError error
  68298. transaction.onabort = function (event) {
  68299. try {
  68300. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68301. var srcElement = (event.srcElement || event.target);
  68302. var error = srcElement.error;
  68303. if (error && error.name === "QuotaExceededError") {
  68304. _this.hasReachedQuota = true;
  68305. }
  68306. }
  68307. catch (ex) { }
  68308. generateBlobUrl();
  68309. };
  68310. transaction.oncomplete = function (event) {
  68311. generateBlobUrl();
  68312. };
  68313. var newTexture = { textureUrl: url, data: blob };
  68314. try {
  68315. // Put the blob into the dabase
  68316. var addRequest = transaction.objectStore("textures").put(newTexture);
  68317. addRequest.onsuccess = function (event) {
  68318. };
  68319. addRequest.onerror = function (event) {
  68320. generateBlobUrl();
  68321. };
  68322. }
  68323. catch (ex) {
  68324. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68325. if (ex.code === 25) {
  68326. Database.IsUASupportingBlobStorage = false;
  68327. }
  68328. image.src = url;
  68329. }
  68330. }
  68331. else {
  68332. image.src = url;
  68333. }
  68334. }, false);
  68335. xhr.addEventListener("error", function (event) {
  68336. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68337. image.src = url;
  68338. }, false);
  68339. xhr.send();
  68340. }
  68341. else {
  68342. image.src = url;
  68343. }
  68344. }
  68345. else {
  68346. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68347. image.src = url;
  68348. }
  68349. };
  68350. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68351. var _this = this;
  68352. var updateVersion = function () {
  68353. // the version is not yet in the DB or we need to update it
  68354. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68355. };
  68356. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68357. };
  68358. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68359. var _this = this;
  68360. if (this.isSupported && this.db) {
  68361. var version;
  68362. try {
  68363. var transaction = this.db.transaction(["versions"]);
  68364. transaction.oncomplete = function (event) {
  68365. if (version) {
  68366. // If the version in the JSON file is > than the version in DB
  68367. if (_this.manifestVersionFound > version.data) {
  68368. _this.mustUpdateRessources = true;
  68369. updateInDBCallback();
  68370. }
  68371. else {
  68372. callback(version.data);
  68373. }
  68374. }
  68375. // version was not found in DB
  68376. else {
  68377. _this.mustUpdateRessources = true;
  68378. updateInDBCallback();
  68379. }
  68380. };
  68381. transaction.onabort = function (event) {
  68382. callback(-1);
  68383. };
  68384. var getRequest = transaction.objectStore("versions").get(url);
  68385. getRequest.onsuccess = function (event) {
  68386. version = (event.target).result;
  68387. };
  68388. getRequest.onerror = function (event) {
  68389. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68390. callback(-1);
  68391. };
  68392. }
  68393. catch (ex) {
  68394. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68395. callback(-1);
  68396. }
  68397. }
  68398. else {
  68399. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68400. callback(-1);
  68401. }
  68402. };
  68403. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68404. var _this = this;
  68405. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68406. try {
  68407. // Open a transaction to the database
  68408. var transaction = this.db.transaction(["versions"], "readwrite");
  68409. // the transaction could abort because of a QuotaExceededError error
  68410. transaction.onabort = function (event) {
  68411. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68412. var error = event.srcElement['error'];
  68413. if (error && error.name === "QuotaExceededError") {
  68414. _this.hasReachedQuota = true;
  68415. }
  68416. }
  68417. catch (ex) { }
  68418. callback(-1);
  68419. };
  68420. transaction.oncomplete = function (event) {
  68421. callback(_this.manifestVersionFound);
  68422. };
  68423. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68424. // Put the scene into the database
  68425. var addRequest = transaction.objectStore("versions").put(newVersion);
  68426. addRequest.onsuccess = function (event) {
  68427. };
  68428. addRequest.onerror = function (event) {
  68429. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68430. };
  68431. }
  68432. catch (ex) {
  68433. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68434. callback(-1);
  68435. }
  68436. }
  68437. else {
  68438. callback(-1);
  68439. }
  68440. };
  68441. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68442. var _this = this;
  68443. var completeUrl = Database.ReturnFullUrlLocation(url);
  68444. var saveAndLoadFile = function () {
  68445. // the scene is not yet in the DB, let's try to save it
  68446. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68447. };
  68448. this._checkVersionFromDB(completeUrl, function (version) {
  68449. if (version !== -1) {
  68450. if (!_this.mustUpdateRessources) {
  68451. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68452. }
  68453. else {
  68454. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68455. }
  68456. }
  68457. else {
  68458. if (errorCallback) {
  68459. errorCallback();
  68460. }
  68461. }
  68462. });
  68463. };
  68464. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68465. if (this.isSupported && this.db) {
  68466. var targetStore;
  68467. if (url.indexOf(".babylon") !== -1) {
  68468. targetStore = "scenes";
  68469. }
  68470. else {
  68471. targetStore = "textures";
  68472. }
  68473. var file;
  68474. var transaction = this.db.transaction([targetStore]);
  68475. transaction.oncomplete = function (event) {
  68476. if (file) {
  68477. callback(file.data);
  68478. }
  68479. // file was not found in DB
  68480. else {
  68481. notInDBCallback();
  68482. }
  68483. };
  68484. transaction.onabort = function (event) {
  68485. notInDBCallback();
  68486. };
  68487. var getRequest = transaction.objectStore(targetStore).get(url);
  68488. getRequest.onsuccess = function (event) {
  68489. file = (event.target).result;
  68490. };
  68491. getRequest.onerror = function (event) {
  68492. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68493. notInDBCallback();
  68494. };
  68495. }
  68496. else {
  68497. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68498. callback();
  68499. }
  68500. };
  68501. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68502. var _this = this;
  68503. if (this.isSupported) {
  68504. var targetStore;
  68505. if (url.indexOf(".babylon") !== -1) {
  68506. targetStore = "scenes";
  68507. }
  68508. else {
  68509. targetStore = "textures";
  68510. }
  68511. // Create XHR
  68512. var xhr = new XMLHttpRequest();
  68513. var fileData;
  68514. xhr.open("GET", url, true);
  68515. if (useArrayBuffer) {
  68516. xhr.responseType = "arraybuffer";
  68517. }
  68518. if (progressCallback) {
  68519. xhr.onprogress = progressCallback;
  68520. }
  68521. xhr.addEventListener("load", function () {
  68522. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68523. // Blob as response (XHR2)
  68524. //fileData = xhr.responseText;
  68525. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68526. if (!_this.hasReachedQuota && _this.db) {
  68527. // Open a transaction to the database
  68528. var transaction = _this.db.transaction([targetStore], "readwrite");
  68529. // the transaction could abort because of a QuotaExceededError error
  68530. transaction.onabort = function (event) {
  68531. try {
  68532. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68533. var error = event.srcElement['error'];
  68534. if (error && error.name === "QuotaExceededError") {
  68535. _this.hasReachedQuota = true;
  68536. }
  68537. }
  68538. catch (ex) { }
  68539. callback(fileData);
  68540. };
  68541. transaction.oncomplete = function (event) {
  68542. callback(fileData);
  68543. };
  68544. var newFile;
  68545. if (targetStore === "scenes") {
  68546. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68547. }
  68548. else {
  68549. newFile = { textureUrl: url, data: fileData };
  68550. }
  68551. try {
  68552. // Put the scene into the database
  68553. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68554. addRequest.onsuccess = function (event) {
  68555. };
  68556. addRequest.onerror = function (event) {
  68557. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68558. };
  68559. }
  68560. catch (ex) {
  68561. callback(fileData);
  68562. }
  68563. }
  68564. else {
  68565. callback(fileData);
  68566. }
  68567. }
  68568. else {
  68569. callback();
  68570. }
  68571. }, false);
  68572. xhr.addEventListener("error", function (event) {
  68573. BABYLON.Tools.Error("error on XHR request.");
  68574. callback();
  68575. }, false);
  68576. xhr.send();
  68577. }
  68578. else {
  68579. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68580. callback();
  68581. }
  68582. };
  68583. Database.IsUASupportingBlobStorage = true;
  68584. Database.IDBStorageEnabled = true;
  68585. Database.parseURL = function (url) {
  68586. var a = document.createElement('a');
  68587. a.href = url;
  68588. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68589. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68590. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68591. return absLocation;
  68592. };
  68593. Database.ReturnFullUrlLocation = function (url) {
  68594. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68595. return (Database.parseURL(window.location.href) + url);
  68596. }
  68597. else {
  68598. return url;
  68599. }
  68600. };
  68601. return Database;
  68602. }());
  68603. BABYLON.Database = Database;
  68604. })(BABYLON || (BABYLON = {}));
  68605. //# sourceMappingURL=babylon.database.js.map
  68606. var BABYLON;
  68607. (function (BABYLON) {
  68608. var FresnelParameters = /** @class */ (function () {
  68609. function FresnelParameters() {
  68610. this._isEnabled = true;
  68611. this.leftColor = BABYLON.Color3.White();
  68612. this.rightColor = BABYLON.Color3.Black();
  68613. this.bias = 0;
  68614. this.power = 1;
  68615. }
  68616. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68617. get: function () {
  68618. return this._isEnabled;
  68619. },
  68620. set: function (value) {
  68621. if (this._isEnabled === value) {
  68622. return;
  68623. }
  68624. this._isEnabled = value;
  68625. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68626. },
  68627. enumerable: true,
  68628. configurable: true
  68629. });
  68630. FresnelParameters.prototype.clone = function () {
  68631. var newFresnelParameters = new FresnelParameters();
  68632. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68633. return newFresnelParameters;
  68634. };
  68635. FresnelParameters.prototype.serialize = function () {
  68636. var serializationObject = {};
  68637. serializationObject.isEnabled = this.isEnabled;
  68638. serializationObject.leftColor = this.leftColor.asArray();
  68639. serializationObject.rightColor = this.rightColor.asArray();
  68640. serializationObject.bias = this.bias;
  68641. serializationObject.power = this.power;
  68642. return serializationObject;
  68643. };
  68644. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68645. var fresnelParameters = new FresnelParameters();
  68646. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68647. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68648. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68649. fresnelParameters.bias = parsedFresnelParameters.bias;
  68650. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68651. return fresnelParameters;
  68652. };
  68653. return FresnelParameters;
  68654. }());
  68655. BABYLON.FresnelParameters = FresnelParameters;
  68656. })(BABYLON || (BABYLON = {}));
  68657. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68658. var BABYLON;
  68659. (function (BABYLON) {
  68660. var MultiMaterial = /** @class */ (function (_super) {
  68661. __extends(MultiMaterial, _super);
  68662. function MultiMaterial(name, scene) {
  68663. var _this = _super.call(this, name, scene, true) || this;
  68664. scene.multiMaterials.push(_this);
  68665. _this.subMaterials = new Array();
  68666. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68667. return _this;
  68668. }
  68669. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68670. get: function () {
  68671. return this._subMaterials;
  68672. },
  68673. set: function (value) {
  68674. this._subMaterials = value;
  68675. this._hookArray(value);
  68676. },
  68677. enumerable: true,
  68678. configurable: true
  68679. });
  68680. MultiMaterial.prototype._hookArray = function (array) {
  68681. var _this = this;
  68682. var oldPush = array.push;
  68683. array.push = function () {
  68684. var items = [];
  68685. for (var _i = 0; _i < arguments.length; _i++) {
  68686. items[_i] = arguments[_i];
  68687. }
  68688. var result = oldPush.apply(array, items);
  68689. _this._markAllSubMeshesAsTexturesDirty();
  68690. return result;
  68691. };
  68692. var oldSplice = array.splice;
  68693. array.splice = function (index, deleteCount) {
  68694. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68695. _this._markAllSubMeshesAsTexturesDirty();
  68696. return deleted;
  68697. };
  68698. };
  68699. // Properties
  68700. MultiMaterial.prototype.getSubMaterial = function (index) {
  68701. if (index < 0 || index >= this.subMaterials.length) {
  68702. return this.getScene().defaultMaterial;
  68703. }
  68704. return this.subMaterials[index];
  68705. };
  68706. MultiMaterial.prototype.getActiveTextures = function () {
  68707. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68708. if (subMaterial) {
  68709. return subMaterial.getActiveTextures();
  68710. }
  68711. else {
  68712. return [];
  68713. }
  68714. }));
  68715. var _a;
  68716. };
  68717. // Methods
  68718. MultiMaterial.prototype.getClassName = function () {
  68719. return "MultiMaterial";
  68720. };
  68721. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68722. for (var index = 0; index < this.subMaterials.length; index++) {
  68723. var subMaterial = this.subMaterials[index];
  68724. if (subMaterial) {
  68725. if (subMaterial.storeEffectOnSubMeshes) {
  68726. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68727. return false;
  68728. }
  68729. continue;
  68730. }
  68731. if (!subMaterial.isReady(mesh)) {
  68732. return false;
  68733. }
  68734. }
  68735. }
  68736. return true;
  68737. };
  68738. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68739. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68740. for (var index = 0; index < this.subMaterials.length; index++) {
  68741. var subMaterial = null;
  68742. var current = this.subMaterials[index];
  68743. if (cloneChildren && current) {
  68744. subMaterial = current.clone(name + "-" + current.name);
  68745. }
  68746. else {
  68747. subMaterial = this.subMaterials[index];
  68748. }
  68749. newMultiMaterial.subMaterials.push(subMaterial);
  68750. }
  68751. return newMultiMaterial;
  68752. };
  68753. MultiMaterial.prototype.serialize = function () {
  68754. var serializationObject = {};
  68755. serializationObject.name = this.name;
  68756. serializationObject.id = this.id;
  68757. if (BABYLON.Tags) {
  68758. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68759. }
  68760. serializationObject.materials = [];
  68761. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68762. var subMat = this.subMaterials[matIndex];
  68763. if (subMat) {
  68764. serializationObject.materials.push(subMat.id);
  68765. }
  68766. else {
  68767. serializationObject.materials.push(null);
  68768. }
  68769. }
  68770. return serializationObject;
  68771. };
  68772. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68773. var scene = this.getScene();
  68774. if (!scene) {
  68775. return;
  68776. }
  68777. var index = scene.multiMaterials.indexOf(this);
  68778. if (index >= 0) {
  68779. scene.multiMaterials.splice(index, 1);
  68780. }
  68781. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68782. };
  68783. return MultiMaterial;
  68784. }(BABYLON.Material));
  68785. BABYLON.MultiMaterial = MultiMaterial;
  68786. })(BABYLON || (BABYLON = {}));
  68787. //# sourceMappingURL=babylon.multiMaterial.js.map
  68788. var BABYLON;
  68789. (function (BABYLON) {
  68790. var FreeCameraTouchInput = /** @class */ (function () {
  68791. function FreeCameraTouchInput() {
  68792. this._offsetX = null;
  68793. this._offsetY = null;
  68794. this._pointerPressed = new Array();
  68795. this.touchAngularSensibility = 200000.0;
  68796. this.touchMoveSensibility = 250.0;
  68797. }
  68798. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68799. var _this = this;
  68800. var previousPosition = null;
  68801. if (this._pointerInput === undefined) {
  68802. this._onLostFocus = function (evt) {
  68803. _this._offsetX = null;
  68804. _this._offsetY = null;
  68805. };
  68806. this._pointerInput = function (p, s) {
  68807. var evt = p.event;
  68808. if (evt.pointerType === "mouse") {
  68809. return;
  68810. }
  68811. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68812. if (!noPreventDefault) {
  68813. evt.preventDefault();
  68814. }
  68815. _this._pointerPressed.push(evt.pointerId);
  68816. if (_this._pointerPressed.length !== 1) {
  68817. return;
  68818. }
  68819. previousPosition = {
  68820. x: evt.clientX,
  68821. y: evt.clientY
  68822. };
  68823. }
  68824. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68825. if (!noPreventDefault) {
  68826. evt.preventDefault();
  68827. }
  68828. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68829. if (index === -1) {
  68830. return;
  68831. }
  68832. _this._pointerPressed.splice(index, 1);
  68833. if (index != 0) {
  68834. return;
  68835. }
  68836. previousPosition = null;
  68837. _this._offsetX = null;
  68838. _this._offsetY = null;
  68839. }
  68840. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68841. if (!noPreventDefault) {
  68842. evt.preventDefault();
  68843. }
  68844. if (!previousPosition) {
  68845. return;
  68846. }
  68847. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68848. if (index != 0) {
  68849. return;
  68850. }
  68851. _this._offsetX = evt.clientX - previousPosition.x;
  68852. _this._offsetY = -(evt.clientY - previousPosition.y);
  68853. }
  68854. };
  68855. }
  68856. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  68857. if (this._onLostFocus) {
  68858. element.addEventListener("blur", this._onLostFocus);
  68859. }
  68860. };
  68861. FreeCameraTouchInput.prototype.detachControl = function (element) {
  68862. if (this._pointerInput && element) {
  68863. if (this._observer) {
  68864. this.camera.getScene().onPointerObservable.remove(this._observer);
  68865. this._observer = null;
  68866. }
  68867. if (this._onLostFocus) {
  68868. element.removeEventListener("blur", this._onLostFocus);
  68869. this._onLostFocus = null;
  68870. }
  68871. this._pointerPressed = [];
  68872. this._offsetX = null;
  68873. this._offsetY = null;
  68874. }
  68875. };
  68876. FreeCameraTouchInput.prototype.checkInputs = function () {
  68877. if (this._offsetX && this._offsetY) {
  68878. var camera = this.camera;
  68879. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  68880. if (this._pointerPressed.length > 1) {
  68881. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  68882. }
  68883. else {
  68884. var speed = camera._computeLocalCameraSpeed();
  68885. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  68886. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  68887. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  68888. }
  68889. }
  68890. };
  68891. FreeCameraTouchInput.prototype.getClassName = function () {
  68892. return "FreeCameraTouchInput";
  68893. };
  68894. FreeCameraTouchInput.prototype.getSimpleName = function () {
  68895. return "touch";
  68896. };
  68897. __decorate([
  68898. BABYLON.serialize()
  68899. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  68900. __decorate([
  68901. BABYLON.serialize()
  68902. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  68903. return FreeCameraTouchInput;
  68904. }());
  68905. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  68906. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  68907. })(BABYLON || (BABYLON = {}));
  68908. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  68909. var BABYLON;
  68910. (function (BABYLON) {
  68911. // We're mainly based on the logic defined into the FreeCamera code
  68912. var TouchCamera = /** @class */ (function (_super) {
  68913. __extends(TouchCamera, _super);
  68914. //-- end properties for backward compatibility for inputs
  68915. function TouchCamera(name, position, scene) {
  68916. var _this = _super.call(this, name, position, scene) || this;
  68917. _this.inputs.addTouch();
  68918. _this._setupInputs();
  68919. return _this;
  68920. }
  68921. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  68922. //-- Begin properties for backward compatibility for inputs
  68923. get: function () {
  68924. var touch = this.inputs.attached["touch"];
  68925. if (touch)
  68926. return touch.touchAngularSensibility;
  68927. return 0;
  68928. },
  68929. set: function (value) {
  68930. var touch = this.inputs.attached["touch"];
  68931. if (touch)
  68932. touch.touchAngularSensibility = value;
  68933. },
  68934. enumerable: true,
  68935. configurable: true
  68936. });
  68937. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  68938. get: function () {
  68939. var touch = this.inputs.attached["touch"];
  68940. if (touch)
  68941. return touch.touchMoveSensibility;
  68942. return 0;
  68943. },
  68944. set: function (value) {
  68945. var touch = this.inputs.attached["touch"];
  68946. if (touch)
  68947. touch.touchMoveSensibility = value;
  68948. },
  68949. enumerable: true,
  68950. configurable: true
  68951. });
  68952. TouchCamera.prototype.getClassName = function () {
  68953. return "TouchCamera";
  68954. };
  68955. TouchCamera.prototype._setupInputs = function () {
  68956. var mouse = this.inputs.attached["mouse"];
  68957. if (mouse) {
  68958. mouse.touchEnabled = false;
  68959. }
  68960. };
  68961. return TouchCamera;
  68962. }(BABYLON.FreeCamera));
  68963. BABYLON.TouchCamera = TouchCamera;
  68964. })(BABYLON || (BABYLON = {}));
  68965. //# sourceMappingURL=babylon.touchCamera.js.map
  68966. var BABYLON;
  68967. (function (BABYLON) {
  68968. var ProceduralTexture = /** @class */ (function (_super) {
  68969. __extends(ProceduralTexture, _super);
  68970. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  68971. if (fallbackTexture === void 0) { fallbackTexture = null; }
  68972. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68973. if (isCube === void 0) { isCube = false; }
  68974. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  68975. _this.isCube = isCube;
  68976. _this.isEnabled = true;
  68977. _this._currentRefreshId = -1;
  68978. _this._refreshRate = 1;
  68979. _this._vertexBuffers = {};
  68980. _this._uniforms = new Array();
  68981. _this._samplers = new Array();
  68982. _this._textures = {};
  68983. _this._floats = {};
  68984. _this._floatsArrays = {};
  68985. _this._colors3 = {};
  68986. _this._colors4 = {};
  68987. _this._vectors2 = {};
  68988. _this._vectors3 = {};
  68989. _this._matrices = {};
  68990. _this._fallbackTextureUsed = false;
  68991. scene.proceduralTextures.push(_this);
  68992. _this._engine = scene.getEngine();
  68993. _this.name = name;
  68994. _this.isRenderTarget = true;
  68995. _this._size = size;
  68996. _this._generateMipMaps = generateMipMaps;
  68997. _this.setFragment(fragment);
  68998. _this._fallbackTexture = fallbackTexture;
  68999. if (isCube) {
  69000. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69001. _this.setFloat("face", 0);
  69002. }
  69003. else {
  69004. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69005. }
  69006. // VBO
  69007. var vertices = [];
  69008. vertices.push(1, 1);
  69009. vertices.push(-1, 1);
  69010. vertices.push(-1, -1);
  69011. vertices.push(1, -1);
  69012. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69013. _this._createIndexBuffer();
  69014. return _this;
  69015. }
  69016. ProceduralTexture.prototype._createIndexBuffer = function () {
  69017. var engine = this._engine;
  69018. // Indices
  69019. var indices = [];
  69020. indices.push(0);
  69021. indices.push(1);
  69022. indices.push(2);
  69023. indices.push(0);
  69024. indices.push(2);
  69025. indices.push(3);
  69026. this._indexBuffer = engine.createIndexBuffer(indices);
  69027. };
  69028. ProceduralTexture.prototype._rebuild = function () {
  69029. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69030. if (vb) {
  69031. vb._rebuild();
  69032. }
  69033. this._createIndexBuffer();
  69034. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69035. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69036. }
  69037. };
  69038. ProceduralTexture.prototype.reset = function () {
  69039. if (this._effect === undefined) {
  69040. return;
  69041. }
  69042. var engine = this._engine;
  69043. engine._releaseEffect(this._effect);
  69044. };
  69045. ProceduralTexture.prototype.isReady = function () {
  69046. var _this = this;
  69047. var engine = this._engine;
  69048. var shaders;
  69049. if (!this._fragment) {
  69050. return false;
  69051. }
  69052. if (this._fallbackTextureUsed) {
  69053. return true;
  69054. }
  69055. if (this._fragment.fragmentElement !== undefined) {
  69056. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69057. }
  69058. else {
  69059. shaders = { vertex: "procedural", fragment: this._fragment };
  69060. }
  69061. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69062. _this.releaseInternalTexture();
  69063. if (_this._fallbackTexture) {
  69064. _this._texture = _this._fallbackTexture._texture;
  69065. if (_this._texture) {
  69066. _this._texture.incrementReferences();
  69067. }
  69068. }
  69069. _this._fallbackTextureUsed = true;
  69070. });
  69071. return this._effect.isReady();
  69072. };
  69073. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69074. this._currentRefreshId = -1;
  69075. };
  69076. ProceduralTexture.prototype.setFragment = function (fragment) {
  69077. this._fragment = fragment;
  69078. };
  69079. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69080. get: function () {
  69081. return this._refreshRate;
  69082. },
  69083. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69084. set: function (value) {
  69085. this._refreshRate = value;
  69086. this.resetRefreshCounter();
  69087. },
  69088. enumerable: true,
  69089. configurable: true
  69090. });
  69091. ProceduralTexture.prototype._shouldRender = function () {
  69092. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69093. return false;
  69094. }
  69095. if (this._fallbackTextureUsed) {
  69096. return false;
  69097. }
  69098. if (this._currentRefreshId === -1) { // At least render once
  69099. this._currentRefreshId = 1;
  69100. return true;
  69101. }
  69102. if (this.refreshRate === this._currentRefreshId) {
  69103. this._currentRefreshId = 1;
  69104. return true;
  69105. }
  69106. this._currentRefreshId++;
  69107. return false;
  69108. };
  69109. ProceduralTexture.prototype.getRenderSize = function () {
  69110. return this._size;
  69111. };
  69112. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69113. if (this._fallbackTextureUsed) {
  69114. return;
  69115. }
  69116. this.releaseInternalTexture();
  69117. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69118. };
  69119. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69120. if (this._uniforms.indexOf(uniformName) === -1) {
  69121. this._uniforms.push(uniformName);
  69122. }
  69123. };
  69124. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69125. if (this._samplers.indexOf(name) === -1) {
  69126. this._samplers.push(name);
  69127. }
  69128. this._textures[name] = texture;
  69129. return this;
  69130. };
  69131. ProceduralTexture.prototype.setFloat = function (name, value) {
  69132. this._checkUniform(name);
  69133. this._floats[name] = value;
  69134. return this;
  69135. };
  69136. ProceduralTexture.prototype.setFloats = function (name, value) {
  69137. this._checkUniform(name);
  69138. this._floatsArrays[name] = value;
  69139. return this;
  69140. };
  69141. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69142. this._checkUniform(name);
  69143. this._colors3[name] = value;
  69144. return this;
  69145. };
  69146. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69147. this._checkUniform(name);
  69148. this._colors4[name] = value;
  69149. return this;
  69150. };
  69151. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69152. this._checkUniform(name);
  69153. this._vectors2[name] = value;
  69154. return this;
  69155. };
  69156. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69157. this._checkUniform(name);
  69158. this._vectors3[name] = value;
  69159. return this;
  69160. };
  69161. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69162. this._checkUniform(name);
  69163. this._matrices[name] = value;
  69164. return this;
  69165. };
  69166. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69167. var scene = this.getScene();
  69168. if (!scene) {
  69169. return;
  69170. }
  69171. var engine = this._engine;
  69172. // Render
  69173. engine.enableEffect(this._effect);
  69174. engine.setState(false);
  69175. // Texture
  69176. for (var name in this._textures) {
  69177. this._effect.setTexture(name, this._textures[name]);
  69178. }
  69179. // Float
  69180. for (name in this._floats) {
  69181. this._effect.setFloat(name, this._floats[name]);
  69182. }
  69183. // Floats
  69184. for (name in this._floatsArrays) {
  69185. this._effect.setArray(name, this._floatsArrays[name]);
  69186. }
  69187. // Color3
  69188. for (name in this._colors3) {
  69189. this._effect.setColor3(name, this._colors3[name]);
  69190. }
  69191. // Color4
  69192. for (name in this._colors4) {
  69193. var color = this._colors4[name];
  69194. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69195. }
  69196. // Vector2
  69197. for (name in this._vectors2) {
  69198. this._effect.setVector2(name, this._vectors2[name]);
  69199. }
  69200. // Vector3
  69201. for (name in this._vectors3) {
  69202. this._effect.setVector3(name, this._vectors3[name]);
  69203. }
  69204. // Matrix
  69205. for (name in this._matrices) {
  69206. this._effect.setMatrix(name, this._matrices[name]);
  69207. }
  69208. if (!this._texture) {
  69209. return;
  69210. }
  69211. if (this.isCube) {
  69212. for (var face = 0; face < 6; face++) {
  69213. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69214. // VBOs
  69215. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69216. this._effect.setFloat("face", face);
  69217. // Clear
  69218. engine.clear(scene.clearColor, true, true, true);
  69219. // Draw order
  69220. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69221. // Mipmaps
  69222. if (face === 5) {
  69223. engine.generateMipMapsForCubemap(this._texture);
  69224. }
  69225. }
  69226. }
  69227. else {
  69228. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69229. // VBOs
  69230. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69231. // Clear
  69232. engine.clear(scene.clearColor, true, true, true);
  69233. // Draw order
  69234. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69235. }
  69236. // Unbind
  69237. engine.unBindFramebuffer(this._texture, this.isCube);
  69238. if (this.onGenerated) {
  69239. this.onGenerated();
  69240. }
  69241. };
  69242. ProceduralTexture.prototype.clone = function () {
  69243. var textureSize = this.getSize();
  69244. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69245. // Base texture
  69246. newTexture.hasAlpha = this.hasAlpha;
  69247. newTexture.level = this.level;
  69248. // RenderTarget Texture
  69249. newTexture.coordinatesMode = this.coordinatesMode;
  69250. return newTexture;
  69251. };
  69252. ProceduralTexture.prototype.dispose = function () {
  69253. var scene = this.getScene();
  69254. if (!scene) {
  69255. return;
  69256. }
  69257. var index = scene.proceduralTextures.indexOf(this);
  69258. if (index >= 0) {
  69259. scene.proceduralTextures.splice(index, 1);
  69260. }
  69261. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69262. if (vertexBuffer) {
  69263. vertexBuffer.dispose();
  69264. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69265. }
  69266. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69267. this._indexBuffer = null;
  69268. }
  69269. _super.prototype.dispose.call(this);
  69270. };
  69271. return ProceduralTexture;
  69272. }(BABYLON.Texture));
  69273. BABYLON.ProceduralTexture = ProceduralTexture;
  69274. })(BABYLON || (BABYLON = {}));
  69275. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69276. var BABYLON;
  69277. (function (BABYLON) {
  69278. var CustomProceduralTexture = /** @class */ (function (_super) {
  69279. __extends(CustomProceduralTexture, _super);
  69280. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69281. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69282. _this._animate = true;
  69283. _this._time = 0;
  69284. _this._texturePath = texturePath;
  69285. //Try to load json
  69286. _this.loadJson(texturePath);
  69287. _this.refreshRate = 1;
  69288. return _this;
  69289. }
  69290. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69291. var _this = this;
  69292. var noConfigFile = function () {
  69293. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69294. try {
  69295. _this.setFragment(_this._texturePath);
  69296. }
  69297. catch (ex) {
  69298. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69299. }
  69300. };
  69301. var configFileUrl = jsonUrl + "/config.json";
  69302. var xhr = new XMLHttpRequest();
  69303. xhr.open("GET", configFileUrl, true);
  69304. xhr.addEventListener("load", function () {
  69305. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69306. try {
  69307. _this._config = JSON.parse(xhr.response);
  69308. _this.updateShaderUniforms();
  69309. _this.updateTextures();
  69310. _this.setFragment(_this._texturePath + "/custom");
  69311. _this._animate = _this._config.animate;
  69312. _this.refreshRate = _this._config.refreshrate;
  69313. }
  69314. catch (ex) {
  69315. noConfigFile();
  69316. }
  69317. }
  69318. else {
  69319. noConfigFile();
  69320. }
  69321. }, false);
  69322. xhr.addEventListener("error", function () {
  69323. noConfigFile();
  69324. }, false);
  69325. try {
  69326. xhr.send();
  69327. }
  69328. catch (ex) {
  69329. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69330. }
  69331. };
  69332. CustomProceduralTexture.prototype.isReady = function () {
  69333. if (!_super.prototype.isReady.call(this)) {
  69334. return false;
  69335. }
  69336. for (var name in this._textures) {
  69337. var texture = this._textures[name];
  69338. if (!texture.isReady()) {
  69339. return false;
  69340. }
  69341. }
  69342. return true;
  69343. };
  69344. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69345. var scene = this.getScene();
  69346. if (this._animate && scene) {
  69347. this._time += scene.getAnimationRatio() * 0.03;
  69348. this.updateShaderUniforms();
  69349. }
  69350. _super.prototype.render.call(this, useCameraPostProcess);
  69351. };
  69352. CustomProceduralTexture.prototype.updateTextures = function () {
  69353. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69354. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69355. }
  69356. };
  69357. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69358. if (this._config) {
  69359. for (var j = 0; j < this._config.uniforms.length; j++) {
  69360. var uniform = this._config.uniforms[j];
  69361. switch (uniform.type) {
  69362. case "float":
  69363. this.setFloat(uniform.name, uniform.value);
  69364. break;
  69365. case "color3":
  69366. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69367. break;
  69368. case "color4":
  69369. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69370. break;
  69371. case "vector2":
  69372. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69373. break;
  69374. case "vector3":
  69375. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69376. break;
  69377. }
  69378. }
  69379. }
  69380. this.setFloat("time", this._time);
  69381. };
  69382. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69383. get: function () {
  69384. return this._animate;
  69385. },
  69386. set: function (value) {
  69387. this._animate = value;
  69388. },
  69389. enumerable: true,
  69390. configurable: true
  69391. });
  69392. return CustomProceduralTexture;
  69393. }(BABYLON.ProceduralTexture));
  69394. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69395. })(BABYLON || (BABYLON = {}));
  69396. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69397. var BABYLON;
  69398. (function (BABYLON) {
  69399. var FreeCameraGamepadInput = /** @class */ (function () {
  69400. function FreeCameraGamepadInput() {
  69401. this.gamepadAngularSensibility = 200;
  69402. this.gamepadMoveSensibility = 40;
  69403. // private members
  69404. this._cameraTransform = BABYLON.Matrix.Identity();
  69405. this._deltaTransform = BABYLON.Vector3.Zero();
  69406. this._vector3 = BABYLON.Vector3.Zero();
  69407. this._vector2 = BABYLON.Vector2.Zero();
  69408. }
  69409. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69410. var _this = this;
  69411. var manager = this.camera.getScene().gamepadManager;
  69412. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69413. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69414. // prioritize XBOX gamepads.
  69415. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69416. _this.gamepad = gamepad;
  69417. }
  69418. }
  69419. });
  69420. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69421. if (_this.gamepad === gamepad) {
  69422. _this.gamepad = null;
  69423. }
  69424. });
  69425. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69426. };
  69427. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69428. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69429. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69430. this.gamepad = null;
  69431. };
  69432. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69433. if (this.gamepad && this.gamepad.leftStick) {
  69434. var camera = this.camera;
  69435. var LSValues = this.gamepad.leftStick;
  69436. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69437. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69438. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69439. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69440. var RSValues = this.gamepad.rightStick;
  69441. if (RSValues) {
  69442. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69443. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69444. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69445. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69446. }
  69447. else {
  69448. RSValues = { x: 0, y: 0 };
  69449. }
  69450. if (!camera.rotationQuaternion) {
  69451. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69452. }
  69453. else {
  69454. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69455. }
  69456. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69457. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69458. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69459. camera.cameraDirection.addInPlace(this._deltaTransform);
  69460. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69461. camera.cameraRotation.addInPlace(this._vector2);
  69462. }
  69463. };
  69464. FreeCameraGamepadInput.prototype.getClassName = function () {
  69465. return "FreeCameraGamepadInput";
  69466. };
  69467. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69468. return "gamepad";
  69469. };
  69470. __decorate([
  69471. BABYLON.serialize()
  69472. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69473. __decorate([
  69474. BABYLON.serialize()
  69475. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69476. return FreeCameraGamepadInput;
  69477. }());
  69478. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69479. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69480. })(BABYLON || (BABYLON = {}));
  69481. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69482. var BABYLON;
  69483. (function (BABYLON) {
  69484. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69485. function ArcRotateCameraGamepadInput() {
  69486. this.gamepadRotationSensibility = 80;
  69487. this.gamepadMoveSensibility = 40;
  69488. }
  69489. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69490. var _this = this;
  69491. var manager = this.camera.getScene().gamepadManager;
  69492. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69493. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69494. // prioritize XBOX gamepads.
  69495. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69496. _this.gamepad = gamepad;
  69497. }
  69498. }
  69499. });
  69500. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69501. if (_this.gamepad === gamepad) {
  69502. _this.gamepad = null;
  69503. }
  69504. });
  69505. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69506. };
  69507. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69508. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69509. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69510. this.gamepad = null;
  69511. };
  69512. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69513. if (this.gamepad) {
  69514. var camera = this.camera;
  69515. var RSValues = this.gamepad.rightStick;
  69516. if (RSValues) {
  69517. if (RSValues.x != 0) {
  69518. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69519. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69520. camera.inertialAlphaOffset += normalizedRX;
  69521. }
  69522. }
  69523. if (RSValues.y != 0) {
  69524. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69525. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69526. camera.inertialBetaOffset += normalizedRY;
  69527. }
  69528. }
  69529. }
  69530. var LSValues = this.gamepad.leftStick;
  69531. if (LSValues && LSValues.y != 0) {
  69532. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69533. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69534. this.camera.inertialRadiusOffset -= normalizedLY;
  69535. }
  69536. }
  69537. }
  69538. };
  69539. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69540. return "ArcRotateCameraGamepadInput";
  69541. };
  69542. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69543. return "gamepad";
  69544. };
  69545. __decorate([
  69546. BABYLON.serialize()
  69547. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69548. __decorate([
  69549. BABYLON.serialize()
  69550. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69551. return ArcRotateCameraGamepadInput;
  69552. }());
  69553. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69554. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69555. })(BABYLON || (BABYLON = {}));
  69556. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69557. var BABYLON;
  69558. (function (BABYLON) {
  69559. var GamepadManager = /** @class */ (function () {
  69560. function GamepadManager(_scene) {
  69561. var _this = this;
  69562. this._scene = _scene;
  69563. this._babylonGamepads = [];
  69564. this._oneGamepadConnected = false;
  69565. this._isMonitoring = false;
  69566. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69567. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69568. this._gamepadEventSupported = false;
  69569. }
  69570. else {
  69571. this._gamepadEventSupported = 'GamepadEvent' in window;
  69572. this._gamepadSupport = (navigator.getGamepads ||
  69573. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69574. }
  69575. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69576. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69577. for (var i in _this._babylonGamepads) {
  69578. var gamepad = _this._babylonGamepads[i];
  69579. if (gamepad && gamepad._isConnected) {
  69580. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69581. }
  69582. }
  69583. });
  69584. this._onGamepadConnectedEvent = function (evt) {
  69585. var gamepad = evt.gamepad;
  69586. if (gamepad.index in _this._babylonGamepads) {
  69587. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69588. return;
  69589. }
  69590. }
  69591. var newGamepad;
  69592. if (_this._babylonGamepads[gamepad.index]) {
  69593. newGamepad = _this._babylonGamepads[gamepad.index];
  69594. newGamepad.browserGamepad = gamepad;
  69595. newGamepad._isConnected = true;
  69596. }
  69597. else {
  69598. newGamepad = _this._addNewGamepad(gamepad);
  69599. }
  69600. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69601. _this._startMonitoringGamepads();
  69602. };
  69603. this._onGamepadDisconnectedEvent = function (evt) {
  69604. var gamepad = evt.gamepad;
  69605. // Remove the gamepad from the list of gamepads to monitor.
  69606. for (var i in _this._babylonGamepads) {
  69607. if (_this._babylonGamepads[i].index === gamepad.index) {
  69608. var disconnectedGamepad = _this._babylonGamepads[i];
  69609. disconnectedGamepad._isConnected = false;
  69610. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69611. break;
  69612. }
  69613. }
  69614. };
  69615. if (this._gamepadSupport) {
  69616. //first add already-connected gamepads
  69617. this._updateGamepadObjects();
  69618. if (this._babylonGamepads.length) {
  69619. this._startMonitoringGamepads();
  69620. }
  69621. // Checking if the gamepad connected event is supported (like in Firefox)
  69622. if (this._gamepadEventSupported) {
  69623. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69624. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69625. }
  69626. else {
  69627. this._startMonitoringGamepads();
  69628. }
  69629. }
  69630. }
  69631. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69632. get: function () {
  69633. return this._babylonGamepads;
  69634. },
  69635. enumerable: true,
  69636. configurable: true
  69637. });
  69638. GamepadManager.prototype.getGamepadByType = function (type) {
  69639. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69640. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69641. var gamepad = _a[_i];
  69642. if (gamepad && gamepad.type === type) {
  69643. return gamepad;
  69644. }
  69645. }
  69646. return null;
  69647. };
  69648. GamepadManager.prototype.dispose = function () {
  69649. if (this._gamepadEventSupported) {
  69650. if (this._onGamepadConnectedEvent) {
  69651. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69652. }
  69653. if (this._onGamepadDisconnectedEvent) {
  69654. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69655. }
  69656. this._onGamepadConnectedEvent = null;
  69657. this._onGamepadDisconnectedEvent = null;
  69658. }
  69659. this._babylonGamepads.forEach(function (gamepad) {
  69660. gamepad.dispose();
  69661. });
  69662. this.onGamepadConnectedObservable.clear();
  69663. this.onGamepadDisconnectedObservable.clear();
  69664. this._oneGamepadConnected = false;
  69665. this._stopMonitoringGamepads();
  69666. this._babylonGamepads = [];
  69667. };
  69668. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69669. if (!this._oneGamepadConnected) {
  69670. this._oneGamepadConnected = true;
  69671. }
  69672. var newGamepad;
  69673. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69674. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69675. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69676. }
  69677. // if pose is supported, use the (WebVR) pose enabled controller
  69678. else if (gamepad.pose) {
  69679. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69680. }
  69681. else {
  69682. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69683. }
  69684. this._babylonGamepads[newGamepad.index] = newGamepad;
  69685. return newGamepad;
  69686. };
  69687. GamepadManager.prototype._startMonitoringGamepads = function () {
  69688. if (!this._isMonitoring) {
  69689. this._isMonitoring = true;
  69690. //back-comp
  69691. if (!this._scene) {
  69692. this._checkGamepadsStatus();
  69693. }
  69694. }
  69695. };
  69696. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69697. this._isMonitoring = false;
  69698. };
  69699. GamepadManager.prototype._checkGamepadsStatus = function () {
  69700. var _this = this;
  69701. // Hack to be compatible Chrome
  69702. this._updateGamepadObjects();
  69703. for (var i in this._babylonGamepads) {
  69704. var gamepad = this._babylonGamepads[i];
  69705. if (!gamepad || !gamepad.isConnected) {
  69706. continue;
  69707. }
  69708. gamepad.update();
  69709. }
  69710. if (this._isMonitoring && !this._scene) {
  69711. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69712. }
  69713. };
  69714. // This function is called only on Chrome, which does not properly support
  69715. // connection/disconnection events and forces you to recopy again the gamepad object
  69716. GamepadManager.prototype._updateGamepadObjects = function () {
  69717. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69718. for (var i = 0; i < gamepads.length; i++) {
  69719. var gamepad = gamepads[i];
  69720. if (gamepad) {
  69721. if (!this._babylonGamepads[gamepad.index]) {
  69722. var newGamepad = this._addNewGamepad(gamepad);
  69723. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69724. }
  69725. else {
  69726. // Forced to copy again this object for Chrome for unknown reason
  69727. this._babylonGamepads[i].browserGamepad = gamepad;
  69728. if (!this._babylonGamepads[i].isConnected) {
  69729. this._babylonGamepads[i]._isConnected = true;
  69730. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69731. }
  69732. }
  69733. }
  69734. }
  69735. };
  69736. return GamepadManager;
  69737. }());
  69738. BABYLON.GamepadManager = GamepadManager;
  69739. })(BABYLON || (BABYLON = {}));
  69740. //# sourceMappingURL=babylon.gamepadManager.js.map
  69741. var BABYLON;
  69742. (function (BABYLON) {
  69743. var StickValues = /** @class */ (function () {
  69744. function StickValues(x, y) {
  69745. this.x = x;
  69746. this.y = y;
  69747. }
  69748. return StickValues;
  69749. }());
  69750. BABYLON.StickValues = StickValues;
  69751. var Gamepad = /** @class */ (function () {
  69752. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69753. if (leftStickX === void 0) { leftStickX = 0; }
  69754. if (leftStickY === void 0) { leftStickY = 1; }
  69755. if (rightStickX === void 0) { rightStickX = 2; }
  69756. if (rightStickY === void 0) { rightStickY = 3; }
  69757. this.id = id;
  69758. this.index = index;
  69759. this.browserGamepad = browserGamepad;
  69760. this._isConnected = true;
  69761. this._invertLeftStickY = false;
  69762. this.type = Gamepad.GAMEPAD;
  69763. this._leftStickAxisX = leftStickX;
  69764. this._leftStickAxisY = leftStickY;
  69765. this._rightStickAxisX = rightStickX;
  69766. this._rightStickAxisY = rightStickY;
  69767. if (this.browserGamepad.axes.length >= 2) {
  69768. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69769. }
  69770. if (this.browserGamepad.axes.length >= 4) {
  69771. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69772. }
  69773. }
  69774. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69775. get: function () {
  69776. return this._isConnected;
  69777. },
  69778. enumerable: true,
  69779. configurable: true
  69780. });
  69781. Gamepad.prototype.onleftstickchanged = function (callback) {
  69782. this._onleftstickchanged = callback;
  69783. };
  69784. Gamepad.prototype.onrightstickchanged = function (callback) {
  69785. this._onrightstickchanged = callback;
  69786. };
  69787. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69788. get: function () {
  69789. return this._leftStick;
  69790. },
  69791. set: function (newValues) {
  69792. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69793. this._onleftstickchanged(newValues);
  69794. }
  69795. this._leftStick = newValues;
  69796. },
  69797. enumerable: true,
  69798. configurable: true
  69799. });
  69800. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69801. get: function () {
  69802. return this._rightStick;
  69803. },
  69804. set: function (newValues) {
  69805. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69806. this._onrightstickchanged(newValues);
  69807. }
  69808. this._rightStick = newValues;
  69809. },
  69810. enumerable: true,
  69811. configurable: true
  69812. });
  69813. Gamepad.prototype.update = function () {
  69814. if (this._leftStick) {
  69815. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69816. if (this._invertLeftStickY) {
  69817. this.leftStick.y *= -1;
  69818. }
  69819. }
  69820. if (this._rightStick) {
  69821. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69822. }
  69823. };
  69824. Gamepad.prototype.dispose = function () {
  69825. };
  69826. Gamepad.GAMEPAD = 0;
  69827. Gamepad.GENERIC = 1;
  69828. Gamepad.XBOX = 2;
  69829. Gamepad.POSE_ENABLED = 3;
  69830. return Gamepad;
  69831. }());
  69832. BABYLON.Gamepad = Gamepad;
  69833. var GenericPad = /** @class */ (function (_super) {
  69834. __extends(GenericPad, _super);
  69835. function GenericPad(id, index, browserGamepad) {
  69836. var _this = _super.call(this, id, index, browserGamepad) || this;
  69837. _this.onButtonDownObservable = new BABYLON.Observable();
  69838. _this.onButtonUpObservable = new BABYLON.Observable();
  69839. _this.type = Gamepad.GENERIC;
  69840. _this._buttons = new Array(browserGamepad.buttons.length);
  69841. return _this;
  69842. }
  69843. GenericPad.prototype.onbuttondown = function (callback) {
  69844. this._onbuttondown = callback;
  69845. };
  69846. GenericPad.prototype.onbuttonup = function (callback) {
  69847. this._onbuttonup = callback;
  69848. };
  69849. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  69850. if (newValue !== currentValue) {
  69851. if (newValue === 1) {
  69852. if (this._onbuttondown) {
  69853. this._onbuttondown(buttonIndex);
  69854. }
  69855. this.onButtonDownObservable.notifyObservers(buttonIndex);
  69856. }
  69857. if (newValue === 0) {
  69858. if (this._onbuttonup) {
  69859. this._onbuttonup(buttonIndex);
  69860. }
  69861. this.onButtonUpObservable.notifyObservers(buttonIndex);
  69862. }
  69863. }
  69864. return newValue;
  69865. };
  69866. GenericPad.prototype.update = function () {
  69867. _super.prototype.update.call(this);
  69868. for (var index = 0; index < this._buttons.length; index++) {
  69869. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  69870. }
  69871. };
  69872. GenericPad.prototype.dispose = function () {
  69873. _super.prototype.dispose.call(this);
  69874. this.onButtonDownObservable.clear();
  69875. this.onButtonUpObservable.clear();
  69876. };
  69877. return GenericPad;
  69878. }(Gamepad));
  69879. BABYLON.GenericPad = GenericPad;
  69880. })(BABYLON || (BABYLON = {}));
  69881. //# sourceMappingURL=babylon.gamepad.js.map
  69882. var BABYLON;
  69883. (function (BABYLON) {
  69884. /**
  69885. * Defines supported buttons for XBox360 compatible gamepads
  69886. */
  69887. var Xbox360Button;
  69888. (function (Xbox360Button) {
  69889. /** A */
  69890. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  69891. /** B */
  69892. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  69893. /** X */
  69894. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  69895. /** Y */
  69896. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  69897. /** Start */
  69898. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  69899. /** Back */
  69900. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  69901. /** Left button */
  69902. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  69903. /** Right button */
  69904. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  69905. /** Left stick */
  69906. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  69907. /** Right stick */
  69908. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  69909. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  69910. /** Defines values for XBox360 DPad */
  69911. var Xbox360Dpad;
  69912. (function (Xbox360Dpad) {
  69913. /** Up */
  69914. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  69915. /** Down */
  69916. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  69917. /** Left */
  69918. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  69919. /** Right */
  69920. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  69921. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  69922. /**
  69923. * Defines a XBox360 gamepad
  69924. */
  69925. var Xbox360Pad = /** @class */ (function (_super) {
  69926. __extends(Xbox360Pad, _super);
  69927. /**
  69928. * Creates a new XBox360 gamepad object
  69929. * @param id defines the id of this gamepad
  69930. * @param index defines its index
  69931. * @param gamepad defines the internal HTML gamepad object
  69932. * @param xboxOne defines if it is a XBox One gamepad
  69933. */
  69934. function Xbox360Pad(id, index, gamepad, xboxOne) {
  69935. if (xboxOne === void 0) { xboxOne = false; }
  69936. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  69937. _this._leftTrigger = 0;
  69938. _this._rightTrigger = 0;
  69939. /** Observable raised when a button is pressed */
  69940. _this.onButtonDownObservable = new BABYLON.Observable();
  69941. /** Observable raised when a button is released */
  69942. _this.onButtonUpObservable = new BABYLON.Observable();
  69943. /** Observable raised when a pad is pressed */
  69944. _this.onPadDownObservable = new BABYLON.Observable();
  69945. /** Observable raised when a pad is released */
  69946. _this.onPadUpObservable = new BABYLON.Observable();
  69947. _this._buttonA = 0;
  69948. _this._buttonB = 0;
  69949. _this._buttonX = 0;
  69950. _this._buttonY = 0;
  69951. _this._buttonBack = 0;
  69952. _this._buttonStart = 0;
  69953. _this._buttonLB = 0;
  69954. _this._buttonRB = 0;
  69955. _this._buttonLeftStick = 0;
  69956. _this._buttonRightStick = 0;
  69957. _this._dPadUp = 0;
  69958. _this._dPadDown = 0;
  69959. _this._dPadLeft = 0;
  69960. _this._dPadRight = 0;
  69961. _this._isXboxOnePad = false;
  69962. _this.type = BABYLON.Gamepad.XBOX;
  69963. _this._isXboxOnePad = xboxOne;
  69964. return _this;
  69965. }
  69966. /**
  69967. * Defines the callback to call when left trigger is pressed
  69968. * @param callback defines the callback to use
  69969. */
  69970. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  69971. this._onlefttriggerchanged = callback;
  69972. };
  69973. /**
  69974. * Defines the callback to call when right trigger is pressed
  69975. * @param callback defines the callback to use
  69976. */
  69977. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  69978. this._onrighttriggerchanged = callback;
  69979. };
  69980. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  69981. /**
  69982. * Gets or sets left trigger value
  69983. */
  69984. get: function () {
  69985. return this._leftTrigger;
  69986. },
  69987. set: function (newValue) {
  69988. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  69989. this._onlefttriggerchanged(newValue);
  69990. }
  69991. this._leftTrigger = newValue;
  69992. },
  69993. enumerable: true,
  69994. configurable: true
  69995. });
  69996. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  69997. /**
  69998. * Gets or sets right trigger value
  69999. */
  70000. get: function () {
  70001. return this._rightTrigger;
  70002. },
  70003. set: function (newValue) {
  70004. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70005. this._onrighttriggerchanged(newValue);
  70006. }
  70007. this._rightTrigger = newValue;
  70008. },
  70009. enumerable: true,
  70010. configurable: true
  70011. });
  70012. /**
  70013. * Defines the callback to call when a button is pressed
  70014. * @param callback defines the callback to use
  70015. */
  70016. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70017. this._onbuttondown = callback;
  70018. };
  70019. /**
  70020. * Defines the callback to call when a button is released
  70021. * @param callback defines the callback to use
  70022. */
  70023. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70024. this._onbuttonup = callback;
  70025. };
  70026. /**
  70027. * Defines the callback to call when a pad is pressed
  70028. * @param callback defines the callback to use
  70029. */
  70030. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70031. this._ondpaddown = callback;
  70032. };
  70033. /**
  70034. * Defines the callback to call when a pad is released
  70035. * @param callback defines the callback to use
  70036. */
  70037. Xbox360Pad.prototype.ondpadup = function (callback) {
  70038. this._ondpadup = callback;
  70039. };
  70040. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70041. if (newValue !== currentValue) {
  70042. if (newValue === 1) {
  70043. if (this._onbuttondown) {
  70044. this._onbuttondown(buttonType);
  70045. }
  70046. this.onButtonDownObservable.notifyObservers(buttonType);
  70047. }
  70048. if (newValue === 0) {
  70049. if (this._onbuttonup) {
  70050. this._onbuttonup(buttonType);
  70051. }
  70052. this.onButtonUpObservable.notifyObservers(buttonType);
  70053. }
  70054. }
  70055. return newValue;
  70056. };
  70057. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70058. if (newValue !== currentValue) {
  70059. if (newValue === 1) {
  70060. if (this._ondpaddown) {
  70061. this._ondpaddown(buttonType);
  70062. }
  70063. this.onPadDownObservable.notifyObservers(buttonType);
  70064. }
  70065. if (newValue === 0) {
  70066. if (this._ondpadup) {
  70067. this._ondpadup(buttonType);
  70068. }
  70069. this.onPadUpObservable.notifyObservers(buttonType);
  70070. }
  70071. }
  70072. return newValue;
  70073. };
  70074. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70075. /** Gets or sets value of A button */
  70076. get: function () {
  70077. return this._buttonA;
  70078. },
  70079. set: function (value) {
  70080. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70081. },
  70082. enumerable: true,
  70083. configurable: true
  70084. });
  70085. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70086. /** Gets or sets value of B button */
  70087. get: function () {
  70088. return this._buttonB;
  70089. },
  70090. set: function (value) {
  70091. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70092. },
  70093. enumerable: true,
  70094. configurable: true
  70095. });
  70096. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70097. /** Gets or sets value of X button */
  70098. get: function () {
  70099. return this._buttonX;
  70100. },
  70101. set: function (value) {
  70102. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70103. },
  70104. enumerable: true,
  70105. configurable: true
  70106. });
  70107. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70108. /** Gets or sets value of Y button */
  70109. get: function () {
  70110. return this._buttonY;
  70111. },
  70112. set: function (value) {
  70113. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70114. },
  70115. enumerable: true,
  70116. configurable: true
  70117. });
  70118. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70119. /** Gets or sets value of Start button */
  70120. get: function () {
  70121. return this._buttonStart;
  70122. },
  70123. set: function (value) {
  70124. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70125. },
  70126. enumerable: true,
  70127. configurable: true
  70128. });
  70129. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70130. /** Gets or sets value of Back button */
  70131. get: function () {
  70132. return this._buttonBack;
  70133. },
  70134. set: function (value) {
  70135. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70136. },
  70137. enumerable: true,
  70138. configurable: true
  70139. });
  70140. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70141. /** Gets or sets value of Left button */
  70142. get: function () {
  70143. return this._buttonLB;
  70144. },
  70145. set: function (value) {
  70146. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70147. },
  70148. enumerable: true,
  70149. configurable: true
  70150. });
  70151. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70152. /** Gets or sets value of Right button */
  70153. get: function () {
  70154. return this._buttonRB;
  70155. },
  70156. set: function (value) {
  70157. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70158. },
  70159. enumerable: true,
  70160. configurable: true
  70161. });
  70162. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70163. /** Gets or sets value of left stick */
  70164. get: function () {
  70165. return this._buttonLeftStick;
  70166. },
  70167. set: function (value) {
  70168. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70169. },
  70170. enumerable: true,
  70171. configurable: true
  70172. });
  70173. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70174. /** Gets or sets value of right stick */
  70175. get: function () {
  70176. return this._buttonRightStick;
  70177. },
  70178. set: function (value) {
  70179. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70180. },
  70181. enumerable: true,
  70182. configurable: true
  70183. });
  70184. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70185. /** Gets or sets value of DPad up */
  70186. get: function () {
  70187. return this._dPadUp;
  70188. },
  70189. set: function (value) {
  70190. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70191. },
  70192. enumerable: true,
  70193. configurable: true
  70194. });
  70195. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70196. /** Gets or sets value of DPad down */
  70197. get: function () {
  70198. return this._dPadDown;
  70199. },
  70200. set: function (value) {
  70201. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70202. },
  70203. enumerable: true,
  70204. configurable: true
  70205. });
  70206. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70207. /** Gets or sets value of DPad left */
  70208. get: function () {
  70209. return this._dPadLeft;
  70210. },
  70211. set: function (value) {
  70212. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70213. },
  70214. enumerable: true,
  70215. configurable: true
  70216. });
  70217. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70218. /** Gets or sets value of DPad right */
  70219. get: function () {
  70220. return this._dPadRight;
  70221. },
  70222. set: function (value) {
  70223. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70224. },
  70225. enumerable: true,
  70226. configurable: true
  70227. });
  70228. /**
  70229. * Force the gamepad to synchronize with device values
  70230. */
  70231. Xbox360Pad.prototype.update = function () {
  70232. _super.prototype.update.call(this);
  70233. if (this._isXboxOnePad) {
  70234. this.buttonA = this.browserGamepad.buttons[0].value;
  70235. this.buttonB = this.browserGamepad.buttons[1].value;
  70236. this.buttonX = this.browserGamepad.buttons[2].value;
  70237. this.buttonY = this.browserGamepad.buttons[3].value;
  70238. this.buttonLB = this.browserGamepad.buttons[4].value;
  70239. this.buttonRB = this.browserGamepad.buttons[5].value;
  70240. this.leftTrigger = this.browserGamepad.axes[2];
  70241. this.rightTrigger = this.browserGamepad.axes[5];
  70242. this.buttonBack = this.browserGamepad.buttons[9].value;
  70243. this.buttonStart = this.browserGamepad.buttons[8].value;
  70244. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70245. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70246. this.dPadUp = this.browserGamepad.buttons[11].value;
  70247. this.dPadDown = this.browserGamepad.buttons[12].value;
  70248. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70249. this.dPadRight = this.browserGamepad.buttons[14].value;
  70250. }
  70251. else {
  70252. this.buttonA = this.browserGamepad.buttons[0].value;
  70253. this.buttonB = this.browserGamepad.buttons[1].value;
  70254. this.buttonX = this.browserGamepad.buttons[2].value;
  70255. this.buttonY = this.browserGamepad.buttons[3].value;
  70256. this.buttonLB = this.browserGamepad.buttons[4].value;
  70257. this.buttonRB = this.browserGamepad.buttons[5].value;
  70258. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70259. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70260. this.buttonBack = this.browserGamepad.buttons[8].value;
  70261. this.buttonStart = this.browserGamepad.buttons[9].value;
  70262. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70263. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70264. this.dPadUp = this.browserGamepad.buttons[12].value;
  70265. this.dPadDown = this.browserGamepad.buttons[13].value;
  70266. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70267. this.dPadRight = this.browserGamepad.buttons[15].value;
  70268. }
  70269. };
  70270. Xbox360Pad.prototype.dispose = function () {
  70271. _super.prototype.dispose.call(this);
  70272. this.onButtonDownObservable.clear();
  70273. this.onButtonUpObservable.clear();
  70274. this.onPadDownObservable.clear();
  70275. this.onPadUpObservable.clear();
  70276. };
  70277. return Xbox360Pad;
  70278. }(BABYLON.Gamepad));
  70279. BABYLON.Xbox360Pad = Xbox360Pad;
  70280. })(BABYLON || (BABYLON = {}));
  70281. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70282. var BABYLON;
  70283. (function (BABYLON) {
  70284. /**
  70285. * Defines the types of pose enabled controllers that are supported
  70286. */
  70287. var PoseEnabledControllerType;
  70288. (function (PoseEnabledControllerType) {
  70289. /**
  70290. * HTC Vive
  70291. */
  70292. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70293. /**
  70294. * Oculus Rift
  70295. */
  70296. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70297. /**
  70298. * Windows mixed reality
  70299. */
  70300. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70301. /**
  70302. * Samsung gear VR
  70303. */
  70304. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70305. /**
  70306. * Google Daydream
  70307. */
  70308. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70309. /**
  70310. * Generic
  70311. */
  70312. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70313. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70314. /**
  70315. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70316. */
  70317. var PoseEnabledControllerHelper = /** @class */ (function () {
  70318. function PoseEnabledControllerHelper() {
  70319. }
  70320. /**
  70321. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70322. * @param vrGamepad the gamepad to initialized
  70323. * @returns a vr controller of the type the gamepad identified as
  70324. */
  70325. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70326. // Oculus Touch
  70327. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70328. return new BABYLON.OculusTouchController(vrGamepad);
  70329. }
  70330. // Windows Mixed Reality controllers
  70331. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70332. return new BABYLON.WindowsMotionController(vrGamepad);
  70333. }
  70334. // HTC Vive
  70335. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70336. return new BABYLON.ViveController(vrGamepad);
  70337. }
  70338. // Samsung/Oculus Gear VR
  70339. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70340. return new BABYLON.GearVRController(vrGamepad);
  70341. }
  70342. // Google Daydream
  70343. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70344. return new BABYLON.DaydreamController(vrGamepad);
  70345. }
  70346. // Generic
  70347. else {
  70348. return new BABYLON.GenericController(vrGamepad);
  70349. }
  70350. };
  70351. return PoseEnabledControllerHelper;
  70352. }());
  70353. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70354. /**
  70355. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70356. */
  70357. var PoseEnabledController = /** @class */ (function (_super) {
  70358. __extends(PoseEnabledController, _super);
  70359. /**
  70360. * Creates a new PoseEnabledController from a gamepad
  70361. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70362. */
  70363. function PoseEnabledController(browserGamepad) {
  70364. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70365. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70366. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70367. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70368. /**
  70369. * The device position in babylon space
  70370. */
  70371. _this.devicePosition = BABYLON.Vector3.Zero();
  70372. /**
  70373. * The device rotation in babylon space
  70374. */
  70375. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70376. /**
  70377. * The scale factor of the device in babylon space
  70378. */
  70379. _this.deviceScaleFactor = 1;
  70380. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70381. /**
  70382. * Internal, matrix used to convert room space to babylon space
  70383. */
  70384. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70385. /**
  70386. * Node to be used when casting a ray from the controller
  70387. */
  70388. _this._pointingPoseNode = null;
  70389. _this._workingMatrix = BABYLON.Matrix.Identity();
  70390. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70391. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70392. _this.position = BABYLON.Vector3.Zero();
  70393. _this.rotationQuaternion = new BABYLON.Quaternion();
  70394. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70395. _this._calculatedRotation = new BABYLON.Quaternion();
  70396. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70397. return _this;
  70398. }
  70399. /**
  70400. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70401. */
  70402. PoseEnabledController.prototype.update = function () {
  70403. _super.prototype.update.call(this);
  70404. var pose = this.browserGamepad.pose;
  70405. this.updateFromDevice(pose);
  70406. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70407. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70408. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70409. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70410. if (this._mesh) {
  70411. this._mesh.position.copyFrom(this.devicePosition);
  70412. if (this._mesh.rotationQuaternion) {
  70413. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70414. }
  70415. }
  70416. };
  70417. /**
  70418. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70419. * @param poseData raw pose fromthe device
  70420. */
  70421. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70422. if (poseData) {
  70423. this.rawPose = poseData;
  70424. if (poseData.position) {
  70425. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70426. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70427. this._deviceRoomPosition.z *= -1;
  70428. }
  70429. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70430. this._calculatedPosition.addInPlace(this.position);
  70431. }
  70432. var pose = this.rawPose;
  70433. if (poseData.orientation && pose.orientation) {
  70434. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70435. if (this._mesh) {
  70436. if (this._mesh.getScene().useRightHandedSystem) {
  70437. this._deviceRoomRotationQuaternion.z *= -1;
  70438. this._deviceRoomRotationQuaternion.w *= -1;
  70439. }
  70440. else {
  70441. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70442. }
  70443. }
  70444. // if the camera is set, rotate to the camera's rotation
  70445. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70446. }
  70447. }
  70448. };
  70449. /**
  70450. * Attaches a mesh to the controller
  70451. * @param mesh the mesh to be attached
  70452. */
  70453. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70454. if (this._mesh) {
  70455. this._mesh.parent = null;
  70456. }
  70457. this._mesh = mesh;
  70458. if (this._poseControlledCamera) {
  70459. this._mesh.parent = this._poseControlledCamera;
  70460. }
  70461. if (!this._mesh.rotationQuaternion) {
  70462. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70463. }
  70464. };
  70465. /**
  70466. * Attaches the controllers mesh to a camera
  70467. * @param camera the camera the mesh should be attached to
  70468. */
  70469. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70470. this._poseControlledCamera = camera;
  70471. if (this._mesh) {
  70472. this._mesh.parent = this._poseControlledCamera;
  70473. }
  70474. };
  70475. /**
  70476. * Disposes of the controller
  70477. */
  70478. PoseEnabledController.prototype.dispose = function () {
  70479. if (this._mesh) {
  70480. this._mesh.dispose();
  70481. }
  70482. this._mesh = null;
  70483. _super.prototype.dispose.call(this);
  70484. };
  70485. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70486. /**
  70487. * The mesh that is attached to the controller
  70488. */
  70489. get: function () {
  70490. return this._mesh;
  70491. },
  70492. enumerable: true,
  70493. configurable: true
  70494. });
  70495. /**
  70496. * Gets the ray of the controller in the direction the controller is pointing
  70497. * @param length the length the resulting ray should be
  70498. * @returns a ray in the direction the controller is pointing
  70499. */
  70500. PoseEnabledController.prototype.getForwardRay = function (length) {
  70501. if (length === void 0) { length = 100; }
  70502. if (!this.mesh) {
  70503. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70504. }
  70505. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70506. var origin = m.getTranslation();
  70507. var forward = new BABYLON.Vector3(0, 0, -1);
  70508. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70509. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70510. return new BABYLON.Ray(origin, direction, length);
  70511. };
  70512. /**
  70513. * Name of the child mesh that can be used to cast a ray from the controller
  70514. */
  70515. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70516. return PoseEnabledController;
  70517. }(BABYLON.Gamepad));
  70518. BABYLON.PoseEnabledController = PoseEnabledController;
  70519. })(BABYLON || (BABYLON = {}));
  70520. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70521. var BABYLON;
  70522. (function (BABYLON) {
  70523. /**
  70524. * Defines the WebVRController object that represents controllers tracked in 3D space
  70525. */
  70526. var WebVRController = /** @class */ (function (_super) {
  70527. __extends(WebVRController, _super);
  70528. /**
  70529. * Creates a new WebVRController from a gamepad
  70530. * @param vrGamepad the gamepad that the WebVRController should be created from
  70531. */
  70532. function WebVRController(vrGamepad) {
  70533. var _this = _super.call(this, vrGamepad) || this;
  70534. // Observables
  70535. /**
  70536. * Fired when the trigger state has changed
  70537. */
  70538. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70539. /**
  70540. * Fired when the main button state has changed
  70541. */
  70542. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70543. /**
  70544. * Fired when the secondary button state has changed
  70545. */
  70546. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70547. /**
  70548. * Fired when the pad state has changed
  70549. */
  70550. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70551. /**
  70552. * Fired when controllers stick values have changed
  70553. */
  70554. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70555. /**
  70556. * X and Y axis corrisponding to the controllers joystick
  70557. */
  70558. _this.pad = { x: 0, y: 0 };
  70559. // avoid GC, store state in a tmp object
  70560. _this._changes = {
  70561. pressChanged: false,
  70562. touchChanged: false,
  70563. valueChanged: false,
  70564. changed: false
  70565. };
  70566. _this._buttons = new Array(vrGamepad.buttons.length);
  70567. _this.hand = vrGamepad.hand;
  70568. return _this;
  70569. }
  70570. /**
  70571. * Fired when a controller button's state has changed
  70572. * @param callback the callback containing the button that was modified
  70573. */
  70574. WebVRController.prototype.onButtonStateChange = function (callback) {
  70575. this._onButtonStateChange = callback;
  70576. };
  70577. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70578. /**
  70579. * The default controller model for the controller
  70580. */
  70581. get: function () {
  70582. return this._defaultModel;
  70583. },
  70584. enumerable: true,
  70585. configurable: true
  70586. });
  70587. /**
  70588. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70589. */
  70590. WebVRController.prototype.update = function () {
  70591. _super.prototype.update.call(this);
  70592. for (var index = 0; index < this._buttons.length; index++) {
  70593. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70594. }
  70595. ;
  70596. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70597. this.pad.x = this.leftStick.x;
  70598. this.pad.y = this.leftStick.y;
  70599. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70600. }
  70601. };
  70602. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70603. if (!newState) {
  70604. newState = {
  70605. pressed: false,
  70606. touched: false,
  70607. value: 0
  70608. };
  70609. }
  70610. if (!currentState) {
  70611. this._buttons[buttonIndex] = {
  70612. pressed: newState.pressed,
  70613. touched: newState.touched,
  70614. value: newState.value
  70615. };
  70616. return;
  70617. }
  70618. this._checkChanges(newState, currentState);
  70619. if (this._changes.changed) {
  70620. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70621. this._handleButtonChange(buttonIndex, newState, this._changes);
  70622. }
  70623. this._buttons[buttonIndex].pressed = newState.pressed;
  70624. this._buttons[buttonIndex].touched = newState.touched;
  70625. // oculus triggers are never 0, thou not touched.
  70626. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70627. };
  70628. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70629. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70630. this._changes.touchChanged = newState.touched !== currentState.touched;
  70631. this._changes.valueChanged = newState.value !== currentState.value;
  70632. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70633. return this._changes;
  70634. };
  70635. /**
  70636. * Disposes of th webVRCOntroller
  70637. */
  70638. WebVRController.prototype.dispose = function () {
  70639. _super.prototype.dispose.call(this);
  70640. this.onTriggerStateChangedObservable.clear();
  70641. this.onMainButtonStateChangedObservable.clear();
  70642. this.onSecondaryButtonStateChangedObservable.clear();
  70643. this.onPadStateChangedObservable.clear();
  70644. this.onPadValuesChangedObservable.clear();
  70645. };
  70646. return WebVRController;
  70647. }(BABYLON.PoseEnabledController));
  70648. BABYLON.WebVRController = WebVRController;
  70649. })(BABYLON || (BABYLON = {}));
  70650. //# sourceMappingURL=babylon.webVRController.js.map
  70651. var BABYLON;
  70652. (function (BABYLON) {
  70653. /**
  70654. * Oculus Touch Controller
  70655. */
  70656. var OculusTouchController = /** @class */ (function (_super) {
  70657. __extends(OculusTouchController, _super);
  70658. /**
  70659. * Creates a new OculusTouchController from a gamepad
  70660. * @param vrGamepad the gamepad that the controller should be created from
  70661. */
  70662. function OculusTouchController(vrGamepad) {
  70663. var _this = _super.call(this, vrGamepad) || this;
  70664. /**
  70665. * Fired when the secondary trigger on this controller is modified
  70666. */
  70667. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70668. /**
  70669. * Fired when the thumb rest on this controller is modified
  70670. */
  70671. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70672. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70673. return _this;
  70674. }
  70675. /**
  70676. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70677. * @param scene scene in which to add meshes
  70678. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70679. */
  70680. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70681. var _this = this;
  70682. var meshName;
  70683. // Hand
  70684. if (this.hand === 'left') {
  70685. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70686. }
  70687. else { // Right is the default if no hand is specified
  70688. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70689. }
  70690. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70691. /*
  70692. Parent Mesh name: oculus_touch_left
  70693. - body
  70694. - trigger
  70695. - thumbstick
  70696. - grip
  70697. - button_y
  70698. - button_x
  70699. - button_enter
  70700. */
  70701. _this._defaultModel = newMeshes[1];
  70702. _this.attachToMesh(_this._defaultModel);
  70703. if (meshLoaded) {
  70704. meshLoaded(_this._defaultModel);
  70705. }
  70706. });
  70707. };
  70708. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70709. /**
  70710. * Fired when the A button on this controller is modified
  70711. */
  70712. get: function () {
  70713. if (this.hand === 'right') {
  70714. return this.onMainButtonStateChangedObservable;
  70715. }
  70716. else {
  70717. throw new Error('No A button on left hand');
  70718. }
  70719. },
  70720. enumerable: true,
  70721. configurable: true
  70722. });
  70723. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70724. /**
  70725. * Fired when the B button on this controller is modified
  70726. */
  70727. get: function () {
  70728. if (this.hand === 'right') {
  70729. return this.onSecondaryButtonStateChangedObservable;
  70730. }
  70731. else {
  70732. throw new Error('No B button on left hand');
  70733. }
  70734. },
  70735. enumerable: true,
  70736. configurable: true
  70737. });
  70738. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70739. /**
  70740. * Fired when the X button on this controller is modified
  70741. */
  70742. get: function () {
  70743. if (this.hand === 'left') {
  70744. return this.onMainButtonStateChangedObservable;
  70745. }
  70746. else {
  70747. throw new Error('No X button on right hand');
  70748. }
  70749. },
  70750. enumerable: true,
  70751. configurable: true
  70752. });
  70753. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70754. /**
  70755. * Fired when the Y button on this controller is modified
  70756. */
  70757. get: function () {
  70758. if (this.hand === 'left') {
  70759. return this.onSecondaryButtonStateChangedObservable;
  70760. }
  70761. else {
  70762. throw new Error('No Y button on right hand');
  70763. }
  70764. },
  70765. enumerable: true,
  70766. configurable: true
  70767. });
  70768. /**
  70769. * Called once for each button that changed state since the last frame
  70770. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70771. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70772. * 2) secondary trigger (same)
  70773. * 3) A (right) X (left), touch, pressed = value
  70774. * 4) B / Y
  70775. * 5) thumb rest
  70776. * @param buttonIdx Which button index changed
  70777. * @param state New state of the button
  70778. * @param changes Which properties on the state changed since last frame
  70779. */
  70780. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70781. var notifyObject = state; //{ state: state, changes: changes };
  70782. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70783. switch (buttonIdx) {
  70784. case 0:
  70785. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70786. return;
  70787. case 1: // index trigger
  70788. if (this._defaultModel) {
  70789. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70790. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70791. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70792. }
  70793. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70794. return;
  70795. case 2: // secondary trigger
  70796. if (this._defaultModel) {
  70797. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  70798. }
  70799. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  70800. return;
  70801. case 3:
  70802. if (this._defaultModel) {
  70803. if (notifyObject.pressed) {
  70804. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  70805. }
  70806. else {
  70807. (this._defaultModel.getChildren()[1]).position.y = 0;
  70808. }
  70809. }
  70810. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70811. return;
  70812. case 4:
  70813. if (this._defaultModel) {
  70814. if (notifyObject.pressed) {
  70815. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70816. }
  70817. else {
  70818. (this._defaultModel.getChildren()[2]).position.y = 0;
  70819. }
  70820. }
  70821. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70822. return;
  70823. case 5:
  70824. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  70825. return;
  70826. }
  70827. };
  70828. /**
  70829. * Base Url for the controller model.
  70830. */
  70831. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  70832. /**
  70833. * File name for the left controller model.
  70834. */
  70835. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  70836. /**
  70837. * File name for the right controller model.
  70838. */
  70839. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  70840. return OculusTouchController;
  70841. }(BABYLON.WebVRController));
  70842. BABYLON.OculusTouchController = OculusTouchController;
  70843. })(BABYLON || (BABYLON = {}));
  70844. //# sourceMappingURL=babylon.oculusTouchController.js.map
  70845. var BABYLON;
  70846. (function (BABYLON) {
  70847. /**
  70848. * Vive Controller
  70849. */
  70850. var ViveController = /** @class */ (function (_super) {
  70851. __extends(ViveController, _super);
  70852. /**
  70853. * Creates a new ViveController from a gamepad
  70854. * @param vrGamepad the gamepad that the controller should be created from
  70855. */
  70856. function ViveController(vrGamepad) {
  70857. var _this = _super.call(this, vrGamepad) || this;
  70858. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  70859. _this._invertLeftStickY = true;
  70860. return _this;
  70861. }
  70862. /**
  70863. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70864. * @param scene scene in which to add meshes
  70865. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70866. */
  70867. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70868. var _this = this;
  70869. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  70870. /*
  70871. Parent Mesh name: ViveWand
  70872. - body
  70873. - r_gripper
  70874. - l_gripper
  70875. - menu_button
  70876. - system_button
  70877. - trackpad
  70878. - trigger
  70879. - LED
  70880. */
  70881. _this._defaultModel = newMeshes[1];
  70882. _this.attachToMesh(_this._defaultModel);
  70883. if (meshLoaded) {
  70884. meshLoaded(_this._defaultModel);
  70885. }
  70886. });
  70887. };
  70888. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  70889. /**
  70890. * Fired when the left button on this controller is modified
  70891. */
  70892. get: function () {
  70893. return this.onMainButtonStateChangedObservable;
  70894. },
  70895. enumerable: true,
  70896. configurable: true
  70897. });
  70898. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  70899. /**
  70900. * Fired when the right button on this controller is modified
  70901. */
  70902. get: function () {
  70903. return this.onMainButtonStateChangedObservable;
  70904. },
  70905. enumerable: true,
  70906. configurable: true
  70907. });
  70908. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  70909. /**
  70910. * Fired when the menu button on this controller is modified
  70911. */
  70912. get: function () {
  70913. return this.onSecondaryButtonStateChangedObservable;
  70914. },
  70915. enumerable: true,
  70916. configurable: true
  70917. });
  70918. /**
  70919. * Called once for each button that changed state since the last frame
  70920. * Vive mapping:
  70921. * 0: touchpad
  70922. * 1: trigger
  70923. * 2: left AND right buttons
  70924. * 3: menu button
  70925. * @param buttonIdx Which button index changed
  70926. * @param state New state of the button
  70927. * @param changes Which properties on the state changed since last frame
  70928. */
  70929. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70930. var notifyObject = state; //{ state: state, changes: changes };
  70931. switch (buttonIdx) {
  70932. case 0:
  70933. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70934. return;
  70935. case 1: // index trigger
  70936. if (this._defaultModel) {
  70937. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  70938. }
  70939. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70940. return;
  70941. case 2: // left AND right button
  70942. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70943. return;
  70944. case 3:
  70945. if (this._defaultModel) {
  70946. if (notifyObject.pressed) {
  70947. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70948. }
  70949. else {
  70950. (this._defaultModel.getChildren()[2]).position.y = 0;
  70951. }
  70952. }
  70953. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70954. return;
  70955. }
  70956. };
  70957. /**
  70958. * Base Url for the controller model.
  70959. */
  70960. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  70961. /**
  70962. * File name for the controller model.
  70963. */
  70964. ViveController.MODEL_FILENAME = 'wand.babylon';
  70965. return ViveController;
  70966. }(BABYLON.WebVRController));
  70967. BABYLON.ViveController = ViveController;
  70968. })(BABYLON || (BABYLON = {}));
  70969. //# sourceMappingURL=babylon.viveController.js.map
  70970. var BABYLON;
  70971. (function (BABYLON) {
  70972. /**
  70973. * Generic Controller
  70974. */
  70975. var GenericController = /** @class */ (function (_super) {
  70976. __extends(GenericController, _super);
  70977. /**
  70978. * Creates a new GenericController from a gamepad
  70979. * @param vrGamepad the gamepad that the controller should be created from
  70980. */
  70981. function GenericController(vrGamepad) {
  70982. return _super.call(this, vrGamepad) || this;
  70983. }
  70984. /**
  70985. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70986. * @param scene scene in which to add meshes
  70987. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70988. */
  70989. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70990. var _this = this;
  70991. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  70992. _this._defaultModel = newMeshes[1];
  70993. _this.attachToMesh(_this._defaultModel);
  70994. if (meshLoaded) {
  70995. meshLoaded(_this._defaultModel);
  70996. }
  70997. });
  70998. };
  70999. /**
  71000. * Called once for each button that changed state since the last frame
  71001. * @param buttonIdx Which button index changed
  71002. * @param state New state of the button
  71003. * @param changes Which properties on the state changed since last frame
  71004. */
  71005. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71006. console.log("Button id: " + buttonIdx + "state: ");
  71007. console.dir(state);
  71008. };
  71009. /**
  71010. * Base Url for the controller model.
  71011. */
  71012. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71013. /**
  71014. * File name for the controller model.
  71015. */
  71016. GenericController.MODEL_FILENAME = 'generic.babylon';
  71017. return GenericController;
  71018. }(BABYLON.WebVRController));
  71019. BABYLON.GenericController = GenericController;
  71020. })(BABYLON || (BABYLON = {}));
  71021. //# sourceMappingURL=babylon.genericController.js.map
  71022. var BABYLON;
  71023. (function (BABYLON) {
  71024. /**
  71025. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71026. */
  71027. var LoadedMeshInfo = /** @class */ (function () {
  71028. function LoadedMeshInfo() {
  71029. /**
  71030. * Map of the button meshes contained in the controller
  71031. */
  71032. this.buttonMeshes = {};
  71033. /**
  71034. * Map of the axis meshes contained in the controller
  71035. */
  71036. this.axisMeshes = {};
  71037. }
  71038. return LoadedMeshInfo;
  71039. }());
  71040. /**
  71041. * Defines the WindowsMotionController object that the state of the windows motion controller
  71042. */
  71043. var WindowsMotionController = /** @class */ (function (_super) {
  71044. __extends(WindowsMotionController, _super);
  71045. /**
  71046. * Creates a new WindowsMotionController from a gamepad
  71047. * @param vrGamepad the gamepad that the controller should be created from
  71048. */
  71049. function WindowsMotionController(vrGamepad) {
  71050. var _this = _super.call(this, vrGamepad) || this;
  71051. _this._mapping = {
  71052. // Semantic button names
  71053. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71054. // A mapping of the button name to glTF model node name
  71055. // that should be transformed by button value.
  71056. buttonMeshNames: {
  71057. 'trigger': 'SELECT',
  71058. 'menu': 'MENU',
  71059. 'grip': 'GRASP',
  71060. 'thumbstick': 'THUMBSTICK_PRESS',
  71061. 'trackpad': 'TOUCHPAD_PRESS'
  71062. },
  71063. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71064. buttonObservableNames: {
  71065. 'trigger': 'onTriggerStateChangedObservable',
  71066. 'menu': 'onSecondaryButtonStateChangedObservable',
  71067. 'grip': 'onMainButtonStateChangedObservable',
  71068. 'thumbstick': 'onPadStateChangedObservable',
  71069. 'trackpad': 'onTrackpadChangedObservable'
  71070. },
  71071. // A mapping of the axis name to glTF model node name
  71072. // that should be transformed by axis value.
  71073. // This array mirrors the browserGamepad.axes array, such that
  71074. // the mesh corresponding to axis 0 is in this array index 0.
  71075. axisMeshNames: [
  71076. 'THUMBSTICK_X',
  71077. 'THUMBSTICK_Y',
  71078. 'TOUCHPAD_TOUCH_X',
  71079. 'TOUCHPAD_TOUCH_Y'
  71080. ],
  71081. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71082. };
  71083. /**
  71084. * Fired when the trackpad on this controller is clicked
  71085. */
  71086. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71087. /**
  71088. * Fired when the trackpad on this controller is modified
  71089. */
  71090. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71091. /**
  71092. * The current x and y values of this controller's trackpad
  71093. */
  71094. _this.trackpad = { x: 0, y: 0 };
  71095. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71096. _this._loadedMeshInfo = null;
  71097. return _this;
  71098. }
  71099. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71100. /**
  71101. * Fired when the trigger on this controller is modified
  71102. */
  71103. get: function () {
  71104. return this.onTriggerStateChangedObservable;
  71105. },
  71106. enumerable: true,
  71107. configurable: true
  71108. });
  71109. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71110. /**
  71111. * Fired when the menu button on this controller is modified
  71112. */
  71113. get: function () {
  71114. return this.onSecondaryButtonStateChangedObservable;
  71115. },
  71116. enumerable: true,
  71117. configurable: true
  71118. });
  71119. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71120. /**
  71121. * Fired when the grip button on this controller is modified
  71122. */
  71123. get: function () {
  71124. return this.onMainButtonStateChangedObservable;
  71125. },
  71126. enumerable: true,
  71127. configurable: true
  71128. });
  71129. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71130. /**
  71131. * Fired when the thumbstick button on this controller is modified
  71132. */
  71133. get: function () {
  71134. return this.onPadStateChangedObservable;
  71135. },
  71136. enumerable: true,
  71137. configurable: true
  71138. });
  71139. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71140. /**
  71141. * Fired when the touchpad button on this controller is modified
  71142. */
  71143. get: function () {
  71144. return this.onTrackpadChangedObservable;
  71145. },
  71146. enumerable: true,
  71147. configurable: true
  71148. });
  71149. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71150. /**
  71151. * Fired when the touchpad values on this controller are modified
  71152. */
  71153. get: function () {
  71154. return this.onTrackpadValuesChangedObservable;
  71155. },
  71156. enumerable: true,
  71157. configurable: true
  71158. });
  71159. /**
  71160. * Called once per frame by the engine.
  71161. */
  71162. WindowsMotionController.prototype.update = function () {
  71163. _super.prototype.update.call(this);
  71164. if (this.browserGamepad.axes) {
  71165. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71166. this.trackpad.x = this.browserGamepad["axes"][2];
  71167. this.trackpad.y = this.browserGamepad["axes"][3];
  71168. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71169. }
  71170. // Only need to animate axes if there is a loaded mesh
  71171. if (this._loadedMeshInfo) {
  71172. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71173. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71174. }
  71175. }
  71176. }
  71177. };
  71178. /**
  71179. * Called once for each button that changed state since the last frame
  71180. * @param buttonIdx Which button index changed
  71181. * @param state New state of the button
  71182. * @param changes Which properties on the state changed since last frame
  71183. */
  71184. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71185. var buttonName = this._mapping.buttons[buttonIdx];
  71186. if (!buttonName) {
  71187. return;
  71188. }
  71189. // Only emit events for buttons that we know how to map from index to name
  71190. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71191. if (observable) {
  71192. observable.notifyObservers(state);
  71193. }
  71194. this._lerpButtonTransform(buttonName, state.value);
  71195. };
  71196. /**
  71197. * Moves the buttons on the controller mesh based on their current state
  71198. * @param buttonName the name of the button to move
  71199. * @param buttonValue the value of the button which determines the buttons new position
  71200. */
  71201. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71202. // If there is no loaded mesh, there is nothing to transform.
  71203. if (!this._loadedMeshInfo) {
  71204. return;
  71205. }
  71206. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71207. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71208. return;
  71209. }
  71210. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71211. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71212. };
  71213. /**
  71214. * Moves the axis on the controller mesh based on its current state
  71215. * @param axis the index of the axis
  71216. * @param axisValue the value of the axis which determines the meshes new position
  71217. * @ignore
  71218. */
  71219. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71220. if (!this._loadedMeshInfo) {
  71221. return;
  71222. }
  71223. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71224. if (!meshInfo) {
  71225. return;
  71226. }
  71227. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71228. return;
  71229. }
  71230. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71231. var lerpValue = axisValue * 0.5 + 0.5;
  71232. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71233. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71234. };
  71235. /**
  71236. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71237. * @param scene scene in which to add meshes
  71238. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71239. */
  71240. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71241. var _this = this;
  71242. if (forceDefault === void 0) { forceDefault = false; }
  71243. var path;
  71244. var filename;
  71245. // Checking if GLB loader is present
  71246. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71247. // Determine the device specific folder based on the ID suffix
  71248. var device = 'default';
  71249. if (this.id && !forceDefault) {
  71250. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71251. device = ((match && match[0]) || device);
  71252. }
  71253. // Hand
  71254. if (this.hand === 'left') {
  71255. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71256. }
  71257. else { // Right is the default if no hand is specified
  71258. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71259. }
  71260. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71261. }
  71262. else {
  71263. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71264. path = BABYLON.GenericController.MODEL_BASE_URL;
  71265. filename = BABYLON.GenericController.MODEL_FILENAME;
  71266. }
  71267. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71268. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71269. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71270. if (!_this._loadedMeshInfo) {
  71271. return;
  71272. }
  71273. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71274. _this.attachToMesh(_this._defaultModel);
  71275. if (meshLoaded) {
  71276. meshLoaded(_this._defaultModel);
  71277. }
  71278. }, null, function (scene, message) {
  71279. BABYLON.Tools.Log(message);
  71280. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71281. if (!forceDefault) {
  71282. _this.initControllerMesh(scene, meshLoaded, true);
  71283. }
  71284. });
  71285. };
  71286. /**
  71287. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71288. * can be transformed by button presses and axes values, based on this._mapping.
  71289. *
  71290. * @param scene scene in which the meshes exist
  71291. * @param meshes list of meshes that make up the controller model to process
  71292. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71293. */
  71294. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71295. var loadedMeshInfo = null;
  71296. // Create a new mesh to contain the glTF hierarchy
  71297. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71298. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71299. var childMesh = null;
  71300. for (var i = 0; i < meshes.length; i++) {
  71301. var mesh = meshes[i];
  71302. if (!mesh.parent) {
  71303. // Exclude controller meshes from picking results
  71304. mesh.isPickable = false;
  71305. // Handle root node, attach to the new parentMesh
  71306. childMesh = mesh;
  71307. break;
  71308. }
  71309. }
  71310. if (childMesh) {
  71311. childMesh.setParent(parentMesh);
  71312. // Create our mesh info. Note that this method will always return non-null.
  71313. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71314. }
  71315. else {
  71316. BABYLON.Tools.Warn('Could not find root node in model file.');
  71317. }
  71318. return loadedMeshInfo;
  71319. };
  71320. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71321. var loadedMeshInfo = new LoadedMeshInfo();
  71322. var i;
  71323. loadedMeshInfo.rootNode = rootNode;
  71324. // Reset the caches
  71325. loadedMeshInfo.buttonMeshes = {};
  71326. loadedMeshInfo.axisMeshes = {};
  71327. // Button Meshes
  71328. for (i = 0; i < this._mapping.buttons.length; i++) {
  71329. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71330. if (!buttonMeshName) {
  71331. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71332. continue;
  71333. }
  71334. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71335. if (!buttonMesh) {
  71336. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71337. continue;
  71338. }
  71339. var buttonMeshInfo = {
  71340. index: i,
  71341. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71342. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71343. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71344. };
  71345. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71346. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71347. }
  71348. else {
  71349. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71350. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71351. '(VALUE: ' + !!buttonMeshInfo.value +
  71352. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71353. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71354. ')');
  71355. }
  71356. }
  71357. // Axis Meshes
  71358. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71359. var axisMeshName = this._mapping.axisMeshNames[i];
  71360. if (!axisMeshName) {
  71361. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71362. continue;
  71363. }
  71364. var axisMesh = getChildByName(rootNode, axisMeshName);
  71365. if (!axisMesh) {
  71366. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71367. continue;
  71368. }
  71369. var axisMeshInfo = {
  71370. index: i,
  71371. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71372. min: getImmediateChildByName(axisMesh, 'MIN'),
  71373. max: getImmediateChildByName(axisMesh, 'MAX')
  71374. };
  71375. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71376. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71377. }
  71378. else {
  71379. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71380. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71381. '(VALUE: ' + !!axisMeshInfo.value +
  71382. ', MIN: ' + !!axisMeshInfo.min +
  71383. ', MAX:' + !!axisMeshInfo.max +
  71384. ')');
  71385. }
  71386. }
  71387. // Pointing Ray
  71388. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71389. if (!loadedMeshInfo.pointingPoseNode) {
  71390. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71391. }
  71392. return loadedMeshInfo;
  71393. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71394. function getChildByName(node, name) {
  71395. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71396. }
  71397. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71398. function getImmediateChildByName(node, name) {
  71399. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71400. }
  71401. };
  71402. /**
  71403. * Gets the ray of the controller in the direction the controller is pointing
  71404. * @param length the length the resulting ray should be
  71405. * @returns a ray in the direction the controller is pointing
  71406. */
  71407. WindowsMotionController.prototype.getForwardRay = function (length) {
  71408. if (length === void 0) { length = 100; }
  71409. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71410. return _super.prototype.getForwardRay.call(this, length);
  71411. }
  71412. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71413. var origin = m.getTranslation();
  71414. var forward = new BABYLON.Vector3(0, 0, -1);
  71415. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71416. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71417. return new BABYLON.Ray(origin, direction, length);
  71418. };
  71419. /**
  71420. * Disposes of the controller
  71421. */
  71422. WindowsMotionController.prototype.dispose = function () {
  71423. _super.prototype.dispose.call(this);
  71424. this.onTrackpadChangedObservable.clear();
  71425. };
  71426. /**
  71427. * The base url used to load the left and right controller models
  71428. */
  71429. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71430. /**
  71431. * The name of the left controller model file
  71432. */
  71433. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71434. /**
  71435. * The name of the right controller model file
  71436. */
  71437. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71438. /**
  71439. * The controller name prefix for this controller type
  71440. */
  71441. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71442. /**
  71443. * The controller id pattern for this controller type
  71444. */
  71445. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71446. return WindowsMotionController;
  71447. }(BABYLON.WebVRController));
  71448. BABYLON.WindowsMotionController = WindowsMotionController;
  71449. })(BABYLON || (BABYLON = {}));
  71450. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71451. var BABYLON;
  71452. (function (BABYLON) {
  71453. /**
  71454. * Gear VR Controller
  71455. */
  71456. var GearVRController = /** @class */ (function (_super) {
  71457. __extends(GearVRController, _super);
  71458. /**
  71459. * Creates a new GearVRController from a gamepad
  71460. * @param vrGamepad the gamepad that the controller should be created from
  71461. */
  71462. function GearVRController(vrGamepad) {
  71463. var _this = _super.call(this, vrGamepad) || this;
  71464. _this._buttonIndexToObservableNameMap = [
  71465. 'onTrackpadChangedObservable',
  71466. 'onTriggerStateChangedObservable' // Trigger
  71467. ];
  71468. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71469. return _this;
  71470. }
  71471. /**
  71472. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71473. * @param scene scene in which to add meshes
  71474. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71475. */
  71476. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71477. var _this = this;
  71478. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71479. _this._defaultModel = newMeshes[1];
  71480. _this.attachToMesh(_this._defaultModel);
  71481. if (meshLoaded) {
  71482. meshLoaded(_this._defaultModel);
  71483. }
  71484. });
  71485. };
  71486. /**
  71487. * Called once for each button that changed state since the last frame
  71488. * @param buttonIdx Which button index changed
  71489. * @param state New state of the button
  71490. * @param changes Which properties on the state changed since last frame
  71491. */
  71492. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71493. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71494. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71495. // Only emit events for buttons that we know how to map from index to observable
  71496. var observable = this[observableName];
  71497. if (observable) {
  71498. observable.notifyObservers(state);
  71499. }
  71500. }
  71501. };
  71502. /**
  71503. * Base Url for the controller model.
  71504. */
  71505. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71506. /**
  71507. * File name for the controller model.
  71508. */
  71509. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71510. /**
  71511. * Gamepad Id prefix used to identify this controller.
  71512. */
  71513. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71514. return GearVRController;
  71515. }(BABYLON.WebVRController));
  71516. BABYLON.GearVRController = GearVRController;
  71517. })(BABYLON || (BABYLON = {}));
  71518. //# sourceMappingURL=babylon.gearVRController.js.map
  71519. var BABYLON;
  71520. (function (BABYLON) {
  71521. /**
  71522. * Google Daydream controller
  71523. */
  71524. var DaydreamController = /** @class */ (function (_super) {
  71525. __extends(DaydreamController, _super);
  71526. /**
  71527. * Creates a new DaydreamController from a gamepad
  71528. * @param vrGamepad the gamepad that the controller should be created from
  71529. */
  71530. function DaydreamController(vrGamepad) {
  71531. var _this = _super.call(this, vrGamepad) || this;
  71532. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71533. return _this;
  71534. }
  71535. /**
  71536. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71537. * @param scene scene in which to add meshes
  71538. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71539. */
  71540. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71541. var _this = this;
  71542. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71543. _this._defaultModel = newMeshes[1];
  71544. _this.attachToMesh(_this._defaultModel);
  71545. if (meshLoaded) {
  71546. meshLoaded(_this._defaultModel);
  71547. }
  71548. });
  71549. };
  71550. /**
  71551. * Called once for each button that changed state since the last frame
  71552. * @param buttonIdx Which button index changed
  71553. * @param state New state of the button
  71554. * @param changes Which properties on the state changed since last frame
  71555. */
  71556. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71557. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71558. if (buttonIdx === 0) {
  71559. var observable = this.onTriggerStateChangedObservable;
  71560. if (observable) {
  71561. observable.notifyObservers(state);
  71562. }
  71563. }
  71564. else {
  71565. // If the app or home buttons are ever made available
  71566. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71567. }
  71568. };
  71569. /**
  71570. * Base Url for the controller model.
  71571. */
  71572. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71573. /**
  71574. * File name for the controller model.
  71575. */
  71576. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71577. /**
  71578. * Gamepad Id prefix used to identify Daydream Controller.
  71579. */
  71580. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71581. return DaydreamController;
  71582. }(BABYLON.WebVRController));
  71583. BABYLON.DaydreamController = DaydreamController;
  71584. })(BABYLON || (BABYLON = {}));
  71585. //# sourceMappingURL=babylon.daydreamController.js.map
  71586. var BABYLON;
  71587. (function (BABYLON) {
  71588. var FollowCamera = /** @class */ (function (_super) {
  71589. __extends(FollowCamera, _super);
  71590. function FollowCamera(name, position, scene, lockedTarget) {
  71591. if (lockedTarget === void 0) { lockedTarget = null; }
  71592. var _this = _super.call(this, name, position, scene) || this;
  71593. _this.radius = 12;
  71594. _this.rotationOffset = 0;
  71595. _this.heightOffset = 4;
  71596. _this.cameraAcceleration = 0.05;
  71597. _this.maxCameraSpeed = 20;
  71598. _this.lockedTarget = lockedTarget;
  71599. return _this;
  71600. }
  71601. FollowCamera.prototype.getRadians = function (degrees) {
  71602. return degrees * Math.PI / 180;
  71603. };
  71604. FollowCamera.prototype.follow = function (cameraTarget) {
  71605. if (!cameraTarget)
  71606. return;
  71607. var yRotation;
  71608. if (cameraTarget.rotationQuaternion) {
  71609. var rotMatrix = new BABYLON.Matrix();
  71610. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71611. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71612. }
  71613. else {
  71614. yRotation = cameraTarget.rotation.y;
  71615. }
  71616. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71617. var targetPosition = cameraTarget.getAbsolutePosition();
  71618. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71619. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71620. var dx = targetX - this.position.x;
  71621. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71622. var dz = (targetZ) - this.position.z;
  71623. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71624. var vy = dy * this.cameraAcceleration;
  71625. var vz = dz * this.cameraAcceleration * 2;
  71626. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71627. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71628. }
  71629. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71630. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71631. }
  71632. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71633. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71634. }
  71635. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71636. this.setTarget(targetPosition);
  71637. };
  71638. FollowCamera.prototype._checkInputs = function () {
  71639. _super.prototype._checkInputs.call(this);
  71640. if (this.lockedTarget) {
  71641. this.follow(this.lockedTarget);
  71642. }
  71643. };
  71644. FollowCamera.prototype.getClassName = function () {
  71645. return "FollowCamera";
  71646. };
  71647. __decorate([
  71648. BABYLON.serialize()
  71649. ], FollowCamera.prototype, "radius", void 0);
  71650. __decorate([
  71651. BABYLON.serialize()
  71652. ], FollowCamera.prototype, "rotationOffset", void 0);
  71653. __decorate([
  71654. BABYLON.serialize()
  71655. ], FollowCamera.prototype, "heightOffset", void 0);
  71656. __decorate([
  71657. BABYLON.serialize()
  71658. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71659. __decorate([
  71660. BABYLON.serialize()
  71661. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71662. __decorate([
  71663. BABYLON.serializeAsMeshReference("lockedTargetId")
  71664. ], FollowCamera.prototype, "lockedTarget", void 0);
  71665. return FollowCamera;
  71666. }(BABYLON.TargetCamera));
  71667. BABYLON.FollowCamera = FollowCamera;
  71668. var ArcFollowCamera = /** @class */ (function (_super) {
  71669. __extends(ArcFollowCamera, _super);
  71670. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71671. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71672. _this.alpha = alpha;
  71673. _this.beta = beta;
  71674. _this.radius = radius;
  71675. _this.target = target;
  71676. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71677. _this.follow();
  71678. return _this;
  71679. }
  71680. ArcFollowCamera.prototype.follow = function () {
  71681. if (!this.target) {
  71682. return;
  71683. }
  71684. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71685. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71686. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71687. var targetPosition = this.target.getAbsolutePosition();
  71688. this.position = targetPosition.add(this._cartesianCoordinates);
  71689. this.setTarget(targetPosition);
  71690. };
  71691. ArcFollowCamera.prototype._checkInputs = function () {
  71692. _super.prototype._checkInputs.call(this);
  71693. this.follow();
  71694. };
  71695. ArcFollowCamera.prototype.getClassName = function () {
  71696. return "ArcFollowCamera";
  71697. };
  71698. return ArcFollowCamera;
  71699. }(BABYLON.TargetCamera));
  71700. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71701. })(BABYLON || (BABYLON = {}));
  71702. //# sourceMappingURL=babylon.followCamera.js.map
  71703. var BABYLON;
  71704. (function (BABYLON) {
  71705. // We're mainly based on the logic defined into the FreeCamera code
  71706. var UniversalCamera = /** @class */ (function (_super) {
  71707. __extends(UniversalCamera, _super);
  71708. //-- end properties for backward compatibility for inputs
  71709. function UniversalCamera(name, position, scene) {
  71710. var _this = _super.call(this, name, position, scene) || this;
  71711. _this.inputs.addGamepad();
  71712. return _this;
  71713. }
  71714. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71715. //-- Begin properties for backward compatibility for inputs
  71716. get: function () {
  71717. var gamepad = this.inputs.attached["gamepad"];
  71718. if (gamepad)
  71719. return gamepad.gamepadAngularSensibility;
  71720. return 0;
  71721. },
  71722. set: function (value) {
  71723. var gamepad = this.inputs.attached["gamepad"];
  71724. if (gamepad)
  71725. gamepad.gamepadAngularSensibility = value;
  71726. },
  71727. enumerable: true,
  71728. configurable: true
  71729. });
  71730. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71731. get: function () {
  71732. var gamepad = this.inputs.attached["gamepad"];
  71733. if (gamepad)
  71734. return gamepad.gamepadMoveSensibility;
  71735. return 0;
  71736. },
  71737. set: function (value) {
  71738. var gamepad = this.inputs.attached["gamepad"];
  71739. if (gamepad)
  71740. gamepad.gamepadMoveSensibility = value;
  71741. },
  71742. enumerable: true,
  71743. configurable: true
  71744. });
  71745. UniversalCamera.prototype.getClassName = function () {
  71746. return "UniversalCamera";
  71747. };
  71748. return UniversalCamera;
  71749. }(BABYLON.TouchCamera));
  71750. BABYLON.UniversalCamera = UniversalCamera;
  71751. })(BABYLON || (BABYLON = {}));
  71752. //# sourceMappingURL=babylon.universalCamera.js.map
  71753. var BABYLON;
  71754. (function (BABYLON) {
  71755. // We're mainly based on the logic defined into the FreeCamera code
  71756. var GamepadCamera = /** @class */ (function (_super) {
  71757. __extends(GamepadCamera, _super);
  71758. //-- end properties for backward compatibility for inputs
  71759. function GamepadCamera(name, position, scene) {
  71760. return _super.call(this, name, position, scene) || this;
  71761. }
  71762. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71763. //-- Begin properties for backward compatibility for inputs
  71764. get: function () {
  71765. var gamepad = this.inputs.attached["gamepad"];
  71766. if (gamepad)
  71767. return gamepad.gamepadAngularSensibility;
  71768. return 0;
  71769. },
  71770. set: function (value) {
  71771. var gamepad = this.inputs.attached["gamepad"];
  71772. if (gamepad)
  71773. gamepad.gamepadAngularSensibility = value;
  71774. },
  71775. enumerable: true,
  71776. configurable: true
  71777. });
  71778. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71779. get: function () {
  71780. var gamepad = this.inputs.attached["gamepad"];
  71781. if (gamepad)
  71782. return gamepad.gamepadMoveSensibility;
  71783. return 0;
  71784. },
  71785. set: function (value) {
  71786. var gamepad = this.inputs.attached["gamepad"];
  71787. if (gamepad)
  71788. gamepad.gamepadMoveSensibility = value;
  71789. },
  71790. enumerable: true,
  71791. configurable: true
  71792. });
  71793. GamepadCamera.prototype.getClassName = function () {
  71794. return "GamepadCamera";
  71795. };
  71796. return GamepadCamera;
  71797. }(BABYLON.UniversalCamera));
  71798. BABYLON.GamepadCamera = GamepadCamera;
  71799. })(BABYLON || (BABYLON = {}));
  71800. //# sourceMappingURL=babylon.gamepadCamera.js.map
  71801. var BABYLON;
  71802. (function (BABYLON) {
  71803. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71804. function PostProcessRenderPipelineManager() {
  71805. this._renderPipelines = {};
  71806. }
  71807. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71808. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71809. };
  71810. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71811. if (unique === void 0) { unique = false; }
  71812. var renderPipeline = this._renderPipelines[renderPipelineName];
  71813. if (!renderPipeline) {
  71814. return;
  71815. }
  71816. renderPipeline._attachCameras(cameras, unique);
  71817. };
  71818. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  71819. var renderPipeline = this._renderPipelines[renderPipelineName];
  71820. if (!renderPipeline) {
  71821. return;
  71822. }
  71823. renderPipeline._detachCameras(cameras);
  71824. };
  71825. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71826. var renderPipeline = this._renderPipelines[renderPipelineName];
  71827. if (!renderPipeline) {
  71828. return;
  71829. }
  71830. renderPipeline._enableEffect(renderEffectName, cameras);
  71831. };
  71832. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71833. var renderPipeline = this._renderPipelines[renderPipelineName];
  71834. if (!renderPipeline) {
  71835. return;
  71836. }
  71837. renderPipeline._disableEffect(renderEffectName, cameras);
  71838. };
  71839. PostProcessRenderPipelineManager.prototype.update = function () {
  71840. for (var renderPipelineName in this._renderPipelines) {
  71841. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71842. var pipeline = this._renderPipelines[renderPipelineName];
  71843. if (!pipeline.isSupported) {
  71844. pipeline.dispose();
  71845. delete this._renderPipelines[renderPipelineName];
  71846. }
  71847. else {
  71848. pipeline._update();
  71849. }
  71850. }
  71851. }
  71852. };
  71853. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  71854. for (var renderPipelineName in this._renderPipelines) {
  71855. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71856. var pipeline = this._renderPipelines[renderPipelineName];
  71857. pipeline._rebuild();
  71858. }
  71859. }
  71860. };
  71861. PostProcessRenderPipelineManager.prototype.dispose = function () {
  71862. for (var renderPipelineName in this._renderPipelines) {
  71863. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71864. var pipeline = this._renderPipelines[renderPipelineName];
  71865. pipeline.dispose();
  71866. }
  71867. }
  71868. };
  71869. return PostProcessRenderPipelineManager;
  71870. }());
  71871. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  71872. })(BABYLON || (BABYLON = {}));
  71873. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  71874. var BABYLON;
  71875. (function (BABYLON) {
  71876. /**
  71877. * This represents a set of one or more post processes in Babylon.
  71878. * A post process can be used to apply a shader to a texture after it is rendered.
  71879. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  71880. */
  71881. var PostProcessRenderEffect = /** @class */ (function () {
  71882. /**
  71883. * Instantiates a post process render effect.
  71884. * A post process can be used to apply a shader to a texture after it is rendered.
  71885. * @param engine The engine the effect is tied to
  71886. * @param name The name of the effect
  71887. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  71888. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  71889. */
  71890. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  71891. this._name = name;
  71892. this._singleInstance = singleInstance || true;
  71893. this._getPostProcesses = getPostProcesses;
  71894. this._cameras = {};
  71895. this._indicesForCamera = {};
  71896. this._postProcesses = {};
  71897. }
  71898. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  71899. /**
  71900. * Checks if all the post processes in the effect are supported.
  71901. */
  71902. get: function () {
  71903. for (var index in this._postProcesses) {
  71904. if (this._postProcesses.hasOwnProperty(index)) {
  71905. var pps = this._postProcesses[index];
  71906. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  71907. if (!pps[ppIndex].isSupported) {
  71908. return false;
  71909. }
  71910. }
  71911. }
  71912. }
  71913. return true;
  71914. },
  71915. enumerable: true,
  71916. configurable: true
  71917. });
  71918. /**
  71919. * Updates the current state of the effect
  71920. */
  71921. PostProcessRenderEffect.prototype._update = function () {
  71922. };
  71923. /**
  71924. * Attaches the effect on cameras
  71925. * @param cameras The camera to attach to.
  71926. */
  71927. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  71928. var _this = this;
  71929. var cameraKey;
  71930. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71931. if (!cams) {
  71932. return;
  71933. }
  71934. for (var i = 0; i < cams.length; i++) {
  71935. var camera = cams[i];
  71936. var cameraName = camera.name;
  71937. if (this._singleInstance) {
  71938. cameraKey = 0;
  71939. }
  71940. else {
  71941. cameraKey = cameraName;
  71942. }
  71943. if (!this._postProcesses[cameraKey]) {
  71944. var postProcess = this._getPostProcesses();
  71945. if (postProcess) {
  71946. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  71947. }
  71948. }
  71949. if (!this._indicesForCamera[cameraName]) {
  71950. this._indicesForCamera[cameraName] = [];
  71951. }
  71952. this._postProcesses[cameraKey].forEach(function (postProcess) {
  71953. var index = camera.attachPostProcess(postProcess);
  71954. _this._indicesForCamera[cameraName].push(index);
  71955. });
  71956. if (!this._cameras[cameraName]) {
  71957. this._cameras[cameraName] = camera;
  71958. }
  71959. }
  71960. };
  71961. /**
  71962. * Detatches the effect on cameras
  71963. * @param cameras The camera to detatch from.
  71964. */
  71965. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  71966. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71967. if (!cams) {
  71968. return;
  71969. }
  71970. for (var i = 0; i < cams.length; i++) {
  71971. var camera = cams[i];
  71972. var cameraName = camera.name;
  71973. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71974. camera.detachPostProcess(postProcess);
  71975. });
  71976. if (this._cameras[cameraName]) {
  71977. //this._indicesForCamera.splice(index, 1);
  71978. this._cameras[cameraName] = null;
  71979. }
  71980. }
  71981. };
  71982. /**
  71983. * Enables the effect on given cameras
  71984. * @param cameras The camera to enable.
  71985. */
  71986. PostProcessRenderEffect.prototype._enable = function (cameras) {
  71987. var _this = this;
  71988. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71989. if (!cams) {
  71990. return;
  71991. }
  71992. for (var i = 0; i < cams.length; i++) {
  71993. var camera = cams[i];
  71994. var cameraName = camera.name;
  71995. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  71996. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  71997. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71998. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  71999. });
  72000. }
  72001. }
  72002. }
  72003. };
  72004. /**
  72005. * Disables the effect on the given cameras
  72006. * @param cameras The camera to disable.
  72007. */
  72008. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72009. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72010. if (!cams) {
  72011. return;
  72012. }
  72013. for (var i = 0; i < cams.length; i++) {
  72014. var camera = cams[i];
  72015. var cameraName = camera.name;
  72016. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72017. camera.detachPostProcess(postProcess);
  72018. });
  72019. }
  72020. };
  72021. /**
  72022. * Gets a list of the post processes contained in the effect.
  72023. * @param camera The camera to get the post processes on.
  72024. * @returns The list of the post processes in the effect.
  72025. */
  72026. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72027. if (this._singleInstance) {
  72028. return this._postProcesses[0];
  72029. }
  72030. else {
  72031. if (!camera) {
  72032. return null;
  72033. }
  72034. return this._postProcesses[camera.name];
  72035. }
  72036. };
  72037. return PostProcessRenderEffect;
  72038. }());
  72039. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72040. })(BABYLON || (BABYLON = {}));
  72041. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72042. var BABYLON;
  72043. (function (BABYLON) {
  72044. var PostProcessRenderPipeline = /** @class */ (function () {
  72045. function PostProcessRenderPipeline(engine, name) {
  72046. this.engine = engine;
  72047. this._name = name;
  72048. this._renderEffects = {};
  72049. this._renderEffectsForIsolatedPass = new Array();
  72050. this._cameras = [];
  72051. }
  72052. PostProcessRenderPipeline.prototype.getClassName = function () {
  72053. return "PostProcessRenderPipeline";
  72054. };
  72055. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72056. get: function () {
  72057. for (var renderEffectName in this._renderEffects) {
  72058. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72059. if (!this._renderEffects[renderEffectName].isSupported) {
  72060. return false;
  72061. }
  72062. }
  72063. }
  72064. return true;
  72065. },
  72066. enumerable: true,
  72067. configurable: true
  72068. });
  72069. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72070. this._renderEffects[renderEffect._name] = renderEffect;
  72071. };
  72072. // private
  72073. PostProcessRenderPipeline.prototype._rebuild = function () {
  72074. };
  72075. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72076. var renderEffects = this._renderEffects[renderEffectName];
  72077. if (!renderEffects) {
  72078. return;
  72079. }
  72080. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72081. };
  72082. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72083. var renderEffects = this._renderEffects[renderEffectName];
  72084. if (!renderEffects) {
  72085. return;
  72086. }
  72087. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72088. };
  72089. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72090. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72091. if (!cams) {
  72092. return;
  72093. }
  72094. var indicesToDelete = [];
  72095. var i;
  72096. for (i = 0; i < cams.length; i++) {
  72097. var camera = cams[i];
  72098. var cameraName = camera.name;
  72099. if (this._cameras.indexOf(camera) === -1) {
  72100. this._cameras[cameraName] = camera;
  72101. }
  72102. else if (unique) {
  72103. indicesToDelete.push(i);
  72104. }
  72105. }
  72106. for (i = 0; i < indicesToDelete.length; i++) {
  72107. cameras.splice(indicesToDelete[i], 1);
  72108. }
  72109. for (var renderEffectName in this._renderEffects) {
  72110. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72111. this._renderEffects[renderEffectName]._attachCameras(cams);
  72112. }
  72113. }
  72114. };
  72115. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72116. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72117. if (!cams) {
  72118. return;
  72119. }
  72120. for (var renderEffectName in this._renderEffects) {
  72121. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72122. this._renderEffects[renderEffectName]._detachCameras(cams);
  72123. }
  72124. }
  72125. for (var i = 0; i < cams.length; i++) {
  72126. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72127. }
  72128. };
  72129. PostProcessRenderPipeline.prototype._update = function () {
  72130. for (var renderEffectName in this._renderEffects) {
  72131. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72132. this._renderEffects[renderEffectName]._update();
  72133. }
  72134. }
  72135. for (var i = 0; i < this._cameras.length; i++) {
  72136. var cameraName = this._cameras[i].name;
  72137. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72138. this._renderEffectsForIsolatedPass[cameraName]._update();
  72139. }
  72140. }
  72141. };
  72142. PostProcessRenderPipeline.prototype._reset = function () {
  72143. this._renderEffects = {};
  72144. this._renderEffectsForIsolatedPass = new Array();
  72145. };
  72146. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72147. // 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)
  72148. var effectKeys = Object.keys(this._renderEffects);
  72149. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72150. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72151. if (postProcesses) {
  72152. postProcesses[0].samples = sampleCount;
  72153. return true;
  72154. }
  72155. }
  72156. return false;
  72157. };
  72158. PostProcessRenderPipeline.prototype.dispose = function () {
  72159. // Must be implemented by children
  72160. };
  72161. __decorate([
  72162. BABYLON.serialize()
  72163. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72164. return PostProcessRenderPipeline;
  72165. }());
  72166. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72167. })(BABYLON || (BABYLON = {}));
  72168. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72169. var BABYLON;
  72170. (function (BABYLON) {
  72171. /**
  72172. * This represents a depth renderer in Babylon.
  72173. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72174. */
  72175. var DepthRenderer = /** @class */ (function () {
  72176. /**
  72177. * Instantiates a depth renderer
  72178. * @param scene The scene the renderer belongs to
  72179. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72180. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72181. */
  72182. function DepthRenderer(scene, type, camera) {
  72183. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72184. if (camera === void 0) { camera = null; }
  72185. var _this = this;
  72186. this._scene = scene;
  72187. this._camera = camera;
  72188. var engine = scene.getEngine();
  72189. // Render target
  72190. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72191. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72192. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72193. this._depthMap.refreshRate = 1;
  72194. this._depthMap.renderParticles = false;
  72195. this._depthMap.renderList = null;
  72196. // Camera to get depth map from to support multiple concurrent cameras
  72197. this._depthMap.activeCamera = this._camera;
  72198. this._depthMap.ignoreCameraViewport = true;
  72199. this._depthMap.useCameraPostProcesses = false;
  72200. // set default depth value to 1.0 (far away)
  72201. this._depthMap.onClearObservable.add(function (engine) {
  72202. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72203. });
  72204. // Custom render function
  72205. var renderSubMesh = function (subMesh) {
  72206. var mesh = subMesh.getRenderingMesh();
  72207. var scene = _this._scene;
  72208. var engine = scene.getEngine();
  72209. var material = subMesh.getMaterial();
  72210. if (!material) {
  72211. return;
  72212. }
  72213. // Culling and reverse (right handed system)
  72214. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72215. // Managing instances
  72216. var batch = mesh._getInstancesRenderList(subMesh._id);
  72217. if (batch.mustReturn) {
  72218. return;
  72219. }
  72220. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72221. var camera = _this._camera || scene.activeCamera;
  72222. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72223. engine.enableEffect(_this._effect);
  72224. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72225. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72226. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72227. // Alpha test
  72228. if (material && material.needAlphaTesting()) {
  72229. var alphaTexture = material.getAlphaTestTexture();
  72230. if (alphaTexture) {
  72231. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72232. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72233. }
  72234. }
  72235. // Bones
  72236. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72237. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72238. }
  72239. // Draw
  72240. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72241. }
  72242. };
  72243. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72244. var index;
  72245. if (depthOnlySubMeshes.length) {
  72246. engine.setColorWrite(false);
  72247. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72248. renderSubMesh(depthOnlySubMeshes.data[index]);
  72249. }
  72250. engine.setColorWrite(true);
  72251. }
  72252. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72253. renderSubMesh(opaqueSubMeshes.data[index]);
  72254. }
  72255. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72256. renderSubMesh(alphaTestSubMeshes.data[index]);
  72257. }
  72258. };
  72259. }
  72260. /**
  72261. * Creates the depth rendering effect and checks if the effect is ready.
  72262. * @param subMesh The submesh to be used to render the depth map of
  72263. * @param useInstances If multiple world instances should be used
  72264. * @returns if the depth renderer is ready to render the depth map
  72265. */
  72266. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72267. var material = subMesh.getMaterial();
  72268. if (material.disableDepthWrite) {
  72269. return false;
  72270. }
  72271. var defines = [];
  72272. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72273. var mesh = subMesh.getMesh();
  72274. // Alpha test
  72275. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72276. defines.push("#define ALPHATEST");
  72277. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72278. attribs.push(BABYLON.VertexBuffer.UVKind);
  72279. defines.push("#define UV1");
  72280. }
  72281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72282. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72283. defines.push("#define UV2");
  72284. }
  72285. }
  72286. // Bones
  72287. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72290. if (mesh.numBoneInfluencers > 4) {
  72291. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72292. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72293. }
  72294. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72295. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72296. }
  72297. else {
  72298. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72299. }
  72300. // Instances
  72301. if (useInstances) {
  72302. defines.push("#define INSTANCES");
  72303. attribs.push("world0");
  72304. attribs.push("world1");
  72305. attribs.push("world2");
  72306. attribs.push("world3");
  72307. }
  72308. // Get correct effect
  72309. var join = defines.join("\n");
  72310. if (this._cachedDefines !== join) {
  72311. this._cachedDefines = join;
  72312. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72313. }
  72314. return this._effect.isReady();
  72315. };
  72316. /**
  72317. * Gets the texture which the depth map will be written to.
  72318. * @returns The depth map texture
  72319. */
  72320. DepthRenderer.prototype.getDepthMap = function () {
  72321. return this._depthMap;
  72322. };
  72323. /**
  72324. * Disposes of the depth renderer.
  72325. */
  72326. DepthRenderer.prototype.dispose = function () {
  72327. this._depthMap.dispose();
  72328. };
  72329. return DepthRenderer;
  72330. }());
  72331. BABYLON.DepthRenderer = DepthRenderer;
  72332. })(BABYLON || (BABYLON = {}));
  72333. //# sourceMappingURL=babylon.depthRenderer.js.map
  72334. var BABYLON;
  72335. (function (BABYLON) {
  72336. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72337. __extends(SSAORenderingPipeline, _super);
  72338. /**
  72339. * @constructor
  72340. * @param {string} name - The rendering pipeline name
  72341. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72342. * @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 }
  72343. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72344. */
  72345. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72346. var _this = _super.call(this, scene.getEngine(), name) || this;
  72347. // Members
  72348. /**
  72349. * The PassPostProcess id in the pipeline that contains the original scene color
  72350. */
  72351. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72352. /**
  72353. * The SSAO PostProcess id in the pipeline
  72354. */
  72355. _this.SSAORenderEffect = "SSAORenderEffect";
  72356. /**
  72357. * The horizontal blur PostProcess id in the pipeline
  72358. */
  72359. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72360. /**
  72361. * The vertical blur PostProcess id in the pipeline
  72362. */
  72363. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72364. /**
  72365. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72366. */
  72367. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72368. /**
  72369. * The output strength of the SSAO post-process. Default value is 1.0.
  72370. */
  72371. _this.totalStrength = 1.0;
  72372. /**
  72373. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72374. */
  72375. _this.radius = 0.0001;
  72376. /**
  72377. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72378. * Must not be equal to fallOff and superior to fallOff.
  72379. * Default value is 0.975
  72380. */
  72381. _this.area = 0.0075;
  72382. /**
  72383. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72384. * Must not be equal to area and inferior to area.
  72385. * Default value is 0.0
  72386. */
  72387. _this.fallOff = 0.000001;
  72388. /**
  72389. * The base color of the SSAO post-process
  72390. * The final result is "base + ssao" between [0, 1]
  72391. */
  72392. _this.base = 0.5;
  72393. _this._firstUpdate = true;
  72394. _this._scene = scene;
  72395. // Set up assets
  72396. _this._createRandomTexture();
  72397. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72398. var ssaoRatio = ratio.ssaoRatio || ratio;
  72399. var combineRatio = ratio.combineRatio || ratio;
  72400. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72401. _this._createSSAOPostProcess(ssaoRatio);
  72402. _this._createBlurPostProcess(ssaoRatio);
  72403. _this._createSSAOCombinePostProcess(combineRatio);
  72404. // Set up pipeline
  72405. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72406. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72407. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72408. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72409. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72410. // Finish
  72411. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72412. if (cameras)
  72413. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72414. return _this;
  72415. }
  72416. // Public Methods
  72417. /**
  72418. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72419. */
  72420. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72421. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72422. for (var i = 0; i < this._scene.cameras.length; i++) {
  72423. var camera = this._scene.cameras[i];
  72424. this._originalColorPostProcess.dispose(camera);
  72425. this._ssaoPostProcess.dispose(camera);
  72426. this._blurHPostProcess.dispose(camera);
  72427. this._blurVPostProcess.dispose(camera);
  72428. this._ssaoCombinePostProcess.dispose(camera);
  72429. }
  72430. this._randomTexture.dispose();
  72431. if (disableDepthRender)
  72432. this._scene.disableDepthRenderer();
  72433. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72434. _super.prototype.dispose.call(this);
  72435. };
  72436. // Private Methods
  72437. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72438. var _this = this;
  72439. var size = 16;
  72440. 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);
  72441. 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);
  72442. this._blurHPostProcess.onActivateObservable.add(function () {
  72443. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72444. _this._blurHPostProcess.kernel = size * dw;
  72445. });
  72446. this._blurVPostProcess.onActivateObservable.add(function () {
  72447. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72448. _this._blurVPostProcess.kernel = size * dw;
  72449. });
  72450. };
  72451. SSAORenderingPipeline.prototype._rebuild = function () {
  72452. this._firstUpdate = true;
  72453. _super.prototype._rebuild.call(this);
  72454. };
  72455. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72456. var _this = this;
  72457. var numSamples = 16;
  72458. var sampleSphere = [
  72459. 0.5381, 0.1856, -0.4319,
  72460. 0.1379, 0.2486, 0.4430,
  72461. 0.3371, 0.5679, -0.0057,
  72462. -0.6999, -0.0451, -0.0019,
  72463. 0.0689, -0.1598, -0.8547,
  72464. 0.0560, 0.0069, -0.1843,
  72465. -0.0146, 0.1402, 0.0762,
  72466. 0.0100, -0.1924, -0.0344,
  72467. -0.3577, -0.5301, -0.4358,
  72468. -0.3169, 0.1063, 0.0158,
  72469. 0.0103, -0.5869, 0.0046,
  72470. -0.0897, -0.4940, 0.3287,
  72471. 0.7119, -0.0154, -0.0918,
  72472. -0.0533, 0.0596, -0.5411,
  72473. 0.0352, -0.0631, 0.5460,
  72474. -0.4776, 0.2847, -0.0271
  72475. ];
  72476. var samplesFactor = 1.0 / numSamples;
  72477. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72478. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72479. "area", "fallOff", "base", "range", "viewport"
  72480. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72481. this._ssaoPostProcess.onApply = function (effect) {
  72482. if (_this._firstUpdate) {
  72483. effect.setArray3("sampleSphere", sampleSphere);
  72484. effect.setFloat("samplesFactor", samplesFactor);
  72485. effect.setFloat("randTextureTiles", 4.0);
  72486. }
  72487. effect.setFloat("totalStrength", _this.totalStrength);
  72488. effect.setFloat("radius", _this.radius);
  72489. effect.setFloat("area", _this.area);
  72490. effect.setFloat("fallOff", _this.fallOff);
  72491. effect.setFloat("base", _this.base);
  72492. effect.setTexture("textureSampler", _this._depthTexture);
  72493. effect.setTexture("randomSampler", _this._randomTexture);
  72494. };
  72495. };
  72496. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72497. var _this = this;
  72498. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72499. this._ssaoCombinePostProcess.onApply = function (effect) {
  72500. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72501. };
  72502. };
  72503. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72504. var size = 512;
  72505. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72506. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72507. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72508. var context = this._randomTexture.getContext();
  72509. var rand = function (min, max) {
  72510. return Math.random() * (max - min) + min;
  72511. };
  72512. var randVector = BABYLON.Vector3.Zero();
  72513. for (var x = 0; x < size; x++) {
  72514. for (var y = 0; y < size; y++) {
  72515. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72516. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72517. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72518. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72519. context.fillRect(x, y, 1, 1);
  72520. }
  72521. }
  72522. this._randomTexture.update(false);
  72523. };
  72524. __decorate([
  72525. BABYLON.serialize()
  72526. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72527. __decorate([
  72528. BABYLON.serialize()
  72529. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72530. __decorate([
  72531. BABYLON.serialize()
  72532. ], SSAORenderingPipeline.prototype, "area", void 0);
  72533. __decorate([
  72534. BABYLON.serialize()
  72535. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72536. __decorate([
  72537. BABYLON.serialize()
  72538. ], SSAORenderingPipeline.prototype, "base", void 0);
  72539. return SSAORenderingPipeline;
  72540. }(BABYLON.PostProcessRenderPipeline));
  72541. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72542. })(BABYLON || (BABYLON = {}));
  72543. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72544. var BABYLON;
  72545. (function (BABYLON) {
  72546. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72547. __extends(SSAO2RenderingPipeline, _super);
  72548. /**
  72549. * @constructor
  72550. * @param {string} name - The rendering pipeline name
  72551. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72552. * @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 }
  72553. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72554. */
  72555. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72556. var _this = _super.call(this, scene.getEngine(), name) || this;
  72557. // Members
  72558. /**
  72559. * The PassPostProcess id in the pipeline that contains the original scene color
  72560. */
  72561. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72562. /**
  72563. * The SSAO PostProcess id in the pipeline
  72564. */
  72565. _this.SSAORenderEffect = "SSAORenderEffect";
  72566. /**
  72567. * The horizontal blur PostProcess id in the pipeline
  72568. */
  72569. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72570. /**
  72571. * The vertical blur PostProcess id in the pipeline
  72572. */
  72573. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72574. /**
  72575. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72576. */
  72577. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72578. /**
  72579. * The output strength of the SSAO post-process. Default value is 1.0.
  72580. */
  72581. _this.totalStrength = 1.0;
  72582. /**
  72583. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72584. */
  72585. _this.maxZ = 100.0;
  72586. /**
  72587. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72588. */
  72589. _this.minZAspect = 0.2;
  72590. /**
  72591. * Number of samples used for the SSAO calculations. Default value is 8
  72592. */
  72593. _this._samples = 8;
  72594. /**
  72595. * Are we using bilateral blur ?
  72596. */
  72597. _this._expensiveBlur = true;
  72598. /**
  72599. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72600. */
  72601. _this.radius = 2.0;
  72602. /**
  72603. * The base color of the SSAO post-process
  72604. * The final result is "base + ssao" between [0, 1]
  72605. */
  72606. _this.base = 0.1;
  72607. _this._firstUpdate = true;
  72608. _this._scene = scene;
  72609. if (!_this.isSupported) {
  72610. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72611. return _this;
  72612. }
  72613. var ssaoRatio = ratio.ssaoRatio || ratio;
  72614. var blurRatio = ratio.blurRatio || ratio;
  72615. // Set up assets
  72616. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72617. _this._createRandomTexture();
  72618. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72619. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72620. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72621. _this._createSSAOPostProcess(1.0);
  72622. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72623. _this._createSSAOCombinePostProcess(blurRatio);
  72624. // Set up pipeline
  72625. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72626. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72627. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72628. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72629. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72630. // Finish
  72631. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72632. if (cameras)
  72633. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72634. return _this;
  72635. }
  72636. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72637. get: function () {
  72638. return this._samples;
  72639. },
  72640. set: function (n) {
  72641. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72642. this._samples = n;
  72643. this._sampleSphere = this._generateHemisphere();
  72644. this._firstUpdate = true;
  72645. },
  72646. enumerable: true,
  72647. configurable: true
  72648. });
  72649. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72650. get: function () {
  72651. return this._expensiveBlur;
  72652. },
  72653. set: function (b) {
  72654. 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"]);
  72655. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72656. this._expensiveBlur = b;
  72657. this._firstUpdate = true;
  72658. },
  72659. enumerable: true,
  72660. configurable: true
  72661. });
  72662. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72663. /**
  72664. * Support test.
  72665. */
  72666. get: function () {
  72667. var engine = BABYLON.Engine.LastCreatedEngine;
  72668. if (!engine) {
  72669. return false;
  72670. }
  72671. return engine.getCaps().drawBuffersExtension;
  72672. },
  72673. enumerable: true,
  72674. configurable: true
  72675. });
  72676. // Public Methods
  72677. /**
  72678. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72679. */
  72680. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72681. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72682. for (var i = 0; i < this._scene.cameras.length; i++) {
  72683. var camera = this._scene.cameras[i];
  72684. this._originalColorPostProcess.dispose(camera);
  72685. this._ssaoPostProcess.dispose(camera);
  72686. this._blurHPostProcess.dispose(camera);
  72687. this._blurVPostProcess.dispose(camera);
  72688. this._ssaoCombinePostProcess.dispose(camera);
  72689. }
  72690. this._randomTexture.dispose();
  72691. if (disableGeometryBufferRenderer)
  72692. this._scene.disableGeometryBufferRenderer();
  72693. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72694. _super.prototype.dispose.call(this);
  72695. };
  72696. // Private Methods
  72697. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72698. var _this = this;
  72699. this._samplerOffsets = [];
  72700. var expensive = this.expensiveBlur;
  72701. for (var i = -8; i < 8; i++) {
  72702. this._samplerOffsets.push(i * 2 + 0.5);
  72703. }
  72704. 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");
  72705. this._blurHPostProcess.onApply = function (effect) {
  72706. if (!_this._scene.activeCamera) {
  72707. return;
  72708. }
  72709. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72710. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72711. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72712. effect.setFloat("radius", _this.radius);
  72713. effect.setTexture("depthSampler", _this._depthTexture);
  72714. if (_this._firstUpdate) {
  72715. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72716. }
  72717. };
  72718. 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");
  72719. this._blurVPostProcess.onApply = function (effect) {
  72720. if (!_this._scene.activeCamera) {
  72721. return;
  72722. }
  72723. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72724. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72725. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72726. effect.setFloat("radius", _this.radius);
  72727. effect.setTexture("depthSampler", _this._depthTexture);
  72728. if (_this._firstUpdate) {
  72729. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72730. _this._firstUpdate = false;
  72731. }
  72732. };
  72733. };
  72734. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72735. this._firstUpdate = true;
  72736. _super.prototype._rebuild.call(this);
  72737. };
  72738. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72739. var numSamples = this.samples;
  72740. var result = [];
  72741. var vector, scale;
  72742. var rand = function (min, max) {
  72743. return Math.random() * (max - min) + min;
  72744. };
  72745. var i = 0;
  72746. while (i < numSamples) {
  72747. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72748. vector.normalize();
  72749. scale = i / numSamples;
  72750. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72751. vector.scaleInPlace(scale);
  72752. result.push(vector.x, vector.y, vector.z);
  72753. i++;
  72754. }
  72755. return result;
  72756. };
  72757. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72758. var _this = this;
  72759. var numSamples = this.samples;
  72760. this._sampleSphere = this._generateHemisphere();
  72761. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72762. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72763. "base", "range", "projection", "near", "far", "texelSize",
  72764. "xViewport", "yViewport", "maxZ", "minZAspect"
  72765. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72766. this._ssaoPostProcess.onApply = function (effect) {
  72767. if (_this._firstUpdate) {
  72768. effect.setArray3("sampleSphere", _this._sampleSphere);
  72769. effect.setFloat("randTextureTiles", 4.0);
  72770. }
  72771. if (!_this._scene.activeCamera) {
  72772. return;
  72773. }
  72774. effect.setFloat("samplesFactor", 1 / _this.samples);
  72775. effect.setFloat("totalStrength", _this.totalStrength);
  72776. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72777. effect.setFloat("radius", _this.radius);
  72778. effect.setFloat("maxZ", _this.maxZ);
  72779. effect.setFloat("minZAspect", _this.minZAspect);
  72780. effect.setFloat("base", _this.base);
  72781. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72782. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72783. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72784. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72785. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  72786. effect.setTexture("textureSampler", _this._depthTexture);
  72787. effect.setTexture("normalSampler", _this._normalTexture);
  72788. effect.setTexture("randomSampler", _this._randomTexture);
  72789. };
  72790. };
  72791. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72792. var _this = this;
  72793. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72794. this._ssaoCombinePostProcess.onApply = function (effect) {
  72795. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72796. };
  72797. };
  72798. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72799. var size = 512;
  72800. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72801. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72802. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72803. var context = this._randomTexture.getContext();
  72804. var rand = function (min, max) {
  72805. return Math.random() * (max - min) + min;
  72806. };
  72807. var randVector = BABYLON.Vector3.Zero();
  72808. for (var x = 0; x < size; x++) {
  72809. for (var y = 0; y < size; y++) {
  72810. randVector.x = rand(0.0, 1.0);
  72811. randVector.y = rand(0.0, 1.0);
  72812. randVector.z = 0.0;
  72813. randVector.normalize();
  72814. randVector.scaleInPlace(255);
  72815. randVector.x = Math.floor(randVector.x);
  72816. randVector.y = Math.floor(randVector.y);
  72817. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72818. context.fillRect(x, y, 1, 1);
  72819. }
  72820. }
  72821. this._randomTexture.update(false);
  72822. };
  72823. __decorate([
  72824. BABYLON.serialize()
  72825. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  72826. __decorate([
  72827. BABYLON.serialize()
  72828. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  72829. __decorate([
  72830. BABYLON.serialize()
  72831. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  72832. __decorate([
  72833. BABYLON.serialize("samples")
  72834. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  72835. __decorate([
  72836. BABYLON.serialize("expensiveBlur")
  72837. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  72838. __decorate([
  72839. BABYLON.serialize()
  72840. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  72841. __decorate([
  72842. BABYLON.serialize()
  72843. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  72844. return SSAO2RenderingPipeline;
  72845. }(BABYLON.PostProcessRenderPipeline));
  72846. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  72847. })(BABYLON || (BABYLON = {}));
  72848. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  72849. // BABYLON.JS Chromatic Aberration GLSL Shader
  72850. // Author: Olivier Guyot
  72851. // Separates very slightly R, G and B colors on the edges of the screen
  72852. // Inspired by Francois Tarlier & Martins Upitis
  72853. var BABYLON;
  72854. (function (BABYLON) {
  72855. var LensRenderingPipeline = /** @class */ (function (_super) {
  72856. __extends(LensRenderingPipeline, _super);
  72857. /**
  72858. * @constructor
  72859. *
  72860. * Effect parameters are as follow:
  72861. * {
  72862. * chromatic_aberration: number; // from 0 to x (1 for realism)
  72863. * edge_blur: number; // from 0 to x (1 for realism)
  72864. * distortion: number; // from 0 to x (1 for realism)
  72865. * grain_amount: number; // from 0 to 1
  72866. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  72867. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  72868. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  72869. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  72870. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  72871. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  72872. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  72873. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  72874. * }
  72875. * Note: if an effect parameter is unset, effect is disabled
  72876. *
  72877. * @param {string} name - The rendering pipeline name
  72878. * @param {object} parameters - An object containing all parameters (see above)
  72879. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72880. * @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)
  72881. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72882. */
  72883. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  72884. if (ratio === void 0) { ratio = 1.0; }
  72885. var _this = _super.call(this, scene.getEngine(), name) || this;
  72886. // Lens effects can be of the following:
  72887. // - chromatic aberration (slight shift of RGB colors)
  72888. // - blur on the edge of the lens
  72889. // - lens distortion
  72890. // - depth-of-field blur & highlights enhancing
  72891. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  72892. // - grain effect (noise or custom texture)
  72893. // Two additional texture samplers are needed:
  72894. // - depth map (for depth-of-field)
  72895. // - grain texture
  72896. /**
  72897. * The chromatic aberration PostProcess id in the pipeline
  72898. */
  72899. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  72900. /**
  72901. * The highlights enhancing PostProcess id in the pipeline
  72902. */
  72903. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  72904. /**
  72905. * The depth-of-field PostProcess id in the pipeline
  72906. */
  72907. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  72908. _this._scene = scene;
  72909. // Fetch texture samplers
  72910. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72911. if (parameters.grain_texture) {
  72912. _this._grainTexture = parameters.grain_texture;
  72913. }
  72914. else {
  72915. _this._createGrainTexture();
  72916. }
  72917. // save parameters
  72918. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  72919. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  72920. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  72921. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  72922. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  72923. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  72924. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  72925. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  72926. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  72927. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  72928. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  72929. // Create effects
  72930. _this._createChromaticAberrationPostProcess(ratio);
  72931. _this._createHighlightsPostProcess(ratio);
  72932. _this._createDepthOfFieldPostProcess(ratio / 4);
  72933. // Set up pipeline
  72934. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  72935. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  72936. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  72937. if (_this._highlightsGain === -1) {
  72938. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  72939. }
  72940. // Finish
  72941. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72942. if (cameras) {
  72943. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72944. }
  72945. return _this;
  72946. }
  72947. // public methods (self explanatory)
  72948. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  72949. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  72950. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  72951. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  72952. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  72953. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  72954. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  72955. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  72956. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  72957. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  72958. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  72959. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  72960. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  72961. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  72962. };
  72963. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  72964. this._highlightsPostProcess.updateEffect();
  72965. };
  72966. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  72967. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  72968. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  72969. this._highlightsGain = amount;
  72970. };
  72971. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  72972. if (this._highlightsGain === -1) {
  72973. this._highlightsGain = 1.0;
  72974. }
  72975. this._highlightsThreshold = amount;
  72976. };
  72977. LensRenderingPipeline.prototype.disableHighlights = function () {
  72978. this._highlightsGain = -1;
  72979. };
  72980. /**
  72981. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  72982. */
  72983. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72984. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72985. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72986. this._chromaticAberrationPostProcess = null;
  72987. this._highlightsPostProcess = null;
  72988. this._depthOfFieldPostProcess = null;
  72989. this._grainTexture.dispose();
  72990. if (disableDepthRender)
  72991. this._scene.disableDepthRenderer();
  72992. };
  72993. // colors shifting and distortion
  72994. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  72995. var _this = this;
  72996. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  72997. [], // samplers
  72998. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72999. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73000. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73001. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73002. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73003. effect.setFloat('radialIntensity', 1);
  73004. effect.setFloat2('direction', 17, 17);
  73005. effect.setFloat2('centerPosition', 0.5, 0.5);
  73006. };
  73007. };
  73008. // highlights enhancing
  73009. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73010. var _this = this;
  73011. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73012. [], // samplers
  73013. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73014. this._highlightsPostProcess.onApply = function (effect) {
  73015. effect.setFloat('gain', _this._highlightsGain);
  73016. effect.setFloat('threshold', _this._highlightsThreshold);
  73017. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73018. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73019. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73020. };
  73021. };
  73022. // colors shifting and distortion
  73023. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73024. var _this = this;
  73025. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73026. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73027. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73028. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73029. this._depthOfFieldPostProcess.onApply = function (effect) {
  73030. effect.setTexture("depthSampler", _this._depthTexture);
  73031. effect.setTexture("grainSampler", _this._grainTexture);
  73032. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73033. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73034. effect.setFloat('grain_amount', _this._grainAmount);
  73035. effect.setBool('blur_noise', _this._blurNoise);
  73036. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73037. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73038. effect.setFloat('distortion', _this._distortion);
  73039. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73040. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73041. effect.setFloat('aperture', _this._dofAperture);
  73042. effect.setFloat('darken', _this._dofDarken);
  73043. effect.setFloat('edge_blur', _this._edgeBlur);
  73044. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73045. if (_this._scene.activeCamera) {
  73046. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73047. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73048. }
  73049. };
  73050. };
  73051. // creates a black and white random noise texture, 512x512
  73052. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73053. var size = 512;
  73054. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73055. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73056. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73057. var context = this._grainTexture.getContext();
  73058. var rand = function (min, max) {
  73059. return Math.random() * (max - min) + min;
  73060. };
  73061. var value;
  73062. for (var x = 0; x < size; x++) {
  73063. for (var y = 0; y < size; y++) {
  73064. value = Math.floor(rand(0.42, 0.58) * 255);
  73065. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73066. context.fillRect(x, y, 1, 1);
  73067. }
  73068. }
  73069. this._grainTexture.update(false);
  73070. };
  73071. return LensRenderingPipeline;
  73072. }(BABYLON.PostProcessRenderPipeline));
  73073. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73074. })(BABYLON || (BABYLON = {}));
  73075. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73076. var BABYLON;
  73077. (function (BABYLON) {
  73078. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73079. __extends(StandardRenderingPipeline, _super);
  73080. /**
  73081. * @constructor
  73082. * @param {string} name - The rendering pipeline name
  73083. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73084. * @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)
  73085. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73086. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73087. */
  73088. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73089. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73090. var _this = _super.call(this, scene.getEngine(), name) || this;
  73091. _this.downSampleX4PostProcess = null;
  73092. _this.brightPassPostProcess = null;
  73093. _this.blurHPostProcesses = [];
  73094. _this.blurVPostProcesses = [];
  73095. _this.textureAdderPostProcess = null;
  73096. _this.volumetricLightPostProcess = null;
  73097. _this.volumetricLightSmoothXPostProcess = null;
  73098. _this.volumetricLightSmoothYPostProcess = null;
  73099. _this.volumetricLightMergePostProces = null;
  73100. _this.volumetricLightFinalPostProcess = null;
  73101. _this.luminancePostProcess = null;
  73102. _this.luminanceDownSamplePostProcesses = [];
  73103. _this.hdrPostProcess = null;
  73104. _this.textureAdderFinalPostProcess = null;
  73105. _this.lensFlareFinalPostProcess = null;
  73106. _this.hdrFinalPostProcess = null;
  73107. _this.lensFlarePostProcess = null;
  73108. _this.lensFlareComposePostProcess = null;
  73109. _this.motionBlurPostProcess = null;
  73110. _this.depthOfFieldPostProcess = null;
  73111. // Values
  73112. _this.brightThreshold = 1.0;
  73113. _this.blurWidth = 512.0;
  73114. _this.horizontalBlur = false;
  73115. _this.exposure = 1.0;
  73116. _this.lensTexture = null;
  73117. _this.volumetricLightCoefficient = 0.2;
  73118. _this.volumetricLightPower = 4.0;
  73119. _this.volumetricLightBlurScale = 64.0;
  73120. _this.sourceLight = null;
  73121. _this.hdrMinimumLuminance = 1.0;
  73122. _this.hdrDecreaseRate = 0.5;
  73123. _this.hdrIncreaseRate = 0.5;
  73124. _this.lensColorTexture = null;
  73125. _this.lensFlareStrength = 20.0;
  73126. _this.lensFlareGhostDispersal = 1.4;
  73127. _this.lensFlareHaloWidth = 0.7;
  73128. _this.lensFlareDistortionStrength = 16.0;
  73129. _this.lensStarTexture = null;
  73130. _this.lensFlareDirtTexture = null;
  73131. _this.depthOfFieldDistance = 10.0;
  73132. _this.depthOfFieldBlurWidth = 64.0;
  73133. _this.motionStrength = 1.0;
  73134. // IAnimatable
  73135. _this.animations = [];
  73136. _this._currentDepthOfFieldSource = null;
  73137. _this._hdrCurrentLuminance = 1.0;
  73138. // Getters and setters
  73139. _this._bloomEnabled = true;
  73140. _this._depthOfFieldEnabled = false;
  73141. _this._vlsEnabled = false;
  73142. _this._lensFlareEnabled = false;
  73143. _this._hdrEnabled = false;
  73144. _this._motionBlurEnabled = false;
  73145. _this._motionBlurSamples = 64.0;
  73146. _this._volumetricLightStepsCount = 50.0;
  73147. _this._cameras = cameras || [];
  73148. // Initialize
  73149. _this._scene = scene;
  73150. _this._basePostProcess = originalPostProcess;
  73151. _this._ratio = ratio;
  73152. // Misc
  73153. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73154. // Finish
  73155. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73156. _this._buildPipeline();
  73157. return _this;
  73158. }
  73159. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73160. get: function () {
  73161. return this._bloomEnabled;
  73162. },
  73163. set: function (enabled) {
  73164. if (this._bloomEnabled === enabled) {
  73165. return;
  73166. }
  73167. this._bloomEnabled = enabled;
  73168. this._buildPipeline();
  73169. },
  73170. enumerable: true,
  73171. configurable: true
  73172. });
  73173. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73174. get: function () {
  73175. return this._depthOfFieldEnabled;
  73176. },
  73177. set: function (enabled) {
  73178. if (this._depthOfFieldEnabled === enabled) {
  73179. return;
  73180. }
  73181. this._depthOfFieldEnabled = enabled;
  73182. this._buildPipeline();
  73183. },
  73184. enumerable: true,
  73185. configurable: true
  73186. });
  73187. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73188. get: function () {
  73189. return this._lensFlareEnabled;
  73190. },
  73191. set: function (enabled) {
  73192. if (this._lensFlareEnabled === enabled) {
  73193. return;
  73194. }
  73195. this._lensFlareEnabled = enabled;
  73196. this._buildPipeline();
  73197. },
  73198. enumerable: true,
  73199. configurable: true
  73200. });
  73201. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73202. get: function () {
  73203. return this._hdrEnabled;
  73204. },
  73205. set: function (enabled) {
  73206. if (this._hdrEnabled === enabled) {
  73207. return;
  73208. }
  73209. this._hdrEnabled = enabled;
  73210. this._buildPipeline();
  73211. },
  73212. enumerable: true,
  73213. configurable: true
  73214. });
  73215. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73216. get: function () {
  73217. return this._vlsEnabled;
  73218. },
  73219. set: function (enabled) {
  73220. if (this._vlsEnabled === enabled) {
  73221. return;
  73222. }
  73223. if (enabled) {
  73224. var geometry = this._scene.enableGeometryBufferRenderer();
  73225. if (!geometry) {
  73226. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73227. return;
  73228. }
  73229. }
  73230. this._vlsEnabled = enabled;
  73231. this._buildPipeline();
  73232. },
  73233. enumerable: true,
  73234. configurable: true
  73235. });
  73236. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73237. get: function () {
  73238. return this._motionBlurEnabled;
  73239. },
  73240. set: function (enabled) {
  73241. if (this._motionBlurEnabled === enabled) {
  73242. return;
  73243. }
  73244. this._motionBlurEnabled = enabled;
  73245. this._buildPipeline();
  73246. },
  73247. enumerable: true,
  73248. configurable: true
  73249. });
  73250. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73251. get: function () {
  73252. return this._volumetricLightStepsCount;
  73253. },
  73254. set: function (count) {
  73255. if (this.volumetricLightPostProcess) {
  73256. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73257. }
  73258. this._volumetricLightStepsCount = count;
  73259. },
  73260. enumerable: true,
  73261. configurable: true
  73262. });
  73263. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73264. get: function () {
  73265. return this._motionBlurSamples;
  73266. },
  73267. set: function (samples) {
  73268. if (this.motionBlurPostProcess) {
  73269. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73270. }
  73271. this._motionBlurSamples = samples;
  73272. },
  73273. enumerable: true,
  73274. configurable: true
  73275. });
  73276. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73277. var _this = this;
  73278. var ratio = this._ratio;
  73279. var scene = this._scene;
  73280. this._disposePostProcesses();
  73281. this._reset();
  73282. // Create pass post-process
  73283. if (!this._basePostProcess) {
  73284. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73285. this.originalPostProcess.onApply = function (effect) {
  73286. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73287. };
  73288. }
  73289. else {
  73290. this.originalPostProcess = this._basePostProcess;
  73291. }
  73292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73293. this._currentDepthOfFieldSource = this.originalPostProcess;
  73294. if (this._vlsEnabled) {
  73295. // Create volumetric light
  73296. this._createVolumetricLightPostProcess(scene, ratio);
  73297. // Create volumetric light final post-process
  73298. 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);
  73299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73300. }
  73301. if (this._bloomEnabled) {
  73302. // Create down sample X4 post-process
  73303. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73304. // Create bright pass post-process
  73305. this._createBrightPassPostProcess(scene, ratio / 2);
  73306. // Create gaussian blur post-processes (down sampling blurs)
  73307. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73308. // Create texture adder post-process
  73309. this._createTextureAdderPostProcess(scene, ratio);
  73310. // Create depth-of-field source post-process
  73311. 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);
  73312. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73313. }
  73314. if (this._lensFlareEnabled) {
  73315. // Create lens flare post-process
  73316. this._createLensFlarePostProcess(scene, ratio);
  73317. // Create depth-of-field source post-process post lens-flare and disable it now
  73318. 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);
  73319. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73320. }
  73321. if (this._hdrEnabled) {
  73322. // Create luminance
  73323. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73324. // Create HDR
  73325. this._createHdrPostProcess(scene, ratio);
  73326. // Create depth-of-field source post-process post hdr and disable it now
  73327. 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);
  73328. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73329. }
  73330. if (this._depthOfFieldEnabled) {
  73331. // Create gaussian blur used by depth-of-field
  73332. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73333. // Create depth-of-field post-process
  73334. this._createDepthOfFieldPostProcess(scene, ratio);
  73335. }
  73336. if (this._motionBlurEnabled) {
  73337. // Create motion blur post-process
  73338. this._createMotionBlurPostProcess(scene, ratio);
  73339. }
  73340. if (this._cameras !== null) {
  73341. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73342. }
  73343. };
  73344. // Down Sample X4 Post-Processs
  73345. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73346. var _this = this;
  73347. var downSampleX4Offsets = new Array(32);
  73348. 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);
  73349. this.downSampleX4PostProcess.onApply = function (effect) {
  73350. var id = 0;
  73351. var width = _this.downSampleX4PostProcess.width;
  73352. var height = _this.downSampleX4PostProcess.height;
  73353. for (var i = -2; i < 2; i++) {
  73354. for (var j = -2; j < 2; j++) {
  73355. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73356. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73357. id += 2;
  73358. }
  73359. }
  73360. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73361. };
  73362. // Add to pipeline
  73363. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73364. };
  73365. // Brightpass Post-Process
  73366. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73367. var _this = this;
  73368. var brightOffsets = new Array(8);
  73369. 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);
  73370. this.brightPassPostProcess.onApply = function (effect) {
  73371. var sU = (1.0 / _this.brightPassPostProcess.width);
  73372. var sV = (1.0 / _this.brightPassPostProcess.height);
  73373. brightOffsets[0] = -0.5 * sU;
  73374. brightOffsets[1] = 0.5 * sV;
  73375. brightOffsets[2] = 0.5 * sU;
  73376. brightOffsets[3] = 0.5 * sV;
  73377. brightOffsets[4] = -0.5 * sU;
  73378. brightOffsets[5] = -0.5 * sV;
  73379. brightOffsets[6] = 0.5 * sU;
  73380. brightOffsets[7] = -0.5 * sV;
  73381. effect.setArray2("dsOffsets", brightOffsets);
  73382. effect.setFloat("brightThreshold", _this.brightThreshold);
  73383. };
  73384. // Add to pipeline
  73385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73386. };
  73387. // Create blur H&V post-processes
  73388. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73389. var _this = this;
  73390. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73391. var engine = scene.getEngine();
  73392. 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);
  73393. 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);
  73394. blurX.onActivateObservable.add(function () {
  73395. var dw = blurX.width / engine.getRenderWidth();
  73396. blurX.kernel = _this[blurWidthKey] * dw;
  73397. });
  73398. blurY.onActivateObservable.add(function () {
  73399. var dw = blurY.height / engine.getRenderHeight();
  73400. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73401. });
  73402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73404. this.blurHPostProcesses.push(blurX);
  73405. this.blurVPostProcesses.push(blurY);
  73406. };
  73407. // Create texture adder post-process
  73408. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73409. var _this = this;
  73410. 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);
  73411. this.textureAdderPostProcess.onApply = function (effect) {
  73412. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73413. effect.setTexture("lensSampler", _this.lensTexture);
  73414. effect.setFloat("exposure", _this.exposure);
  73415. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73416. };
  73417. // Add to pipeline
  73418. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73419. };
  73420. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73421. var _this = this;
  73422. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73423. geometryRenderer.enablePosition = true;
  73424. var geometry = geometryRenderer.getGBuffer();
  73425. // Base post-process
  73426. 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));
  73427. var depthValues = BABYLON.Vector2.Zero();
  73428. this.volumetricLightPostProcess.onApply = function (effect) {
  73429. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73430. var generator = _this.sourceLight.getShadowGenerator();
  73431. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73432. effect.setTexture("positionSampler", geometry.textures[2]);
  73433. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73434. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73435. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73436. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73437. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73438. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73439. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73440. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73441. effect.setVector2("depthValues", depthValues);
  73442. }
  73443. };
  73444. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73445. // Smooth
  73446. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73447. // Merge
  73448. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73449. this.volumetricLightMergePostProces.onApply = function (effect) {
  73450. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  73451. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73452. };
  73453. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73454. };
  73455. // Create luminance
  73456. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73457. var _this = this;
  73458. // Create luminance
  73459. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73460. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73461. var offsets = [];
  73462. this.luminancePostProcess.onApply = function (effect) {
  73463. var sU = (1.0 / _this.luminancePostProcess.width);
  73464. var sV = (1.0 / _this.luminancePostProcess.height);
  73465. offsets[0] = -0.5 * sU;
  73466. offsets[1] = 0.5 * sV;
  73467. offsets[2] = 0.5 * sU;
  73468. offsets[3] = 0.5 * sV;
  73469. offsets[4] = -0.5 * sU;
  73470. offsets[5] = -0.5 * sV;
  73471. offsets[6] = 0.5 * sU;
  73472. offsets[7] = -0.5 * sV;
  73473. effect.setArray2("lumOffsets", offsets);
  73474. };
  73475. // Add to pipeline
  73476. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73477. // Create down sample luminance
  73478. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73479. var size = Math.pow(3, i);
  73480. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73481. if (i === 0) {
  73482. defines += "#define FINAL_DOWN_SAMPLER";
  73483. }
  73484. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73485. this.luminanceDownSamplePostProcesses.push(postProcess);
  73486. }
  73487. // Create callbacks and add effects
  73488. var lastLuminance = this.luminancePostProcess;
  73489. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73490. var downSampleOffsets = new Array(18);
  73491. pp.onApply = function (effect) {
  73492. if (!lastLuminance) {
  73493. return;
  73494. }
  73495. var id = 0;
  73496. for (var x = -1; x < 2; x++) {
  73497. for (var y = -1; y < 2; y++) {
  73498. downSampleOffsets[id] = x / lastLuminance.width;
  73499. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73500. id += 2;
  73501. }
  73502. }
  73503. effect.setArray2("dsOffsets", downSampleOffsets);
  73504. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73505. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73506. lastLuminance = _this.luminancePostProcess;
  73507. }
  73508. else {
  73509. lastLuminance = pp;
  73510. }
  73511. };
  73512. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73513. pp.onAfterRender = function (effect) {
  73514. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73515. 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);
  73516. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73517. };
  73518. }
  73519. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73520. });
  73521. };
  73522. // Create HDR post-process
  73523. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73524. var _this = this;
  73525. 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);
  73526. var outputLiminance = 1;
  73527. var time = 0;
  73528. var lastTime = 0;
  73529. this.hdrPostProcess.onApply = function (effect) {
  73530. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73531. time += scene.getEngine().getDeltaTime();
  73532. if (outputLiminance < 0) {
  73533. outputLiminance = _this._hdrCurrentLuminance;
  73534. }
  73535. else {
  73536. var dt = (lastTime - time) / 1000.0;
  73537. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73538. outputLiminance += _this.hdrDecreaseRate * dt;
  73539. }
  73540. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73541. outputLiminance -= _this.hdrIncreaseRate * dt;
  73542. }
  73543. else {
  73544. outputLiminance = _this._hdrCurrentLuminance;
  73545. }
  73546. }
  73547. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73548. effect.setFloat("averageLuminance", outputLiminance);
  73549. lastTime = time;
  73550. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73551. };
  73552. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73553. };
  73554. // Create lens flare post-process
  73555. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73556. var _this = this;
  73557. 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);
  73558. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73559. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73560. 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);
  73561. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73562. var resolution = new BABYLON.Vector2(0, 0);
  73563. // Lens flare
  73564. this.lensFlarePostProcess.onApply = function (effect) {
  73565. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73566. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73567. effect.setFloat("strength", _this.lensFlareStrength);
  73568. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73569. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73570. // Shift
  73571. resolution.x = _this.lensFlarePostProcess.width;
  73572. resolution.y = _this.lensFlarePostProcess.height;
  73573. effect.setVector2("resolution", resolution);
  73574. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73575. };
  73576. // Compose
  73577. 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);
  73578. 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);
  73579. this.lensFlareComposePostProcess.onApply = function (effect) {
  73580. if (!_this._scene.activeCamera) {
  73581. return;
  73582. }
  73583. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73584. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73585. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73586. // Lens start rotation matrix
  73587. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73588. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73589. 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));
  73590. camRot *= 4.0;
  73591. 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);
  73592. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73593. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73594. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73595. };
  73596. };
  73597. // Create depth-of-field post-process
  73598. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73599. var _this = this;
  73600. 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);
  73601. this.depthOfFieldPostProcess.onApply = function (effect) {
  73602. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73603. effect.setTexture("depthSampler", _this._getDepthTexture());
  73604. effect.setFloat("distance", _this.depthOfFieldDistance);
  73605. };
  73606. // Add to pipeline
  73607. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73608. };
  73609. // Create motion blur post-process
  73610. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73611. var _this = this;
  73612. 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);
  73613. var motionScale = 0;
  73614. var prevViewProjection = BABYLON.Matrix.Identity();
  73615. var invViewProjection = BABYLON.Matrix.Identity();
  73616. var viewProjection = BABYLON.Matrix.Identity();
  73617. var screenSize = BABYLON.Vector2.Zero();
  73618. this.motionBlurPostProcess.onApply = function (effect) {
  73619. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73620. viewProjection.invertToRef(invViewProjection);
  73621. effect.setMatrix("inverseViewProjection", invViewProjection);
  73622. effect.setMatrix("prevViewProjection", prevViewProjection);
  73623. prevViewProjection = viewProjection;
  73624. screenSize.x = _this.motionBlurPostProcess.width;
  73625. screenSize.y = _this.motionBlurPostProcess.height;
  73626. effect.setVector2("screenSize", screenSize);
  73627. motionScale = scene.getEngine().getFps() / 60.0;
  73628. effect.setFloat("motionScale", motionScale);
  73629. effect.setFloat("motionStrength", _this.motionStrength);
  73630. effect.setTexture("depthSampler", _this._getDepthTexture());
  73631. };
  73632. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73633. };
  73634. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73635. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73636. var renderer = this._scene.enableGeometryBufferRenderer();
  73637. return renderer.getGBuffer().textures[0];
  73638. }
  73639. return this._scene.enableDepthRenderer().getDepthMap();
  73640. };
  73641. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73642. for (var i = 0; i < this._cameras.length; i++) {
  73643. var camera = this._cameras[i];
  73644. if (this.originalPostProcess) {
  73645. this.originalPostProcess.dispose(camera);
  73646. }
  73647. if (this.downSampleX4PostProcess) {
  73648. this.downSampleX4PostProcess.dispose(camera);
  73649. }
  73650. if (this.brightPassPostProcess) {
  73651. this.brightPassPostProcess.dispose(camera);
  73652. }
  73653. if (this.textureAdderPostProcess) {
  73654. this.textureAdderPostProcess.dispose(camera);
  73655. }
  73656. if (this.textureAdderFinalPostProcess) {
  73657. this.textureAdderFinalPostProcess.dispose(camera);
  73658. }
  73659. if (this.volumetricLightPostProcess) {
  73660. this.volumetricLightPostProcess.dispose(camera);
  73661. }
  73662. if (this.volumetricLightSmoothXPostProcess) {
  73663. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73664. }
  73665. if (this.volumetricLightSmoothYPostProcess) {
  73666. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73667. }
  73668. if (this.volumetricLightMergePostProces) {
  73669. this.volumetricLightMergePostProces.dispose(camera);
  73670. }
  73671. if (this.volumetricLightFinalPostProcess) {
  73672. this.volumetricLightFinalPostProcess.dispose(camera);
  73673. }
  73674. if (this.lensFlarePostProcess) {
  73675. this.lensFlarePostProcess.dispose(camera);
  73676. }
  73677. if (this.lensFlareComposePostProcess) {
  73678. this.lensFlareComposePostProcess.dispose(camera);
  73679. }
  73680. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73681. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73682. }
  73683. if (this.luminancePostProcess) {
  73684. this.luminancePostProcess.dispose(camera);
  73685. }
  73686. if (this.hdrPostProcess) {
  73687. this.hdrPostProcess.dispose(camera);
  73688. }
  73689. if (this.hdrFinalPostProcess) {
  73690. this.hdrFinalPostProcess.dispose(camera);
  73691. }
  73692. if (this.depthOfFieldPostProcess) {
  73693. this.depthOfFieldPostProcess.dispose(camera);
  73694. }
  73695. if (this.motionBlurPostProcess) {
  73696. this.motionBlurPostProcess.dispose(camera);
  73697. }
  73698. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73699. this.blurHPostProcesses[j].dispose(camera);
  73700. }
  73701. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73702. this.blurVPostProcesses[j].dispose(camera);
  73703. }
  73704. }
  73705. this.originalPostProcess = null;
  73706. this.downSampleX4PostProcess = null;
  73707. this.brightPassPostProcess = null;
  73708. this.textureAdderPostProcess = null;
  73709. this.textureAdderFinalPostProcess = null;
  73710. this.volumetricLightPostProcess = null;
  73711. this.volumetricLightSmoothXPostProcess = null;
  73712. this.volumetricLightSmoothYPostProcess = null;
  73713. this.volumetricLightMergePostProces = null;
  73714. this.volumetricLightFinalPostProcess = null;
  73715. this.lensFlarePostProcess = null;
  73716. this.lensFlareComposePostProcess = null;
  73717. this.luminancePostProcess = null;
  73718. this.hdrPostProcess = null;
  73719. this.hdrFinalPostProcess = null;
  73720. this.depthOfFieldPostProcess = null;
  73721. this.motionBlurPostProcess = null;
  73722. this.luminanceDownSamplePostProcesses = [];
  73723. this.blurHPostProcesses = [];
  73724. this.blurVPostProcesses = [];
  73725. };
  73726. // Dispose
  73727. StandardRenderingPipeline.prototype.dispose = function () {
  73728. this._disposePostProcesses();
  73729. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73730. _super.prototype.dispose.call(this);
  73731. };
  73732. // Serialize rendering pipeline
  73733. StandardRenderingPipeline.prototype.serialize = function () {
  73734. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73735. serializationObject.customType = "StandardRenderingPipeline";
  73736. return serializationObject;
  73737. };
  73738. /**
  73739. * Static members
  73740. */
  73741. // Parse serialized pipeline
  73742. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73743. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73744. };
  73745. // Luminance steps
  73746. StandardRenderingPipeline.LuminanceSteps = 6;
  73747. __decorate([
  73748. BABYLON.serialize()
  73749. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  73750. __decorate([
  73751. BABYLON.serialize()
  73752. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  73753. __decorate([
  73754. BABYLON.serialize()
  73755. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  73756. __decorate([
  73757. BABYLON.serialize()
  73758. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  73759. __decorate([
  73760. BABYLON.serializeAsTexture("lensTexture")
  73761. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  73762. __decorate([
  73763. BABYLON.serialize()
  73764. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  73765. __decorate([
  73766. BABYLON.serialize()
  73767. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  73768. __decorate([
  73769. BABYLON.serialize()
  73770. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  73771. __decorate([
  73772. BABYLON.serialize()
  73773. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  73774. __decorate([
  73775. BABYLON.serialize()
  73776. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  73777. __decorate([
  73778. BABYLON.serialize()
  73779. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  73780. __decorate([
  73781. BABYLON.serializeAsTexture("lensColorTexture")
  73782. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  73783. __decorate([
  73784. BABYLON.serialize()
  73785. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  73786. __decorate([
  73787. BABYLON.serialize()
  73788. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  73789. __decorate([
  73790. BABYLON.serialize()
  73791. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  73792. __decorate([
  73793. BABYLON.serialize()
  73794. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  73795. __decorate([
  73796. BABYLON.serializeAsTexture("lensStarTexture")
  73797. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  73798. __decorate([
  73799. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  73800. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  73801. __decorate([
  73802. BABYLON.serialize()
  73803. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  73804. __decorate([
  73805. BABYLON.serialize()
  73806. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  73807. __decorate([
  73808. BABYLON.serialize()
  73809. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  73810. __decorate([
  73811. BABYLON.serialize()
  73812. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  73813. __decorate([
  73814. BABYLON.serialize()
  73815. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  73816. __decorate([
  73817. BABYLON.serialize()
  73818. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  73819. __decorate([
  73820. BABYLON.serialize()
  73821. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  73822. __decorate([
  73823. BABYLON.serialize()
  73824. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  73825. __decorate([
  73826. BABYLON.serialize()
  73827. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  73828. __decorate([
  73829. BABYLON.serialize()
  73830. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  73831. __decorate([
  73832. BABYLON.serialize()
  73833. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  73834. __decorate([
  73835. BABYLON.serialize()
  73836. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  73837. return StandardRenderingPipeline;
  73838. }(BABYLON.PostProcessRenderPipeline));
  73839. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  73840. })(BABYLON || (BABYLON = {}));
  73841. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  73842. var BABYLON;
  73843. (function (BABYLON) {
  73844. var FxaaPostProcess = /** @class */ (function (_super) {
  73845. __extends(FxaaPostProcess, _super);
  73846. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73847. if (camera === void 0) { camera = null; }
  73848. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73849. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  73850. _this.onApplyObservable.add(function (effect) {
  73851. var texelSize = _this.texelSize;
  73852. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  73853. });
  73854. return _this;
  73855. }
  73856. return FxaaPostProcess;
  73857. }(BABYLON.PostProcess));
  73858. BABYLON.FxaaPostProcess = FxaaPostProcess;
  73859. })(BABYLON || (BABYLON = {}));
  73860. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  73861. var BABYLON;
  73862. (function (BABYLON) {
  73863. /**
  73864. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  73865. */
  73866. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  73867. __extends(ChromaticAberrationPostProcess, _super);
  73868. /**
  73869. * Creates a new instance ChromaticAberrationPostProcess
  73870. * @param name The name of the effect.
  73871. * @param screenWidth The width of the screen to apply the effect on.
  73872. * @param screenHeight The height of the screen to apply the effect on.
  73873. * @param options The required width/height ratio to downsize to before computing the render pass.
  73874. * @param camera The camera to apply the render pass to.
  73875. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73876. * @param engine The engine which the post process will be applied. (default: current engine)
  73877. * @param reusable If the post process can be reused on the same frame. (default: false)
  73878. * @param textureType Type of textures used when performing the post process. (default: 0)
  73879. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  73880. */
  73881. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73882. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73883. if (blockCompilation === void 0) { blockCompilation = false; }
  73884. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73885. /**
  73886. * The amount of seperation of rgb channels (default: 30)
  73887. */
  73888. _this.aberrationAmount = 30;
  73889. /**
  73890. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  73891. */
  73892. _this.radialIntensity = 0;
  73893. /**
  73894. * 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))
  73895. */
  73896. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  73897. /**
  73898. * 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))
  73899. */
  73900. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  73901. _this.onApplyObservable.add(function (effect) {
  73902. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  73903. effect.setFloat('screen_width', screenWidth);
  73904. effect.setFloat('screen_height', screenHeight);
  73905. effect.setFloat('radialIntensity', _this.radialIntensity);
  73906. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  73907. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  73908. });
  73909. return _this;
  73910. }
  73911. return ChromaticAberrationPostProcess;
  73912. }(BABYLON.PostProcess));
  73913. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  73914. })(BABYLON || (BABYLON = {}));
  73915. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  73916. var BABYLON;
  73917. (function (BABYLON) {
  73918. /**
  73919. * The GrainPostProcess adds noise to the image at mid luminance levels
  73920. */
  73921. var GrainPostProcess = /** @class */ (function (_super) {
  73922. __extends(GrainPostProcess, _super);
  73923. /**
  73924. * Creates a new instance of @see GrainPostProcess
  73925. * @param name The name of the effect.
  73926. * @param options The required width/height ratio to downsize to before computing the render pass.
  73927. * @param camera The camera to apply the render pass to.
  73928. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73929. * @param engine The engine which the post process will be applied. (default: current engine)
  73930. * @param reusable If the post process can be reused on the same frame. (default: false)
  73931. * @param textureType Type of textures used when performing the post process. (default: 0)
  73932. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  73933. */
  73934. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73935. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73936. if (blockCompilation === void 0) { blockCompilation = false; }
  73937. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73938. /**
  73939. * The intensity of the grain added (default: 30)
  73940. */
  73941. _this.intensity = 30;
  73942. /**
  73943. * If the grain should be randomized on every frame
  73944. */
  73945. _this.animated = false;
  73946. _this.onApplyObservable.add(function (effect) {
  73947. effect.setFloat('intensity', _this.intensity);
  73948. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  73949. });
  73950. return _this;
  73951. }
  73952. return GrainPostProcess;
  73953. }(BABYLON.PostProcess));
  73954. BABYLON.GrainPostProcess = GrainPostProcess;
  73955. })(BABYLON || (BABYLON = {}));
  73956. //# sourceMappingURL=babylon.grainPostProcess.js.map
  73957. var BABYLON;
  73958. (function (BABYLON) {
  73959. /**
  73960. * The SharpenPostProcess applies a sharpen kernel to every pixel
  73961. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  73962. */
  73963. var SharpenPostProcess = /** @class */ (function (_super) {
  73964. __extends(SharpenPostProcess, _super);
  73965. /**
  73966. * Creates a new instance ConvolutionPostProcess
  73967. * @param name The name of the effect.
  73968. * @param options The required width/height ratio to downsize to before computing the render pass.
  73969. * @param camera The camera to apply the render pass to.
  73970. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73971. * @param engine The engine which the post process will be applied. (default: current engine)
  73972. * @param reusable If the post process can be reused on the same frame. (default: false)
  73973. * @param textureType Type of textures used when performing the post process. (default: 0)
  73974. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  73975. */
  73976. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73977. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73978. if (blockCompilation === void 0) { blockCompilation = false; }
  73979. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73980. /**
  73981. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  73982. */
  73983. _this.colorAmount = 1.0;
  73984. /**
  73985. * How much sharpness should be applied (default: 0.3)
  73986. */
  73987. _this.edgeAmount = 0.3;
  73988. _this.onApply = function (effect) {
  73989. effect.setFloat2("screenSize", _this.width, _this.height);
  73990. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  73991. };
  73992. return _this;
  73993. }
  73994. return SharpenPostProcess;
  73995. }(BABYLON.PostProcess));
  73996. BABYLON.SharpenPostProcess = SharpenPostProcess;
  73997. })(BABYLON || (BABYLON = {}));
  73998. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  73999. var BABYLON;
  74000. (function (BABYLON) {
  74001. /**
  74002. * The Blur Post Process which blurs an image based on a kernel and direction.
  74003. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74004. */
  74005. var BlurPostProcess = /** @class */ (function (_super) {
  74006. __extends(BlurPostProcess, _super);
  74007. /**
  74008. * Creates a new instance BlurPostProcess
  74009. * @param name The name of the effect.
  74010. * @param direction The direction in which to blur the image.
  74011. * @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.
  74012. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74013. * @param camera The camera to apply the render pass to.
  74014. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74015. * @param engine The engine which the post process will be applied. (default: current engine)
  74016. * @param reusable If the post process can be reused on the same frame. (default: false)
  74017. * @param textureType Type of textures used when performing the post process. (default: 0)
  74018. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74019. */
  74020. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74021. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74022. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74023. if (defines === void 0) { defines = ""; }
  74024. if (blockCompilation === void 0) { blockCompilation = false; }
  74025. 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;
  74026. _this.direction = direction;
  74027. _this.blockCompilation = blockCompilation;
  74028. _this._packedFloat = false;
  74029. _this._staticDefines = "";
  74030. _this._staticDefines = defines;
  74031. _this.onApplyObservable.add(function (effect) {
  74032. if (_this._outputTexture) {
  74033. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74034. }
  74035. else {
  74036. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74037. }
  74038. });
  74039. _this.kernel = kernel;
  74040. return _this;
  74041. }
  74042. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74043. /**
  74044. * Gets the length in pixels of the blur sample region
  74045. */
  74046. get: function () {
  74047. return this._idealKernel;
  74048. },
  74049. /**
  74050. * Sets the length in pixels of the blur sample region
  74051. */
  74052. set: function (v) {
  74053. if (this._idealKernel === v) {
  74054. return;
  74055. }
  74056. v = Math.max(v, 1);
  74057. this._idealKernel = v;
  74058. this._kernel = this._nearestBestKernel(v);
  74059. if (!this.blockCompilation) {
  74060. this._updateParameters();
  74061. }
  74062. },
  74063. enumerable: true,
  74064. configurable: true
  74065. });
  74066. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74067. /**
  74068. * Gets wether or not the blur is unpacking/repacking floats
  74069. */
  74070. get: function () {
  74071. return this._packedFloat;
  74072. },
  74073. /**
  74074. * Sets wether or not the blur needs to unpack/repack floats
  74075. */
  74076. set: function (v) {
  74077. if (this._packedFloat === v) {
  74078. return;
  74079. }
  74080. this._packedFloat = v;
  74081. if (!this.blockCompilation) {
  74082. this._updateParameters();
  74083. }
  74084. },
  74085. enumerable: true,
  74086. configurable: true
  74087. });
  74088. /**
  74089. * Updates the effect with the current post process compile time values and recompiles the shader.
  74090. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74091. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74092. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74093. * @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
  74094. * @param onCompiled Called when the shader has been compiled.
  74095. * @param onError Called if there is an error when compiling a shader.
  74096. */
  74097. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74098. if (defines === void 0) { defines = null; }
  74099. if (uniforms === void 0) { uniforms = null; }
  74100. if (samplers === void 0) { samplers = null; }
  74101. this._updateParameters(onCompiled, onError);
  74102. };
  74103. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74104. // Generate sampling offsets and weights
  74105. var N = this._kernel;
  74106. var centerIndex = (N - 1) / 2;
  74107. // Generate Gaussian sampling weights over kernel
  74108. var offsets = [];
  74109. var weights = [];
  74110. var totalWeight = 0;
  74111. for (var i = 0; i < N; i++) {
  74112. var u = i / (N - 1);
  74113. var w = this._gaussianWeight(u * 2.0 - 1);
  74114. offsets[i] = (i - centerIndex);
  74115. weights[i] = w;
  74116. totalWeight += w;
  74117. }
  74118. // Normalize weights
  74119. for (var i = 0; i < weights.length; i++) {
  74120. weights[i] /= totalWeight;
  74121. }
  74122. // Optimize: combine samples to take advantage of hardware linear sampling
  74123. // Walk from left to center, combining pairs (symmetrically)
  74124. var linearSamplingWeights = [];
  74125. var linearSamplingOffsets = [];
  74126. var linearSamplingMap = [];
  74127. for (var i = 0; i <= centerIndex; i += 2) {
  74128. var j = Math.min(i + 1, Math.floor(centerIndex));
  74129. var singleCenterSample = i === j;
  74130. if (singleCenterSample) {
  74131. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74132. }
  74133. else {
  74134. var sharedCell = j === centerIndex;
  74135. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74136. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74137. if (offsetLinear === 0) {
  74138. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74139. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74140. }
  74141. else {
  74142. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74143. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74144. }
  74145. }
  74146. }
  74147. for (var i = 0; i < linearSamplingMap.length; i++) {
  74148. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74149. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74150. }
  74151. // Replace with optimized
  74152. offsets = linearSamplingOffsets;
  74153. weights = linearSamplingWeights;
  74154. // Generate shaders
  74155. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74156. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74157. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74158. var defines = "";
  74159. defines += this._staticDefines;
  74160. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74161. if (this._staticDefines.indexOf("DOF") != -1) {
  74162. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74163. varyingCount--;
  74164. }
  74165. for (var i = 0; i < varyingCount; i++) {
  74166. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74167. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74168. }
  74169. var depCount = 0;
  74170. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74171. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74172. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74173. depCount++;
  74174. }
  74175. if (this.packedFloat) {
  74176. defines += "#define PACKEDFLOAT 1";
  74177. }
  74178. this.blockCompilation = false;
  74179. _super.prototype.updateEffect.call(this, defines, null, null, {
  74180. varyingCount: varyingCount,
  74181. depCount: depCount
  74182. }, onCompiled, onError);
  74183. };
  74184. /**
  74185. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74186. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74187. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74188. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74189. * The gaps between physical kernels are compensated for in the weighting of the samples
  74190. * @param idealKernel Ideal blur kernel.
  74191. * @return Nearest best kernel.
  74192. */
  74193. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74194. var v = Math.round(idealKernel);
  74195. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74196. var k = _a[_i];
  74197. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74198. return Math.max(k, 3);
  74199. }
  74200. }
  74201. return Math.max(v, 3);
  74202. };
  74203. /**
  74204. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74205. * @param x The point on the Gaussian distribution to sample.
  74206. * @return the value of the Gaussian function at x.
  74207. */
  74208. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74209. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74210. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74211. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74212. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74213. // truncated at around 1.3% of peak strength.
  74214. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74215. var sigma = (1 / 3);
  74216. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74217. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74218. var weight = (1.0 / denominator) * Math.exp(exponent);
  74219. return weight;
  74220. };
  74221. /**
  74222. * Generates a string that can be used as a floating point number in GLSL.
  74223. * @param x Value to print.
  74224. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74225. * @return GLSL float string.
  74226. */
  74227. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74228. if (decimalFigures === void 0) { decimalFigures = 8; }
  74229. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74230. };
  74231. return BlurPostProcess;
  74232. }(BABYLON.PostProcess));
  74233. BABYLON.BlurPostProcess = BlurPostProcess;
  74234. })(BABYLON || (BABYLON = {}));
  74235. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74236. var BABYLON;
  74237. (function (BABYLON) {
  74238. /**
  74239. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74240. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74241. * based on samples that have a large difference in distance than the center pixel.
  74242. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74243. */
  74244. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74245. __extends(DepthOfFieldBlurPostProcess, _super);
  74246. /**
  74247. * Creates a new instance CircleOfConfusionPostProcess
  74248. * @param name The name of the effect.
  74249. * @param scene The scene the effect belongs to.
  74250. * @param direction The direction the blur should be applied.
  74251. * @param kernel The size of the kernel used to blur.
  74252. * @param options The required width/height ratio to downsize to before computing the render pass.
  74253. * @param camera The camera to apply the render pass to.
  74254. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74255. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74256. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74257. * @param engine The engine which the post process will be applied. (default: current engine)
  74258. * @param reusable If the post process can be reused on the same frame. (default: false)
  74259. * @param textureType Type of textures used when performing the post process. (default: 0)
  74260. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74261. */
  74262. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74263. if (imageToBlur === void 0) { imageToBlur = null; }
  74264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74265. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74266. if (blockCompilation === void 0) { blockCompilation = false; }
  74267. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  74268. _this.direction = direction;
  74269. _this.onApplyObservable.add(function (effect) {
  74270. if (imageToBlur != null) {
  74271. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74272. }
  74273. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74274. if (scene.activeCamera) {
  74275. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74276. }
  74277. });
  74278. return _this;
  74279. }
  74280. return DepthOfFieldBlurPostProcess;
  74281. }(BABYLON.BlurPostProcess));
  74282. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74283. })(BABYLON || (BABYLON = {}));
  74284. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74285. var BABYLON;
  74286. (function (BABYLON) {
  74287. /**
  74288. * Options to be set when merging outputs from the default pipeline.
  74289. */
  74290. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74291. function DepthOfFieldMergePostProcessOptions() {
  74292. }
  74293. return DepthOfFieldMergePostProcessOptions;
  74294. }());
  74295. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74296. /**
  74297. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74298. */
  74299. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74300. __extends(DepthOfFieldMergePostProcess, _super);
  74301. /**
  74302. * Creates a new instance of DepthOfFieldMergePostProcess
  74303. * @param name The name of the effect.
  74304. * @param originalFromInput Post process which's input will be used for the merge.
  74305. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74306. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74307. * @param options The required width/height ratio to downsize to before computing the render pass.
  74308. * @param camera The camera to apply the render pass to.
  74309. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74310. * @param engine The engine which the post process will be applied. (default: current engine)
  74311. * @param reusable If the post process can be reused on the same frame. (default: false)
  74312. * @param textureType Type of textures used when performing the post process. (default: 0)
  74313. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74314. */
  74315. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74316. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74317. if (blockCompilation === void 0) { blockCompilation = false; }
  74318. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74319. _this.blurSteps = blurSteps;
  74320. _this.onApplyObservable.add(function (effect) {
  74321. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74322. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74323. blurSteps.forEach(function (step, index) {
  74324. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74325. });
  74326. });
  74327. if (!blockCompilation) {
  74328. _this.updateEffect();
  74329. }
  74330. return _this;
  74331. }
  74332. /**
  74333. * Updates the effect with the current post process compile time values and recompiles the shader.
  74334. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74335. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74336. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74337. * @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
  74338. * @param onCompiled Called when the shader has been compiled.
  74339. * @param onError Called if there is an error when compiling a shader.
  74340. */
  74341. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74342. if (defines === void 0) { defines = null; }
  74343. if (uniforms === void 0) { uniforms = null; }
  74344. if (samplers === void 0) { samplers = null; }
  74345. if (!defines) {
  74346. defines = "";
  74347. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74348. }
  74349. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74350. };
  74351. return DepthOfFieldMergePostProcess;
  74352. }(BABYLON.PostProcess));
  74353. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74354. })(BABYLON || (BABYLON = {}));
  74355. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74356. var BABYLON;
  74357. (function (BABYLON) {
  74358. /**
  74359. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74360. */
  74361. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74362. __extends(CircleOfConfusionPostProcess, _super);
  74363. /**
  74364. * Creates a new instance CircleOfConfusionPostProcess
  74365. * @param name The name of the effect.
  74366. * @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.
  74367. * @param options The required width/height ratio to downsize to before computing the render pass.
  74368. * @param camera The camera to apply the render pass to.
  74369. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74370. * @param engine The engine which the post process will be applied. (default: current engine)
  74371. * @param reusable If the post process can be reused on the same frame. (default: false)
  74372. * @param textureType Type of textures used when performing the post process. (default: 0)
  74373. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74374. */
  74375. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74376. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74377. if (blockCompilation === void 0) { blockCompilation = false; }
  74378. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74379. /**
  74380. * 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.
  74381. */
  74382. _this.lensSize = 50;
  74383. /**
  74384. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74385. */
  74386. _this.fStop = 1.4;
  74387. /**
  74388. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74389. */
  74390. _this.focusDistance = 2000;
  74391. /**
  74392. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74393. */
  74394. _this.focalLength = 50;
  74395. _this._depthTexture = null;
  74396. _this._depthTexture = depthTexture;
  74397. _this.onApplyObservable.add(function (effect) {
  74398. if (!_this._depthTexture) {
  74399. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74400. return;
  74401. }
  74402. effect.setTexture("depthSampler", _this._depthTexture);
  74403. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74404. var aperture = _this.lensSize / _this.fStop;
  74405. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74406. effect.setFloat('focusDistance', _this.focusDistance);
  74407. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74408. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74409. });
  74410. return _this;
  74411. }
  74412. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74413. /**
  74414. * 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.
  74415. */
  74416. set: function (value) {
  74417. this._depthTexture = value;
  74418. },
  74419. enumerable: true,
  74420. configurable: true
  74421. });
  74422. return CircleOfConfusionPostProcess;
  74423. }(BABYLON.PostProcess));
  74424. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74425. })(BABYLON || (BABYLON = {}));
  74426. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74427. var BABYLON;
  74428. (function (BABYLON) {
  74429. /**
  74430. * Specifies the level of max blur that should be applied when using the depth of field effect
  74431. */
  74432. var DepthOfFieldEffectBlurLevel;
  74433. (function (DepthOfFieldEffectBlurLevel) {
  74434. /**
  74435. * Subtle blur
  74436. */
  74437. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74438. /**
  74439. * Medium blur
  74440. */
  74441. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74442. /**
  74443. * Large blur
  74444. */
  74445. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74446. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74447. ;
  74448. /**
  74449. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74450. */
  74451. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74452. __extends(DepthOfFieldEffect, _super);
  74453. /**
  74454. * Creates a new instance DepthOfFieldEffect
  74455. * @param scene The scene the effect belongs to.
  74456. * @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.
  74457. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74458. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74459. */
  74460. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74461. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74462. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74463. if (blockCompilation === void 0) { blockCompilation = false; }
  74464. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74465. return _this._effects;
  74466. }, true) || this;
  74467. /**
  74468. * Internal post processes in depth of field effect
  74469. */
  74470. _this._effects = [];
  74471. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74472. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74473. // 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)
  74474. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74475. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74476. _this._depthOfFieldBlurY = [];
  74477. _this._depthOfFieldBlurX = [];
  74478. var blurCount = 1;
  74479. var kernelSize = 15;
  74480. switch (blurLevel) {
  74481. case DepthOfFieldEffectBlurLevel.High: {
  74482. blurCount = 3;
  74483. kernelSize = 51;
  74484. break;
  74485. }
  74486. case DepthOfFieldEffectBlurLevel.Medium: {
  74487. blurCount = 2;
  74488. kernelSize = 31;
  74489. break;
  74490. }
  74491. default: {
  74492. kernelSize = 15;
  74493. blurCount = 1;
  74494. break;
  74495. }
  74496. }
  74497. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74498. var ratio = 1.0;
  74499. for (var i = 0; i < blurCount; i++) {
  74500. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74501. blurY.autoClear = false;
  74502. ratio = 0.75 / Math.pow(2, i);
  74503. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74504. blurX.autoClear = false;
  74505. _this._depthOfFieldBlurY.push(blurY);
  74506. _this._depthOfFieldBlurX.push(blurX);
  74507. }
  74508. // Set all post processes on the effect.
  74509. _this._effects = [_this._circleOfConfusion];
  74510. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74511. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74512. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74513. }
  74514. // Merge blurred images with original image based on circleOfConfusion
  74515. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74516. _this._dofMerge.autoClear = false;
  74517. _this._effects.push(_this._dofMerge);
  74518. return _this;
  74519. }
  74520. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74521. get: function () {
  74522. return this._circleOfConfusion.focalLength;
  74523. },
  74524. /**
  74525. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74526. */
  74527. set: function (value) {
  74528. this._circleOfConfusion.focalLength = value;
  74529. },
  74530. enumerable: true,
  74531. configurable: true
  74532. });
  74533. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74534. get: function () {
  74535. return this._circleOfConfusion.fStop;
  74536. },
  74537. /**
  74538. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74539. */
  74540. set: function (value) {
  74541. this._circleOfConfusion.fStop = value;
  74542. },
  74543. enumerable: true,
  74544. configurable: true
  74545. });
  74546. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74547. get: function () {
  74548. return this._circleOfConfusion.focusDistance;
  74549. },
  74550. /**
  74551. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74552. */
  74553. set: function (value) {
  74554. this._circleOfConfusion.focusDistance = value;
  74555. },
  74556. enumerable: true,
  74557. configurable: true
  74558. });
  74559. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74560. get: function () {
  74561. return this._circleOfConfusion.lensSize;
  74562. },
  74563. /**
  74564. * 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.
  74565. */
  74566. set: function (value) {
  74567. this._circleOfConfusion.lensSize = value;
  74568. },
  74569. enumerable: true,
  74570. configurable: true
  74571. });
  74572. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74573. /**
  74574. * 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.
  74575. */
  74576. set: function (value) {
  74577. this._circleOfConfusion.depthTexture = value;
  74578. },
  74579. enumerable: true,
  74580. configurable: true
  74581. });
  74582. /**
  74583. * Disposes each of the internal effects for a given camera.
  74584. * @param camera The camera to dispose the effect on.
  74585. */
  74586. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74587. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74588. this._effects[effectIndex].dispose(camera);
  74589. }
  74590. };
  74591. /**
  74592. * Internal
  74593. */
  74594. DepthOfFieldEffect.prototype._updateEffects = function () {
  74595. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74596. this._effects[effectIndex].updateEffect();
  74597. }
  74598. };
  74599. /**
  74600. * Internal
  74601. * @returns if all the contained post processes are ready.
  74602. */
  74603. DepthOfFieldEffect.prototype._isReady = function () {
  74604. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74605. if (!this._effects[effectIndex].isReady()) {
  74606. return false;
  74607. }
  74608. }
  74609. return true;
  74610. };
  74611. return DepthOfFieldEffect;
  74612. }(BABYLON.PostProcessRenderEffect));
  74613. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74614. })(BABYLON || (BABYLON = {}));
  74615. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74616. var BABYLON;
  74617. (function (BABYLON) {
  74618. /**
  74619. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74620. */
  74621. var BloomMergePostProcess = /** @class */ (function (_super) {
  74622. __extends(BloomMergePostProcess, _super);
  74623. /**
  74624. * Creates a new instance of @see BloomMergePostProcess
  74625. * @param name The name of the effect.
  74626. * @param originalFromInput Post process which's input will be used for the merge.
  74627. * @param blurred Blurred highlights post process which's output will be used.
  74628. * @param weight Weight of the bloom to be added to the original input.
  74629. * @param options The required width/height ratio to downsize to before computing the render pass.
  74630. * @param camera The camera to apply the render pass to.
  74631. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74632. * @param engine The engine which the post process will be applied. (default: current engine)
  74633. * @param reusable If the post process can be reused on the same frame. (default: false)
  74634. * @param textureType Type of textures used when performing the post process. (default: 0)
  74635. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74636. */
  74637. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74638. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74639. if (blockCompilation === void 0) { blockCompilation = false; }
  74640. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74641. _this.weight = weight;
  74642. _this.onApplyObservable.add(function (effect) {
  74643. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74644. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74645. effect.setFloat("bloomWeight", _this.weight);
  74646. });
  74647. if (!blockCompilation) {
  74648. _this.updateEffect();
  74649. }
  74650. return _this;
  74651. }
  74652. return BloomMergePostProcess;
  74653. }(BABYLON.PostProcess));
  74654. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74655. })(BABYLON || (BABYLON = {}));
  74656. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74657. var BABYLON;
  74658. (function (BABYLON) {
  74659. /**
  74660. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  74661. */
  74662. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  74663. __extends(ExtractHighlightsPostProcess, _super);
  74664. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74665. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74666. if (blockCompilation === void 0) { blockCompilation = false; }
  74667. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74668. /**
  74669. * The luminance threshold, pixels below this value will be set to black.
  74670. */
  74671. _this.threshold = 0.9;
  74672. /**
  74673. * Internal
  74674. */
  74675. _this._exposure = 1;
  74676. /**
  74677. * Post process which has the input texture to be used when performing highlight extraction
  74678. */
  74679. _this._inputPostProcess = null;
  74680. _this.onApplyObservable.add(function (effect) {
  74681. if (_this._inputPostProcess) {
  74682. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74683. }
  74684. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74685. effect.setFloat('exposure', _this._exposure);
  74686. });
  74687. return _this;
  74688. }
  74689. return ExtractHighlightsPostProcess;
  74690. }(BABYLON.PostProcess));
  74691. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74692. })(BABYLON || (BABYLON = {}));
  74693. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74694. var BABYLON;
  74695. (function (BABYLON) {
  74696. /**
  74697. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74698. */
  74699. var BloomEffect = /** @class */ (function (_super) {
  74700. __extends(BloomEffect, _super);
  74701. /**
  74702. * Creates a new instance of @see BloomEffect
  74703. * @param scene The scene the effect belongs to.
  74704. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74705. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74706. * @param bloomWeight The the strength of bloom.
  74707. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74708. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  74709. */
  74710. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74711. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74712. if (blockCompilation === void 0) { blockCompilation = false; }
  74713. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74714. return _this._effects;
  74715. }, true) || this;
  74716. _this.bloomScale = bloomScale;
  74717. /**
  74718. * Internal
  74719. */
  74720. _this._effects = [];
  74721. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74722. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  74723. _this._blurX.alwaysForcePOT = true;
  74724. _this._blurX.autoClear = false;
  74725. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  74726. _this._blurY.alwaysForcePOT = true;
  74727. _this._blurY.autoClear = false;
  74728. _this.kernel = bloomKernel;
  74729. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74730. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74731. _this._merge.autoClear = false;
  74732. _this._effects.push(_this._merge);
  74733. return _this;
  74734. }
  74735. Object.defineProperty(BloomEffect.prototype, "threshold", {
  74736. /**
  74737. * The luminance threshold to find bright areas of the image to bloom.
  74738. */
  74739. get: function () {
  74740. return this._downscale.threshold;
  74741. },
  74742. set: function (value) {
  74743. this._downscale.threshold = value;
  74744. },
  74745. enumerable: true,
  74746. configurable: true
  74747. });
  74748. Object.defineProperty(BloomEffect.prototype, "weight", {
  74749. /**
  74750. * The strength of the bloom.
  74751. */
  74752. get: function () {
  74753. return this._merge.weight;
  74754. },
  74755. set: function (value) {
  74756. this._merge.weight = value;
  74757. },
  74758. enumerable: true,
  74759. configurable: true
  74760. });
  74761. Object.defineProperty(BloomEffect.prototype, "kernel", {
  74762. /**
  74763. * Specifies the size of the bloom blur kernel, relative to the final output size
  74764. */
  74765. get: function () {
  74766. return this._blurX.kernel / this.bloomScale;
  74767. },
  74768. set: function (value) {
  74769. this._blurX.kernel = value * this.bloomScale;
  74770. this._blurY.kernel = value * this.bloomScale;
  74771. },
  74772. enumerable: true,
  74773. configurable: true
  74774. });
  74775. /**
  74776. * Disposes each of the internal effects for a given camera.
  74777. * @param camera The camera to dispose the effect on.
  74778. */
  74779. BloomEffect.prototype.disposeEffects = function (camera) {
  74780. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74781. this._effects[effectIndex].dispose(camera);
  74782. }
  74783. };
  74784. /**
  74785. * Internal
  74786. */
  74787. BloomEffect.prototype._updateEffects = function () {
  74788. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74789. this._effects[effectIndex].updateEffect();
  74790. }
  74791. };
  74792. /**
  74793. * Internal
  74794. * @returns if all the contained post processes are ready.
  74795. */
  74796. BloomEffect.prototype._isReady = function () {
  74797. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74798. if (!this._effects[effectIndex].isReady()) {
  74799. return false;
  74800. }
  74801. }
  74802. return true;
  74803. };
  74804. return BloomEffect;
  74805. }(BABYLON.PostProcessRenderEffect));
  74806. BABYLON.BloomEffect = BloomEffect;
  74807. })(BABYLON || (BABYLON = {}));
  74808. //# sourceMappingURL=babylon.bloomEffect.js.map
  74809. var BABYLON;
  74810. (function (BABYLON) {
  74811. /**
  74812. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  74813. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  74814. */
  74815. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  74816. __extends(DefaultRenderingPipeline, _super);
  74817. /**
  74818. * @constructor
  74819. * @param {string} name - The rendering pipeline name
  74820. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74821. * @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)
  74822. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74823. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  74824. */
  74825. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  74826. if (automaticBuild === void 0) { automaticBuild = true; }
  74827. var _this = _super.call(this, scene.getEngine(), name) || this;
  74828. _this._originalCameras = [];
  74829. /**
  74830. * ID of the sharpen post process,
  74831. */
  74832. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  74833. /**
  74834. * ID of the image processing post process;
  74835. */
  74836. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  74837. /**
  74838. * ID of the Fast Approximate Anti-Aliasing post process;
  74839. */
  74840. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  74841. /**
  74842. * ID of the chromatic aberration post process,
  74843. */
  74844. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  74845. /**
  74846. * ID of the grain post process
  74847. */
  74848. _this.GrainPostProcessId = "GrainPostProcessEffect";
  74849. /**
  74850. * Animations which can be used to tweak settings over a period of time
  74851. */
  74852. _this.animations = [];
  74853. _this._imageProcessingConfigurationObserver = null;
  74854. // Values
  74855. _this._sharpenEnabled = false;
  74856. _this._bloomEnabled = false;
  74857. _this._depthOfFieldEnabled = false;
  74858. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  74859. _this._fxaaEnabled = false;
  74860. _this._imageProcessingEnabled = true;
  74861. _this._bloomScale = 0.5;
  74862. _this._chromaticAberrationEnabled = false;
  74863. _this._grainEnabled = false;
  74864. _this._buildAllowed = true;
  74865. _this._resizeObserver = null;
  74866. _this._hardwareScaleLevel = 1.0;
  74867. _this._bloomKernel = 64;
  74868. /**
  74869. * Specifies the weight of the bloom in the final rendering
  74870. */
  74871. _this._bloomWeight = 0.15;
  74872. /**
  74873. * Specifies the luma threshold for the area that will be blurred by the bloom
  74874. */
  74875. _this._bloomThreshold = 0.9;
  74876. _this._samples = 1;
  74877. _this._hasCleared = false;
  74878. _this._prevPostProcess = null;
  74879. _this._prevPrevPostProcess = null;
  74880. _this._cameras = cameras || [];
  74881. _this._originalCameras = _this._cameras.slice();
  74882. _this._buildAllowed = automaticBuild;
  74883. // Initialize
  74884. _this._scene = scene;
  74885. var caps = _this._scene.getEngine().getCaps();
  74886. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  74887. // Misc
  74888. if (_this._hdr) {
  74889. if (caps.textureHalfFloatRender) {
  74890. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74891. }
  74892. else if (caps.textureFloatRender) {
  74893. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74894. }
  74895. }
  74896. else {
  74897. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74898. }
  74899. // Attach
  74900. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74901. var engine = _this._scene.getEngine();
  74902. // Create post processes before hand so they can be modified before enabled.
  74903. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  74904. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74905. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  74906. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  74907. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  74908. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74909. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  74910. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74911. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  74912. _this._resizeObserver = engine.onResizeObservable.add(function () {
  74913. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  74914. _this.bloomKernel = _this.bloomKernel;
  74915. });
  74916. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74917. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  74918. });
  74919. _this._buildPipeline();
  74920. return _this;
  74921. }
  74922. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  74923. get: function () {
  74924. return this._sharpenEnabled;
  74925. },
  74926. /**
  74927. * Enable or disable the sharpen process from the pipeline
  74928. */
  74929. set: function (enabled) {
  74930. if (this._sharpenEnabled === enabled) {
  74931. return;
  74932. }
  74933. this._sharpenEnabled = enabled;
  74934. this._buildPipeline();
  74935. },
  74936. enumerable: true,
  74937. configurable: true
  74938. });
  74939. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  74940. /**
  74941. * Specifies the size of the bloom blur kernel, relative to the final output size
  74942. */
  74943. get: function () {
  74944. return this._bloomKernel;
  74945. },
  74946. set: function (value) {
  74947. this._bloomKernel = value;
  74948. this.bloom.kernel = value / this._hardwareScaleLevel;
  74949. },
  74950. enumerable: true,
  74951. configurable: true
  74952. });
  74953. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  74954. get: function () {
  74955. return this._bloomWeight;
  74956. },
  74957. /**
  74958. * The strength of the bloom.
  74959. */
  74960. set: function (value) {
  74961. if (this._bloomWeight === value) {
  74962. return;
  74963. }
  74964. this.bloom.weight = value;
  74965. this._bloomWeight = value;
  74966. },
  74967. enumerable: true,
  74968. configurable: true
  74969. });
  74970. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  74971. get: function () {
  74972. return this._bloomThreshold;
  74973. },
  74974. /**
  74975. * The strength of the bloom.
  74976. */
  74977. set: function (value) {
  74978. if (this._bloomThreshold === value) {
  74979. return;
  74980. }
  74981. this.bloom.threshold = value;
  74982. this._bloomThreshold = value;
  74983. },
  74984. enumerable: true,
  74985. configurable: true
  74986. });
  74987. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  74988. get: function () {
  74989. return this._bloomScale;
  74990. },
  74991. /**
  74992. * The scale of the bloom, lower value will provide better performance.
  74993. */
  74994. set: function (value) {
  74995. if (this._bloomScale === value) {
  74996. return;
  74997. }
  74998. this._bloomScale = value;
  74999. // recreate bloom and dispose old as this setting is not dynamic
  75000. this._rebuildBloom();
  75001. this._buildPipeline();
  75002. },
  75003. enumerable: true,
  75004. configurable: true
  75005. });
  75006. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75007. get: function () {
  75008. return this._bloomEnabled;
  75009. },
  75010. /**
  75011. * Enable or disable the bloom from the pipeline
  75012. */
  75013. set: function (enabled) {
  75014. if (this._bloomEnabled === enabled) {
  75015. return;
  75016. }
  75017. this._bloomEnabled = enabled;
  75018. this._buildPipeline();
  75019. },
  75020. enumerable: true,
  75021. configurable: true
  75022. });
  75023. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75024. // recreate bloom and dispose old as this setting is not dynamic
  75025. var oldBloom = this.bloom;
  75026. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75027. this.bloom.threshold = oldBloom.threshold;
  75028. for (var i = 0; i < this._cameras.length; i++) {
  75029. oldBloom.disposeEffects(this._cameras[i]);
  75030. }
  75031. };
  75032. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75033. /**
  75034. * If the depth of field is enabled.
  75035. */
  75036. get: function () {
  75037. return this._depthOfFieldEnabled;
  75038. },
  75039. set: function (enabled) {
  75040. if (this._depthOfFieldEnabled === enabled) {
  75041. return;
  75042. }
  75043. this._depthOfFieldEnabled = enabled;
  75044. this._buildPipeline();
  75045. },
  75046. enumerable: true,
  75047. configurable: true
  75048. });
  75049. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75050. /**
  75051. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75052. */
  75053. get: function () {
  75054. return this._depthOfFieldBlurLevel;
  75055. },
  75056. set: function (value) {
  75057. if (this._depthOfFieldBlurLevel === value) {
  75058. return;
  75059. }
  75060. this._depthOfFieldBlurLevel = value;
  75061. // recreate dof and dispose old as this setting is not dynamic
  75062. var oldDof = this.depthOfField;
  75063. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75064. this.depthOfField.focalLength = oldDof.focalLength;
  75065. this.depthOfField.focusDistance = oldDof.focusDistance;
  75066. this.depthOfField.fStop = oldDof.fStop;
  75067. this.depthOfField.lensSize = oldDof.lensSize;
  75068. for (var i = 0; i < this._cameras.length; i++) {
  75069. oldDof.disposeEffects(this._cameras[i]);
  75070. }
  75071. this._buildPipeline();
  75072. },
  75073. enumerable: true,
  75074. configurable: true
  75075. });
  75076. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75077. get: function () {
  75078. return this._fxaaEnabled;
  75079. },
  75080. /**
  75081. * If the anti aliasing is enabled.
  75082. */
  75083. set: function (enabled) {
  75084. if (this._fxaaEnabled === enabled) {
  75085. return;
  75086. }
  75087. this._fxaaEnabled = enabled;
  75088. this._buildPipeline();
  75089. },
  75090. enumerable: true,
  75091. configurable: true
  75092. });
  75093. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75094. get: function () {
  75095. return this._samples;
  75096. },
  75097. /**
  75098. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75099. */
  75100. set: function (sampleCount) {
  75101. if (this._samples === sampleCount) {
  75102. return;
  75103. }
  75104. this._samples = sampleCount;
  75105. this._buildPipeline();
  75106. },
  75107. enumerable: true,
  75108. configurable: true
  75109. });
  75110. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75111. get: function () {
  75112. return this._imageProcessingEnabled;
  75113. },
  75114. /**
  75115. * If image processing is enabled.
  75116. */
  75117. set: function (enabled) {
  75118. if (this._imageProcessingEnabled === enabled) {
  75119. return;
  75120. }
  75121. this._imageProcessingEnabled = enabled;
  75122. this._buildPipeline();
  75123. },
  75124. enumerable: true,
  75125. configurable: true
  75126. });
  75127. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75128. get: function () {
  75129. return this._chromaticAberrationEnabled;
  75130. },
  75131. /**
  75132. * Enable or disable the chromaticAberration process from the pipeline
  75133. */
  75134. set: function (enabled) {
  75135. if (this._chromaticAberrationEnabled === enabled) {
  75136. return;
  75137. }
  75138. this._chromaticAberrationEnabled = enabled;
  75139. this._buildPipeline();
  75140. },
  75141. enumerable: true,
  75142. configurable: true
  75143. });
  75144. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75145. get: function () {
  75146. return this._grainEnabled;
  75147. },
  75148. /**
  75149. * Enable or disable the grain process from the pipeline
  75150. */
  75151. set: function (enabled) {
  75152. if (this._grainEnabled === enabled) {
  75153. return;
  75154. }
  75155. this._grainEnabled = enabled;
  75156. this._buildPipeline();
  75157. },
  75158. enumerable: true,
  75159. configurable: true
  75160. });
  75161. /**
  75162. * Force the compilation of the entire pipeline.
  75163. */
  75164. DefaultRenderingPipeline.prototype.prepare = function () {
  75165. var previousState = this._buildAllowed;
  75166. this._buildAllowed = true;
  75167. this._buildPipeline();
  75168. this._buildAllowed = previousState;
  75169. };
  75170. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75171. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75172. if (this._hasCleared) {
  75173. postProcess.autoClear = false;
  75174. }
  75175. else {
  75176. postProcess.autoClear = true;
  75177. this._scene.autoClear = false;
  75178. this._hasCleared = true;
  75179. }
  75180. if (!skipTextureSharing) {
  75181. if (this._prevPrevPostProcess) {
  75182. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75183. }
  75184. else {
  75185. postProcess.useOwnOutput();
  75186. }
  75187. if (this._prevPostProcess) {
  75188. this._prevPrevPostProcess = this._prevPostProcess;
  75189. }
  75190. this._prevPostProcess = postProcess;
  75191. }
  75192. };
  75193. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75194. var _this = this;
  75195. if (!this._buildAllowed) {
  75196. return;
  75197. }
  75198. this._scene.autoClear = true;
  75199. var engine = this._scene.getEngine();
  75200. this._disposePostProcesses();
  75201. if (this._cameras !== null) {
  75202. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75203. // get back cameras to be used to reattach pipeline
  75204. this._cameras = this._originalCameras.slice();
  75205. }
  75206. this._reset();
  75207. this._prevPostProcess = null;
  75208. this._prevPrevPostProcess = null;
  75209. this._hasCleared = false;
  75210. if (this.depthOfFieldEnabled) {
  75211. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75212. this.depthOfField.depthTexture = depthTexture;
  75213. if (!this.depthOfField._isReady()) {
  75214. this.depthOfField._updateEffects();
  75215. }
  75216. this.addEffect(this.depthOfField);
  75217. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75218. }
  75219. if (this.bloomEnabled) {
  75220. if (!this.bloom._isReady()) {
  75221. this.bloom._updateEffects();
  75222. }
  75223. this.addEffect(this.bloom);
  75224. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75225. }
  75226. if (this._imageProcessingEnabled) {
  75227. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75228. if (this._hdr) {
  75229. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75230. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75231. }
  75232. else {
  75233. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75234. }
  75235. }
  75236. if (this.sharpenEnabled) {
  75237. if (!this.sharpen.isReady()) {
  75238. this.sharpen.updateEffect();
  75239. }
  75240. this.addEffect(this._sharpenEffect);
  75241. this._setAutoClearAndTextureSharing(this.sharpen);
  75242. }
  75243. if (this.grainEnabled) {
  75244. if (!this.grain.isReady()) {
  75245. this.grain.updateEffect();
  75246. }
  75247. this.addEffect(this._grainEffect);
  75248. this._setAutoClearAndTextureSharing(this.grain);
  75249. }
  75250. if (this.chromaticAberrationEnabled) {
  75251. if (!this.chromaticAberration.isReady()) {
  75252. this.chromaticAberration.updateEffect();
  75253. }
  75254. this.addEffect(this._chromaticAberrationEffect);
  75255. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75256. }
  75257. if (this.fxaaEnabled) {
  75258. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75259. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75260. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75261. }
  75262. if (this._cameras !== null) {
  75263. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75264. }
  75265. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75266. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75267. }
  75268. };
  75269. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75270. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75271. for (var i = 0; i < this._cameras.length; i++) {
  75272. var camera = this._cameras[i];
  75273. if (this.imageProcessing) {
  75274. this.imageProcessing.dispose(camera);
  75275. }
  75276. if (this.fxaa) {
  75277. this.fxaa.dispose(camera);
  75278. }
  75279. // These are created in the constructor and should not be disposed on every pipeline change
  75280. if (disposeNonRecreated) {
  75281. if (this.sharpen) {
  75282. this.sharpen.dispose(camera);
  75283. }
  75284. if (this.depthOfField) {
  75285. this.depthOfField.disposeEffects(camera);
  75286. }
  75287. if (this.bloom) {
  75288. this.bloom.disposeEffects(camera);
  75289. }
  75290. if (this.chromaticAberration) {
  75291. this.chromaticAberration.dispose(camera);
  75292. }
  75293. if (this.grain) {
  75294. this.grain.dispose(camera);
  75295. }
  75296. }
  75297. }
  75298. this.imageProcessing = null;
  75299. this.fxaa = null;
  75300. if (disposeNonRecreated) {
  75301. this.sharpen = null;
  75302. this._sharpenEffect = null;
  75303. this.depthOfField = null;
  75304. this.bloom = null;
  75305. this.chromaticAberration = null;
  75306. this._chromaticAberrationEffect = null;
  75307. this.grain = null;
  75308. this._grainEffect = null;
  75309. }
  75310. };
  75311. /**
  75312. * Dispose of the pipeline and stop all post processes
  75313. */
  75314. DefaultRenderingPipeline.prototype.dispose = function () {
  75315. this._disposePostProcesses(true);
  75316. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75317. this._scene.autoClear = true;
  75318. if (this._resizeObserver) {
  75319. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75320. this._resizeObserver = null;
  75321. }
  75322. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75323. _super.prototype.dispose.call(this);
  75324. };
  75325. /**
  75326. * Serialize the rendering pipeline (Used when exporting)
  75327. * @returns the serialized object
  75328. */
  75329. DefaultRenderingPipeline.prototype.serialize = function () {
  75330. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75331. serializationObject.customType = "DefaultRenderingPipeline";
  75332. return serializationObject;
  75333. };
  75334. /**
  75335. * Parse the serialized pipeline
  75336. * @param source Source pipeline.
  75337. * @param scene The scene to load the pipeline to.
  75338. * @param rootUrl The URL of the serialized pipeline.
  75339. * @returns An instantiated pipeline from the serialized object.
  75340. */
  75341. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75342. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75343. };
  75344. __decorate([
  75345. BABYLON.serialize()
  75346. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75347. __decorate([
  75348. BABYLON.serialize()
  75349. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75350. __decorate([
  75351. BABYLON.serialize()
  75352. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75353. __decorate([
  75354. BABYLON.serialize()
  75355. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75356. __decorate([
  75357. BABYLON.serialize()
  75358. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75359. __decorate([
  75360. BABYLON.serialize()
  75361. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75362. __decorate([
  75363. BABYLON.serialize()
  75364. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75365. __decorate([
  75366. BABYLON.serialize()
  75367. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75368. __decorate([
  75369. BABYLON.serialize()
  75370. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75371. __decorate([
  75372. BABYLON.serialize()
  75373. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75374. __decorate([
  75375. BABYLON.serialize()
  75376. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75377. __decorate([
  75378. BABYLON.serialize()
  75379. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75380. __decorate([
  75381. BABYLON.serialize()
  75382. ], DefaultRenderingPipeline.prototype, "samples", null);
  75383. __decorate([
  75384. BABYLON.serialize()
  75385. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75386. __decorate([
  75387. BABYLON.serialize()
  75388. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75389. __decorate([
  75390. BABYLON.serialize()
  75391. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75392. return DefaultRenderingPipeline;
  75393. }(BABYLON.PostProcessRenderPipeline));
  75394. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75395. })(BABYLON || (BABYLON = {}));
  75396. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75397. var BABYLON;
  75398. (function (BABYLON) {
  75399. /**
  75400. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75401. */
  75402. var GeometryBufferRenderer = /** @class */ (function () {
  75403. /**
  75404. * Creates a new G Buffer for the scene
  75405. * @param scene The scene the buffer belongs to
  75406. * @param ratio How big is the buffer related to the main canvas.
  75407. */
  75408. function GeometryBufferRenderer(scene, ratio) {
  75409. if (ratio === void 0) { ratio = 1; }
  75410. this._enablePosition = false;
  75411. this._scene = scene;
  75412. this._ratio = ratio;
  75413. // Render target
  75414. this._createRenderTargets();
  75415. }
  75416. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75417. /**
  75418. * Set the render list (meshes to be rendered) used in the G buffer.
  75419. */
  75420. set: function (meshes) {
  75421. this._multiRenderTarget.renderList = meshes;
  75422. },
  75423. enumerable: true,
  75424. configurable: true
  75425. });
  75426. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75427. /**
  75428. * Gets wether or not G buffer are supported by the running hardware.
  75429. * This requires draw buffer supports
  75430. */
  75431. get: function () {
  75432. return this._multiRenderTarget.isSupported;
  75433. },
  75434. enumerable: true,
  75435. configurable: true
  75436. });
  75437. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75438. /**
  75439. * Gets wether or not position are enabled for the G buffer.
  75440. */
  75441. get: function () {
  75442. return this._enablePosition;
  75443. },
  75444. /**
  75445. * Sets wether or not position are enabled for the G buffer.
  75446. */
  75447. set: function (enable) {
  75448. this._enablePosition = enable;
  75449. this.dispose();
  75450. this._createRenderTargets();
  75451. },
  75452. enumerable: true,
  75453. configurable: true
  75454. });
  75455. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75456. /**
  75457. * Gets the scene associated with the buffer.
  75458. */
  75459. get: function () {
  75460. return this._scene;
  75461. },
  75462. enumerable: true,
  75463. configurable: true
  75464. });
  75465. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75466. /**
  75467. * Gets the ratio used by the buffer during its creation.
  75468. * How big is the buffer related to the main canvas.
  75469. */
  75470. get: function () {
  75471. return this._ratio;
  75472. },
  75473. enumerable: true,
  75474. configurable: true
  75475. });
  75476. /**
  75477. * Checks wether everything is ready to render a submesh to the G buffer.
  75478. * @param subMesh the submesh to check readiness for
  75479. * @param useInstances is the mesh drawn using instance or not
  75480. * @returns true if ready otherwise false
  75481. */
  75482. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75483. var material = subMesh.getMaterial();
  75484. if (material && material.disableDepthWrite) {
  75485. return false;
  75486. }
  75487. var defines = [];
  75488. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75489. var mesh = subMesh.getMesh();
  75490. // Alpha test
  75491. if (material && material.needAlphaTesting()) {
  75492. defines.push("#define ALPHATEST");
  75493. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75494. attribs.push(BABYLON.VertexBuffer.UVKind);
  75495. defines.push("#define UV1");
  75496. }
  75497. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75498. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75499. defines.push("#define UV2");
  75500. }
  75501. }
  75502. // Buffers
  75503. if (this._enablePosition) {
  75504. defines.push("#define POSITION");
  75505. }
  75506. // Bones
  75507. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75508. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75509. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75510. if (mesh.numBoneInfluencers > 4) {
  75511. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75512. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75513. }
  75514. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75515. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75516. }
  75517. else {
  75518. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75519. }
  75520. // Instances
  75521. if (useInstances) {
  75522. defines.push("#define INSTANCES");
  75523. attribs.push("world0");
  75524. attribs.push("world1");
  75525. attribs.push("world2");
  75526. attribs.push("world3");
  75527. }
  75528. // Get correct effect
  75529. var join = defines.join("\n");
  75530. if (this._cachedDefines !== join) {
  75531. this._cachedDefines = join;
  75532. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75533. }
  75534. return this._effect.isReady();
  75535. };
  75536. /**
  75537. * Gets the current underlying G Buffer.
  75538. * @returns the buffer
  75539. */
  75540. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75541. return this._multiRenderTarget;
  75542. };
  75543. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75544. /**
  75545. * Gets the number of samples used to render the buffer (anti aliasing).
  75546. */
  75547. get: function () {
  75548. return this._multiRenderTarget.samples;
  75549. },
  75550. /**
  75551. * Sets the number of samples used to render the buffer (anti aliasing).
  75552. */
  75553. set: function (value) {
  75554. this._multiRenderTarget.samples = value;
  75555. },
  75556. enumerable: true,
  75557. configurable: true
  75558. });
  75559. /**
  75560. * Disposes the renderer and frees up associated resources.
  75561. */
  75562. GeometryBufferRenderer.prototype.dispose = function () {
  75563. this.getGBuffer().dispose();
  75564. };
  75565. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75566. var _this = this;
  75567. var engine = this._scene.getEngine();
  75568. var count = this._enablePosition ? 3 : 2;
  75569. 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 });
  75570. if (!this.isSupported) {
  75571. return;
  75572. }
  75573. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75574. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75575. this._multiRenderTarget.refreshRate = 1;
  75576. this._multiRenderTarget.renderParticles = false;
  75577. this._multiRenderTarget.renderList = null;
  75578. // set default depth value to 1.0 (far away)
  75579. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75580. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75581. });
  75582. // Custom render function
  75583. var renderSubMesh = function (subMesh) {
  75584. var mesh = subMesh.getRenderingMesh();
  75585. var scene = _this._scene;
  75586. var engine = scene.getEngine();
  75587. var material = subMesh.getMaterial();
  75588. if (!material) {
  75589. return;
  75590. }
  75591. // Culling
  75592. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75593. // Managing instances
  75594. var batch = mesh._getInstancesRenderList(subMesh._id);
  75595. if (batch.mustReturn) {
  75596. return;
  75597. }
  75598. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75599. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75600. engine.enableEffect(_this._effect);
  75601. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75602. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75603. _this._effect.setMatrix("view", scene.getViewMatrix());
  75604. // Alpha test
  75605. if (material && material.needAlphaTesting()) {
  75606. var alphaTexture = material.getAlphaTestTexture();
  75607. if (alphaTexture) {
  75608. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75609. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75610. }
  75611. }
  75612. // Bones
  75613. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75614. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75615. }
  75616. // Draw
  75617. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75618. }
  75619. };
  75620. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75621. var index;
  75622. if (depthOnlySubMeshes.length) {
  75623. engine.setColorWrite(false);
  75624. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75625. renderSubMesh(depthOnlySubMeshes.data[index]);
  75626. }
  75627. engine.setColorWrite(true);
  75628. }
  75629. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75630. renderSubMesh(opaqueSubMeshes.data[index]);
  75631. }
  75632. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75633. renderSubMesh(alphaTestSubMeshes.data[index]);
  75634. }
  75635. };
  75636. };
  75637. return GeometryBufferRenderer;
  75638. }());
  75639. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  75640. })(BABYLON || (BABYLON = {}));
  75641. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  75642. var BABYLON;
  75643. (function (BABYLON) {
  75644. var RefractionPostProcess = /** @class */ (function (_super) {
  75645. __extends(RefractionPostProcess, _super);
  75646. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  75647. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  75648. _this.color = color;
  75649. _this.depth = depth;
  75650. _this.colorLevel = colorLevel;
  75651. _this._ownRefractionTexture = true;
  75652. _this.onActivateObservable.add(function (cam) {
  75653. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  75654. });
  75655. _this.onApplyObservable.add(function (effect) {
  75656. effect.setColor3("baseColor", _this.color);
  75657. effect.setFloat("depth", _this.depth);
  75658. effect.setFloat("colorLevel", _this.colorLevel);
  75659. effect.setTexture("refractionSampler", _this._refTexture);
  75660. });
  75661. return _this;
  75662. }
  75663. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  75664. /**
  75665. * Gets or sets the refraction texture
  75666. * Please note that you are responsible for disposing the texture if you set it manually
  75667. */
  75668. get: function () {
  75669. return this._refTexture;
  75670. },
  75671. set: function (value) {
  75672. if (this._refTexture && this._ownRefractionTexture) {
  75673. this._refTexture.dispose();
  75674. }
  75675. this._refTexture = value;
  75676. this._ownRefractionTexture = false;
  75677. },
  75678. enumerable: true,
  75679. configurable: true
  75680. });
  75681. // Methods
  75682. RefractionPostProcess.prototype.dispose = function (camera) {
  75683. if (this._refTexture && this._ownRefractionTexture) {
  75684. this._refTexture.dispose();
  75685. this._refTexture = null;
  75686. }
  75687. _super.prototype.dispose.call(this, camera);
  75688. };
  75689. return RefractionPostProcess;
  75690. }(BABYLON.PostProcess));
  75691. BABYLON.RefractionPostProcess = RefractionPostProcess;
  75692. })(BABYLON || (BABYLON = {}));
  75693. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  75694. var BABYLON;
  75695. (function (BABYLON) {
  75696. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  75697. __extends(BlackAndWhitePostProcess, _super);
  75698. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  75699. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  75700. _this.degree = 1;
  75701. _this.onApplyObservable.add(function (effect) {
  75702. effect.setFloat("degree", _this.degree);
  75703. });
  75704. return _this;
  75705. }
  75706. return BlackAndWhitePostProcess;
  75707. }(BABYLON.PostProcess));
  75708. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  75709. })(BABYLON || (BABYLON = {}));
  75710. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  75711. var BABYLON;
  75712. (function (BABYLON) {
  75713. /**
  75714. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  75715. * input texture to perform effects such as edge detection or sharpening
  75716. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75717. */
  75718. var ConvolutionPostProcess = /** @class */ (function (_super) {
  75719. __extends(ConvolutionPostProcess, _super);
  75720. /**
  75721. * Creates a new instance ConvolutionPostProcess
  75722. * @param name The name of the effect.
  75723. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  75724. * @param options The required width/height ratio to downsize to before computing the render pass.
  75725. * @param camera The camera to apply the render pass to.
  75726. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75727. * @param engine The engine which the post process will be applied. (default: current engine)
  75728. * @param reusable If the post process can be reused on the same frame. (default: false)
  75729. * @param textureType Type of textures used when performing the post process. (default: 0)
  75730. */
  75731. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  75732. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75733. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75734. _this.kernel = kernel;
  75735. _this.onApply = function (effect) {
  75736. effect.setFloat2("screenSize", _this.width, _this.height);
  75737. effect.setArray("kernel", _this.kernel);
  75738. };
  75739. return _this;
  75740. }
  75741. // Statics
  75742. /**
  75743. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75744. */
  75745. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  75746. /**
  75747. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75748. */
  75749. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  75750. /**
  75751. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75752. */
  75753. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  75754. /**
  75755. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75756. */
  75757. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  75758. /**
  75759. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75760. */
  75761. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  75762. /**
  75763. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75764. */
  75765. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  75766. return ConvolutionPostProcess;
  75767. }(BABYLON.PostProcess));
  75768. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  75769. })(BABYLON || (BABYLON = {}));
  75770. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  75771. var BABYLON;
  75772. (function (BABYLON) {
  75773. var FilterPostProcess = /** @class */ (function (_super) {
  75774. __extends(FilterPostProcess, _super);
  75775. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  75776. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  75777. _this.kernelMatrix = kernelMatrix;
  75778. _this.onApply = function (effect) {
  75779. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  75780. };
  75781. return _this;
  75782. }
  75783. return FilterPostProcess;
  75784. }(BABYLON.PostProcess));
  75785. BABYLON.FilterPostProcess = FilterPostProcess;
  75786. })(BABYLON || (BABYLON = {}));
  75787. //# sourceMappingURL=babylon.filterPostProcess.js.map
  75788. var BABYLON;
  75789. (function (BABYLON) {
  75790. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  75791. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  75792. __extends(VolumetricLightScatteringPostProcess, _super);
  75793. /**
  75794. * @constructor
  75795. * @param {string} name - The post-process name
  75796. * @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)
  75797. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  75798. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  75799. * @param {number} samples - The post-process quality, default 100
  75800. * @param {number} samplingMode - The post-process filtering mode
  75801. * @param {BABYLON.Engine} engine - The babylon engine
  75802. * @param {boolean} reusable - If the post-process is reusable
  75803. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  75804. */
  75805. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  75806. if (samples === void 0) { samples = 100; }
  75807. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75808. 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;
  75809. _this._screenCoordinates = BABYLON.Vector2.Zero();
  75810. /**
  75811. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  75812. */
  75813. _this.customMeshPosition = BABYLON.Vector3.Zero();
  75814. /**
  75815. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  75816. */
  75817. _this.useCustomMeshPosition = false;
  75818. /**
  75819. * If the post-process should inverse the light scattering direction
  75820. */
  75821. _this.invert = true;
  75822. /**
  75823. * Array containing the excluded meshes not rendered in the internal pass
  75824. */
  75825. _this.excludedMeshes = new Array();
  75826. /**
  75827. * Controls the overall intensity of the post-process
  75828. */
  75829. _this.exposure = 0.3;
  75830. /**
  75831. * Dissipates each sample's contribution in range [0, 1]
  75832. */
  75833. _this.decay = 0.96815;
  75834. /**
  75835. * Controls the overall intensity of each sample
  75836. */
  75837. _this.weight = 0.58767;
  75838. /**
  75839. * Controls the density of each sample
  75840. */
  75841. _this.density = 0.926;
  75842. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  75843. engine = scene.getEngine();
  75844. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  75845. // Configure mesh
  75846. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  75847. // Configure
  75848. _this._createPass(scene, ratio.passRatio || ratio);
  75849. _this.onActivate = function (camera) {
  75850. if (!_this.isSupported) {
  75851. _this.dispose(camera);
  75852. }
  75853. _this.onActivate = null;
  75854. };
  75855. _this.onApplyObservable.add(function (effect) {
  75856. _this._updateMeshScreenCoordinates(scene);
  75857. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  75858. effect.setFloat("exposure", _this.exposure);
  75859. effect.setFloat("decay", _this.decay);
  75860. effect.setFloat("weight", _this.weight);
  75861. effect.setFloat("density", _this.density);
  75862. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  75863. });
  75864. return _this;
  75865. }
  75866. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  75867. get: function () {
  75868. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75869. return false;
  75870. },
  75871. set: function (useDiffuseColor) {
  75872. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75873. },
  75874. enumerable: true,
  75875. configurable: true
  75876. });
  75877. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  75878. return "VolumetricLightScatteringPostProcess";
  75879. };
  75880. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  75881. var mesh = subMesh.getMesh();
  75882. // Render this.mesh as default
  75883. if (mesh === this.mesh && mesh.material) {
  75884. return mesh.material.isReady(mesh);
  75885. }
  75886. var defines = [];
  75887. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75888. var material = subMesh.getMaterial();
  75889. // Alpha test
  75890. if (material) {
  75891. if (material.needAlphaTesting()) {
  75892. defines.push("#define ALPHATEST");
  75893. }
  75894. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75895. attribs.push(BABYLON.VertexBuffer.UVKind);
  75896. defines.push("#define UV1");
  75897. }
  75898. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75899. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75900. defines.push("#define UV2");
  75901. }
  75902. }
  75903. // Bones
  75904. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75905. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75906. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75907. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75908. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75909. }
  75910. else {
  75911. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75912. }
  75913. // Instances
  75914. if (useInstances) {
  75915. defines.push("#define INSTANCES");
  75916. attribs.push("world0");
  75917. attribs.push("world1");
  75918. attribs.push("world2");
  75919. attribs.push("world3");
  75920. }
  75921. // Get correct effect
  75922. var join = defines.join("\n");
  75923. if (this._cachedDefines !== join) {
  75924. this._cachedDefines = join;
  75925. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  75926. }
  75927. return this._volumetricLightScatteringPass.isReady();
  75928. };
  75929. /**
  75930. * Sets the new light position for light scattering effect
  75931. * @param {BABYLON.Vector3} The new custom light position
  75932. */
  75933. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  75934. this.customMeshPosition = position;
  75935. };
  75936. /**
  75937. * Returns the light position for light scattering effect
  75938. * @return {BABYLON.Vector3} The custom light position
  75939. */
  75940. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  75941. return this.customMeshPosition;
  75942. };
  75943. /**
  75944. * Disposes the internal assets and detaches the post-process from the camera
  75945. */
  75946. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  75947. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  75948. if (rttIndex !== -1) {
  75949. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  75950. }
  75951. this._volumetricLightScatteringRTT.dispose();
  75952. _super.prototype.dispose.call(this, camera);
  75953. };
  75954. /**
  75955. * Returns the render target texture used by the post-process
  75956. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  75957. */
  75958. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  75959. return this._volumetricLightScatteringRTT;
  75960. };
  75961. // Private methods
  75962. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  75963. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  75964. return true;
  75965. }
  75966. return false;
  75967. };
  75968. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  75969. var _this = this;
  75970. var engine = scene.getEngine();
  75971. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75972. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75973. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75974. this._volumetricLightScatteringRTT.renderList = null;
  75975. this._volumetricLightScatteringRTT.renderParticles = false;
  75976. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  75977. var camera = this.getCamera();
  75978. if (camera) {
  75979. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75980. }
  75981. else {
  75982. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75983. }
  75984. // Custom render function for submeshes
  75985. var renderSubMesh = function (subMesh) {
  75986. var mesh = subMesh.getRenderingMesh();
  75987. if (_this._meshExcluded(mesh)) {
  75988. return;
  75989. }
  75990. var material = subMesh.getMaterial();
  75991. if (!material) {
  75992. return;
  75993. }
  75994. var scene = mesh.getScene();
  75995. var engine = scene.getEngine();
  75996. // Culling
  75997. engine.setState(material.backFaceCulling);
  75998. // Managing instances
  75999. var batch = mesh._getInstancesRenderList(subMesh._id);
  76000. if (batch.mustReturn) {
  76001. return;
  76002. }
  76003. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76004. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76005. var effect = _this._volumetricLightScatteringPass;
  76006. if (mesh === _this.mesh) {
  76007. if (subMesh.effect) {
  76008. effect = subMesh.effect;
  76009. }
  76010. else {
  76011. effect = material.getEffect();
  76012. }
  76013. }
  76014. engine.enableEffect(effect);
  76015. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76016. if (mesh === _this.mesh) {
  76017. material.bind(mesh.getWorldMatrix(), mesh);
  76018. }
  76019. else {
  76020. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76021. // Alpha test
  76022. if (material && material.needAlphaTesting()) {
  76023. var alphaTexture = material.getAlphaTestTexture();
  76024. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76025. if (alphaTexture) {
  76026. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76027. }
  76028. }
  76029. // Bones
  76030. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76031. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76032. }
  76033. }
  76034. // Draw
  76035. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76036. }
  76037. };
  76038. // Render target texture callbacks
  76039. var savedSceneClearColor;
  76040. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76041. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76042. savedSceneClearColor = scene.clearColor;
  76043. scene.clearColor = sceneClearColor;
  76044. });
  76045. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76046. scene.clearColor = savedSceneClearColor;
  76047. });
  76048. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76049. var engine = scene.getEngine();
  76050. var index;
  76051. if (depthOnlySubMeshes.length) {
  76052. engine.setColorWrite(false);
  76053. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76054. renderSubMesh(depthOnlySubMeshes.data[index]);
  76055. }
  76056. engine.setColorWrite(true);
  76057. }
  76058. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76059. renderSubMesh(opaqueSubMeshes.data[index]);
  76060. }
  76061. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76062. renderSubMesh(alphaTestSubMeshes.data[index]);
  76063. }
  76064. if (transparentSubMeshes.length) {
  76065. // Sort sub meshes
  76066. for (index = 0; index < transparentSubMeshes.length; index++) {
  76067. var submesh = transparentSubMeshes.data[index];
  76068. var boundingInfo = submesh.getBoundingInfo();
  76069. if (boundingInfo && scene.activeCamera) {
  76070. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76071. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76072. }
  76073. }
  76074. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76075. sortedArray.sort(function (a, b) {
  76076. // Alpha index first
  76077. if (a._alphaIndex > b._alphaIndex) {
  76078. return 1;
  76079. }
  76080. if (a._alphaIndex < b._alphaIndex) {
  76081. return -1;
  76082. }
  76083. // Then distance to camera
  76084. if (a._distanceToCamera < b._distanceToCamera) {
  76085. return 1;
  76086. }
  76087. if (a._distanceToCamera > b._distanceToCamera) {
  76088. return -1;
  76089. }
  76090. return 0;
  76091. });
  76092. // Render sub meshes
  76093. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76094. for (index = 0; index < sortedArray.length; index++) {
  76095. renderSubMesh(sortedArray[index]);
  76096. }
  76097. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76098. }
  76099. };
  76100. };
  76101. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76102. var transform = scene.getTransformMatrix();
  76103. var meshPosition;
  76104. if (this.useCustomMeshPosition) {
  76105. meshPosition = this.customMeshPosition;
  76106. }
  76107. else if (this.attachedNode) {
  76108. meshPosition = this.attachedNode.position;
  76109. }
  76110. else {
  76111. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76112. }
  76113. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76114. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76115. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76116. if (this.invert)
  76117. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76118. };
  76119. // Static methods
  76120. /**
  76121. * Creates a default mesh for the Volumeric Light Scattering post-process
  76122. * @param {string} The mesh name
  76123. * @param {BABYLON.Scene} The scene where to create the mesh
  76124. * @return {BABYLON.Mesh} the default mesh
  76125. */
  76126. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76127. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76128. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76129. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76130. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76131. mesh.material = material;
  76132. return mesh;
  76133. };
  76134. __decorate([
  76135. BABYLON.serializeAsVector3()
  76136. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76137. __decorate([
  76138. BABYLON.serialize()
  76139. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76140. __decorate([
  76141. BABYLON.serialize()
  76142. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76143. __decorate([
  76144. BABYLON.serializeAsMeshReference()
  76145. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76146. __decorate([
  76147. BABYLON.serialize()
  76148. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76149. __decorate([
  76150. BABYLON.serialize()
  76151. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76152. __decorate([
  76153. BABYLON.serialize()
  76154. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76155. __decorate([
  76156. BABYLON.serialize()
  76157. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76158. __decorate([
  76159. BABYLON.serialize()
  76160. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76161. return VolumetricLightScatteringPostProcess;
  76162. }(BABYLON.PostProcess));
  76163. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76164. })(BABYLON || (BABYLON = {}));
  76165. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76166. //
  76167. // This post-process allows the modification of rendered colors by using
  76168. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76169. //
  76170. // The object needs to be provided an url to a texture containing the color
  76171. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76172. // Use an image editing software to tweak the LUT to match your needs.
  76173. //
  76174. // For an example of a color LUT, see here:
  76175. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76176. // For explanations on color grading, see here:
  76177. // http://udn.epicgames.com/Three/ColorGrading.html
  76178. //
  76179. var BABYLON;
  76180. (function (BABYLON) {
  76181. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76182. __extends(ColorCorrectionPostProcess, _super);
  76183. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76184. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76185. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76186. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76187. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76188. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76189. _this.onApply = function (effect) {
  76190. effect.setTexture("colorTable", _this._colorTableTexture);
  76191. };
  76192. return _this;
  76193. }
  76194. return ColorCorrectionPostProcess;
  76195. }(BABYLON.PostProcess));
  76196. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76197. })(BABYLON || (BABYLON = {}));
  76198. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76199. var BABYLON;
  76200. (function (BABYLON) {
  76201. /** Defines operator used for tonemapping */
  76202. var TonemappingOperator;
  76203. (function (TonemappingOperator) {
  76204. /** Hable */
  76205. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76206. /** Reinhard */
  76207. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76208. /** HejiDawson */
  76209. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76210. /** Photographic */
  76211. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76212. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76213. ;
  76214. /**
  76215. * Defines a post process to apply tone mapping
  76216. */
  76217. var TonemapPostProcess = /** @class */ (function (_super) {
  76218. __extends(TonemapPostProcess, _super);
  76219. /**
  76220. * Creates a new TonemapPostProcess
  76221. * @param name defines the name of the postprocess
  76222. * @param _operator defines the operator to use
  76223. * @param exposureAdjustment defines the required exposure adjustement
  76224. * @param camera defines the camera to use (can be null)
  76225. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76226. * @param engine defines the hosting engine (can be ignore if camera is set)
  76227. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76228. */
  76229. function TonemapPostProcess(name, _operator,
  76230. /** Defines the required exposure adjustement */
  76231. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76233. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76234. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76235. _this._operator = _operator;
  76236. _this.exposureAdjustment = exposureAdjustment;
  76237. var defines = "#define ";
  76238. if (_this._operator === TonemappingOperator.Hable)
  76239. defines += "HABLE_TONEMAPPING";
  76240. else if (_this._operator === TonemappingOperator.Reinhard)
  76241. defines += "REINHARD_TONEMAPPING";
  76242. else if (_this._operator === TonemappingOperator.HejiDawson)
  76243. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76244. else if (_this._operator === TonemappingOperator.Photographic)
  76245. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76246. //sadly a second call to create the effect.
  76247. _this.updateEffect(defines);
  76248. _this.onApply = function (effect) {
  76249. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76250. };
  76251. return _this;
  76252. }
  76253. return TonemapPostProcess;
  76254. }(BABYLON.PostProcess));
  76255. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76256. })(BABYLON || (BABYLON = {}));
  76257. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76258. var BABYLON;
  76259. (function (BABYLON) {
  76260. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76261. __extends(DisplayPassPostProcess, _super);
  76262. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76263. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76264. }
  76265. return DisplayPassPostProcess;
  76266. }(BABYLON.PostProcess));
  76267. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76268. })(BABYLON || (BABYLON = {}));
  76269. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76270. var BABYLON;
  76271. (function (BABYLON) {
  76272. var HighlightsPostProcess = /** @class */ (function (_super) {
  76273. __extends(HighlightsPostProcess, _super);
  76274. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76275. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76276. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76277. }
  76278. return HighlightsPostProcess;
  76279. }(BABYLON.PostProcess));
  76280. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76281. })(BABYLON || (BABYLON = {}));
  76282. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76283. var BABYLON;
  76284. (function (BABYLON) {
  76285. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76286. __extends(ImageProcessingPostProcess, _super);
  76287. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76288. if (camera === void 0) { camera = null; }
  76289. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76290. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76291. _this._fromLinearSpace = true;
  76292. /**
  76293. * Defines cache preventing GC.
  76294. */
  76295. _this._defines = {
  76296. IMAGEPROCESSING: false,
  76297. VIGNETTE: false,
  76298. VIGNETTEBLENDMODEMULTIPLY: false,
  76299. VIGNETTEBLENDMODEOPAQUE: false,
  76300. TONEMAPPING: false,
  76301. CONTRAST: false,
  76302. COLORCURVES: false,
  76303. COLORGRADING: false,
  76304. COLORGRADING3D: false,
  76305. FROMLINEARSPACE: false,
  76306. SAMPLER3DGREENDEPTH: false,
  76307. SAMPLER3DBGRMAP: false,
  76308. IMAGEPROCESSINGPOSTPROCESS: false,
  76309. EXPOSURE: false,
  76310. };
  76311. // Setup the configuration as forced by the constructor. This would then not force the
  76312. // scene materials output in linear space and let untouched the default forward pass.
  76313. if (imageProcessingConfiguration) {
  76314. imageProcessingConfiguration.applyByPostProcess = true;
  76315. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76316. // This will cause the shader to be compiled
  76317. _this.fromLinearSpace = false;
  76318. }
  76319. // Setup the default processing configuration to the scene.
  76320. else {
  76321. _this._attachImageProcessingConfiguration(null, true);
  76322. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76323. }
  76324. _this.onApply = function (effect) {
  76325. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76326. };
  76327. return _this;
  76328. }
  76329. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76330. /**
  76331. * Gets the image processing configuration used either in this material.
  76332. */
  76333. get: function () {
  76334. return this._imageProcessingConfiguration;
  76335. },
  76336. /**
  76337. * Sets the Default image processing configuration used either in the this material.
  76338. *
  76339. * If sets to null, the scene one is in use.
  76340. */
  76341. set: function (value) {
  76342. this._attachImageProcessingConfiguration(value);
  76343. },
  76344. enumerable: true,
  76345. configurable: true
  76346. });
  76347. /**
  76348. * Attaches a new image processing configuration to the PBR Material.
  76349. * @param configuration
  76350. */
  76351. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76352. var _this = this;
  76353. if (doNotBuild === void 0) { doNotBuild = false; }
  76354. if (configuration === this._imageProcessingConfiguration) {
  76355. return;
  76356. }
  76357. // Detaches observer.
  76358. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76359. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76360. }
  76361. // Pick the scene configuration if needed.
  76362. if (!configuration) {
  76363. var scene = null;
  76364. var engine = this.getEngine();
  76365. var camera = this.getCamera();
  76366. if (camera) {
  76367. scene = camera.getScene();
  76368. }
  76369. else if (engine && engine.scenes) {
  76370. var scenes = engine.scenes;
  76371. scene = scenes[scenes.length - 1];
  76372. }
  76373. else {
  76374. scene = BABYLON.Engine.LastCreatedScene;
  76375. }
  76376. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76377. }
  76378. else {
  76379. this._imageProcessingConfiguration = configuration;
  76380. }
  76381. // Attaches observer.
  76382. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76383. _this._updateParameters();
  76384. });
  76385. // Ensure the effect will be rebuilt.
  76386. if (!doNotBuild) {
  76387. this._updateParameters();
  76388. }
  76389. };
  76390. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76391. /**
  76392. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76393. */
  76394. get: function () {
  76395. return this.imageProcessingConfiguration.colorCurves;
  76396. },
  76397. /**
  76398. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76399. */
  76400. set: function (value) {
  76401. this.imageProcessingConfiguration.colorCurves = value;
  76402. },
  76403. enumerable: true,
  76404. configurable: true
  76405. });
  76406. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76407. /**
  76408. * Gets wether the color curves effect is enabled.
  76409. */
  76410. get: function () {
  76411. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76412. },
  76413. /**
  76414. * Sets wether the color curves effect is enabled.
  76415. */
  76416. set: function (value) {
  76417. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76418. },
  76419. enumerable: true,
  76420. configurable: true
  76421. });
  76422. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76423. /**
  76424. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76425. */
  76426. get: function () {
  76427. return this.imageProcessingConfiguration.colorGradingTexture;
  76428. },
  76429. /**
  76430. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76431. */
  76432. set: function (value) {
  76433. this.imageProcessingConfiguration.colorGradingTexture = value;
  76434. },
  76435. enumerable: true,
  76436. configurable: true
  76437. });
  76438. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76439. /**
  76440. * Gets wether the color grading effect is enabled.
  76441. */
  76442. get: function () {
  76443. return this.imageProcessingConfiguration.colorGradingEnabled;
  76444. },
  76445. /**
  76446. * Gets wether the color grading effect is enabled.
  76447. */
  76448. set: function (value) {
  76449. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76450. },
  76451. enumerable: true,
  76452. configurable: true
  76453. });
  76454. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  76455. /**
  76456. * Gets exposure used in the effect.
  76457. */
  76458. get: function () {
  76459. return this.imageProcessingConfiguration.exposure;
  76460. },
  76461. /**
  76462. * Sets exposure used in the effect.
  76463. */
  76464. set: function (value) {
  76465. this.imageProcessingConfiguration.exposure = value;
  76466. },
  76467. enumerable: true,
  76468. configurable: true
  76469. });
  76470. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  76471. /**
  76472. * Gets wether tonemapping is enabled or not.
  76473. */
  76474. get: function () {
  76475. return this._imageProcessingConfiguration.toneMappingEnabled;
  76476. },
  76477. /**
  76478. * Sets wether tonemapping is enabled or not
  76479. */
  76480. set: function (value) {
  76481. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76482. },
  76483. enumerable: true,
  76484. configurable: true
  76485. });
  76486. ;
  76487. ;
  76488. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  76489. /**
  76490. * Gets contrast used in the effect.
  76491. */
  76492. get: function () {
  76493. return this.imageProcessingConfiguration.contrast;
  76494. },
  76495. /**
  76496. * Sets contrast used in the effect.
  76497. */
  76498. set: function (value) {
  76499. this.imageProcessingConfiguration.contrast = value;
  76500. },
  76501. enumerable: true,
  76502. configurable: true
  76503. });
  76504. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  76505. /**
  76506. * Gets Vignette stretch size.
  76507. */
  76508. get: function () {
  76509. return this.imageProcessingConfiguration.vignetteStretch;
  76510. },
  76511. /**
  76512. * Sets Vignette stretch size.
  76513. */
  76514. set: function (value) {
  76515. this.imageProcessingConfiguration.vignetteStretch = value;
  76516. },
  76517. enumerable: true,
  76518. configurable: true
  76519. });
  76520. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  76521. /**
  76522. * Gets Vignette centre X Offset.
  76523. */
  76524. get: function () {
  76525. return this.imageProcessingConfiguration.vignetteCentreX;
  76526. },
  76527. /**
  76528. * Sets Vignette centre X Offset.
  76529. */
  76530. set: function (value) {
  76531. this.imageProcessingConfiguration.vignetteCentreX = value;
  76532. },
  76533. enumerable: true,
  76534. configurable: true
  76535. });
  76536. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  76537. /**
  76538. * Gets Vignette centre Y Offset.
  76539. */
  76540. get: function () {
  76541. return this.imageProcessingConfiguration.vignetteCentreY;
  76542. },
  76543. /**
  76544. * Sets Vignette centre Y Offset.
  76545. */
  76546. set: function (value) {
  76547. this.imageProcessingConfiguration.vignetteCentreY = value;
  76548. },
  76549. enumerable: true,
  76550. configurable: true
  76551. });
  76552. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  76553. /**
  76554. * Gets Vignette weight or intensity of the vignette effect.
  76555. */
  76556. get: function () {
  76557. return this.imageProcessingConfiguration.vignetteWeight;
  76558. },
  76559. /**
  76560. * Sets Vignette weight or intensity of the vignette effect.
  76561. */
  76562. set: function (value) {
  76563. this.imageProcessingConfiguration.vignetteWeight = value;
  76564. },
  76565. enumerable: true,
  76566. configurable: true
  76567. });
  76568. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  76569. /**
  76570. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76571. * if vignetteEnabled is set to true.
  76572. */
  76573. get: function () {
  76574. return this.imageProcessingConfiguration.vignetteColor;
  76575. },
  76576. /**
  76577. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76578. * if vignetteEnabled is set to true.
  76579. */
  76580. set: function (value) {
  76581. this.imageProcessingConfiguration.vignetteColor = value;
  76582. },
  76583. enumerable: true,
  76584. configurable: true
  76585. });
  76586. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  76587. /**
  76588. * Gets Camera field of view used by the Vignette effect.
  76589. */
  76590. get: function () {
  76591. return this.imageProcessingConfiguration.vignetteCameraFov;
  76592. },
  76593. /**
  76594. * Sets Camera field of view used by the Vignette effect.
  76595. */
  76596. set: function (value) {
  76597. this.imageProcessingConfiguration.vignetteCameraFov = value;
  76598. },
  76599. enumerable: true,
  76600. configurable: true
  76601. });
  76602. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  76603. /**
  76604. * Gets the vignette blend mode allowing different kind of effect.
  76605. */
  76606. get: function () {
  76607. return this.imageProcessingConfiguration.vignetteBlendMode;
  76608. },
  76609. /**
  76610. * Sets the vignette blend mode allowing different kind of effect.
  76611. */
  76612. set: function (value) {
  76613. this.imageProcessingConfiguration.vignetteBlendMode = value;
  76614. },
  76615. enumerable: true,
  76616. configurable: true
  76617. });
  76618. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  76619. /**
  76620. * Gets wether the vignette effect is enabled.
  76621. */
  76622. get: function () {
  76623. return this.imageProcessingConfiguration.vignetteEnabled;
  76624. },
  76625. /**
  76626. * Sets wether the vignette effect is enabled.
  76627. */
  76628. set: function (value) {
  76629. this.imageProcessingConfiguration.vignetteEnabled = value;
  76630. },
  76631. enumerable: true,
  76632. configurable: true
  76633. });
  76634. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  76635. /**
  76636. * Gets wether the input of the processing is in Gamma or Linear Space.
  76637. */
  76638. get: function () {
  76639. return this._fromLinearSpace;
  76640. },
  76641. /**
  76642. * Sets wether the input of the processing is in Gamma or Linear Space.
  76643. */
  76644. set: function (value) {
  76645. if (this._fromLinearSpace === value) {
  76646. return;
  76647. }
  76648. this._fromLinearSpace = value;
  76649. this._updateParameters();
  76650. },
  76651. enumerable: true,
  76652. configurable: true
  76653. });
  76654. ImageProcessingPostProcess.prototype.getClassName = function () {
  76655. return "ImageProcessingPostProcess";
  76656. };
  76657. ImageProcessingPostProcess.prototype._updateParameters = function () {
  76658. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  76659. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  76660. var defines = "";
  76661. for (var define in this._defines) {
  76662. if (this._defines[define]) {
  76663. defines += "#define " + define + ";\r\n";
  76664. }
  76665. }
  76666. var samplers = ["textureSampler"];
  76667. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  76668. var uniforms = ["scale"];
  76669. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  76670. this.updateEffect(defines, uniforms, samplers);
  76671. };
  76672. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  76673. _super.prototype.dispose.call(this, camera);
  76674. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76675. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76676. }
  76677. this.imageProcessingConfiguration.applyByPostProcess = false;
  76678. };
  76679. __decorate([
  76680. BABYLON.serialize()
  76681. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  76682. return ImageProcessingPostProcess;
  76683. }(BABYLON.PostProcess));
  76684. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  76685. })(BABYLON || (BABYLON = {}));
  76686. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  76687. var BABYLON;
  76688. (function (BABYLON) {
  76689. /**
  76690. * Class used to store bone information
  76691. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  76692. */
  76693. var Bone = /** @class */ (function (_super) {
  76694. __extends(Bone, _super);
  76695. /**
  76696. * Create a new bone
  76697. * @param name defines the bone name
  76698. * @param skeleton defines the parent skeleton
  76699. * @param parentBone defines the parent (can be null if the bone is the root)
  76700. * @param localMatrix defines the local matrix
  76701. * @param restPose defines the rest pose matrix
  76702. * @param baseMatrix defines the base matrix
  76703. * @param index defines index of the bone in the hiearchy
  76704. */
  76705. function Bone(
  76706. /**
  76707. * defines the bone name
  76708. */
  76709. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  76710. if (parentBone === void 0) { parentBone = null; }
  76711. if (localMatrix === void 0) { localMatrix = null; }
  76712. if (restPose === void 0) { restPose = null; }
  76713. if (baseMatrix === void 0) { baseMatrix = null; }
  76714. if (index === void 0) { index = null; }
  76715. var _this = _super.call(this, name, skeleton.getScene()) || this;
  76716. _this.name = name;
  76717. /**
  76718. * Gets the list of child bones
  76719. */
  76720. _this.children = new Array();
  76721. /** Gets the animations associated with this bone */
  76722. _this.animations = new Array();
  76723. /**
  76724. * @ignore Internal only
  76725. * Set this value to map this bone to a different index in the transform matrices
  76726. * Set this value to -1 to exclude the bone from the transform matrices
  76727. */
  76728. _this._index = null;
  76729. _this._absoluteTransform = new BABYLON.Matrix();
  76730. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  76731. _this._scalingDeterminant = 1;
  76732. _this._worldTransform = new BABYLON.Matrix();
  76733. _this._needToDecompose = true;
  76734. _this._needToCompose = false;
  76735. _this._skeleton = skeleton;
  76736. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  76737. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  76738. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  76739. _this._index = index;
  76740. skeleton.bones.push(_this);
  76741. _this.setParent(parentBone, false);
  76742. if (baseMatrix || localMatrix) {
  76743. _this._updateDifferenceMatrix();
  76744. }
  76745. return _this;
  76746. }
  76747. Object.defineProperty(Bone.prototype, "_matrix", {
  76748. /** @ignore */
  76749. get: function () {
  76750. this._compose();
  76751. return this._localMatrix;
  76752. },
  76753. /** @ignore */
  76754. set: function (value) {
  76755. this._localMatrix.copyFrom(value);
  76756. this._needToDecompose = true;
  76757. },
  76758. enumerable: true,
  76759. configurable: true
  76760. });
  76761. // Members
  76762. /**
  76763. * Gets the parent skeleton
  76764. * @returns a skeleton
  76765. */
  76766. Bone.prototype.getSkeleton = function () {
  76767. return this._skeleton;
  76768. };
  76769. /**
  76770. * Gets parent bone
  76771. * @returns a bone or null if the bone is the root of the bone hierarchy
  76772. */
  76773. Bone.prototype.getParent = function () {
  76774. return this._parent;
  76775. };
  76776. /**
  76777. * Sets the parent bone
  76778. * @param parent defines the parent (can be null if the bone is the root)
  76779. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76780. */
  76781. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  76782. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76783. if (this._parent === parent) {
  76784. return;
  76785. }
  76786. if (this._parent) {
  76787. var index = this._parent.children.indexOf(this);
  76788. if (index !== -1) {
  76789. this._parent.children.splice(index, 1);
  76790. }
  76791. }
  76792. this._parent = parent;
  76793. if (this._parent) {
  76794. this._parent.children.push(this);
  76795. }
  76796. if (updateDifferenceMatrix) {
  76797. this._updateDifferenceMatrix();
  76798. }
  76799. this.markAsDirty();
  76800. };
  76801. /**
  76802. * Gets the local matrix
  76803. * @returns a matrix
  76804. */
  76805. Bone.prototype.getLocalMatrix = function () {
  76806. this._compose();
  76807. return this._localMatrix;
  76808. };
  76809. /**
  76810. * Gets the base matrix (initial matrix which remains unchanged)
  76811. * @returns a matrix
  76812. */
  76813. Bone.prototype.getBaseMatrix = function () {
  76814. return this._baseMatrix;
  76815. };
  76816. /**
  76817. * Gets the rest pose matrix
  76818. * @returns a matrix
  76819. */
  76820. Bone.prototype.getRestPose = function () {
  76821. return this._restPose;
  76822. };
  76823. /**
  76824. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  76825. */
  76826. Bone.prototype.getWorldMatrix = function () {
  76827. return this._worldTransform;
  76828. };
  76829. /**
  76830. * Sets the local matrix to rest pose matrix
  76831. */
  76832. Bone.prototype.returnToRest = function () {
  76833. this.updateMatrix(this._restPose.clone());
  76834. };
  76835. /**
  76836. * Gets the inverse of the absolute transform matrix.
  76837. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  76838. * @returns a matrix
  76839. */
  76840. Bone.prototype.getInvertedAbsoluteTransform = function () {
  76841. return this._invertedAbsoluteTransform;
  76842. };
  76843. /**
  76844. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  76845. * @returns a matrix
  76846. */
  76847. Bone.prototype.getAbsoluteTransform = function () {
  76848. return this._absoluteTransform;
  76849. };
  76850. Object.defineProperty(Bone.prototype, "position", {
  76851. // Properties (matches AbstractMesh properties)
  76852. /** Gets or sets current position (in local space) */
  76853. get: function () {
  76854. this._decompose();
  76855. return this._localPosition;
  76856. },
  76857. set: function (newPosition) {
  76858. this._decompose();
  76859. this._localPosition.copyFrom(newPosition);
  76860. this._markAsDirtyAndCompose();
  76861. },
  76862. enumerable: true,
  76863. configurable: true
  76864. });
  76865. Object.defineProperty(Bone.prototype, "rotation", {
  76866. /** Gets or sets current rotation (in local space) */
  76867. get: function () {
  76868. return this.getRotation();
  76869. },
  76870. set: function (newRotation) {
  76871. this.setRotation(newRotation);
  76872. },
  76873. enumerable: true,
  76874. configurable: true
  76875. });
  76876. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  76877. /** Gets or sets current rotation quaternion (in local space) */
  76878. get: function () {
  76879. this._decompose();
  76880. return this._localRotation;
  76881. },
  76882. set: function (newRotation) {
  76883. this.setRotationQuaternion(newRotation);
  76884. },
  76885. enumerable: true,
  76886. configurable: true
  76887. });
  76888. Object.defineProperty(Bone.prototype, "scaling", {
  76889. /** Gets or sets current scaling (in local space) */
  76890. get: function () {
  76891. return this.getScale();
  76892. },
  76893. set: function (newScaling) {
  76894. this.setScale(newScaling);
  76895. },
  76896. enumerable: true,
  76897. configurable: true
  76898. });
  76899. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  76900. /**
  76901. * Gets the animation properties override
  76902. */
  76903. get: function () {
  76904. return this._skeleton.animationPropertiesOverride;
  76905. },
  76906. enumerable: true,
  76907. configurable: true
  76908. });
  76909. // Methods
  76910. Bone.prototype._decompose = function () {
  76911. if (!this._needToDecompose) {
  76912. return;
  76913. }
  76914. this._needToDecompose = false;
  76915. if (!this._localScaling) {
  76916. this._localScaling = BABYLON.Vector3.Zero();
  76917. this._localRotation = BABYLON.Quaternion.Zero();
  76918. this._localPosition = BABYLON.Vector3.Zero();
  76919. }
  76920. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  76921. };
  76922. Bone.prototype._compose = function () {
  76923. if (!this._needToCompose) {
  76924. return;
  76925. }
  76926. this._needToCompose = false;
  76927. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  76928. };
  76929. /**
  76930. * Update the base and local matrices
  76931. * @param matrix defines the new base or local matrix
  76932. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76933. * @param updateLocalMatrix defines if the local matrix should be updated
  76934. */
  76935. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  76936. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76937. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  76938. this._baseMatrix.copyFrom(matrix);
  76939. if (updateDifferenceMatrix) {
  76940. this._updateDifferenceMatrix();
  76941. }
  76942. if (updateLocalMatrix) {
  76943. this._localMatrix.copyFrom(matrix);
  76944. this._markAsDirtyAndDecompose();
  76945. }
  76946. else {
  76947. this.markAsDirty();
  76948. }
  76949. };
  76950. /** @ignore */
  76951. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  76952. if (updateChildren === void 0) { updateChildren = true; }
  76953. if (!rootMatrix) {
  76954. rootMatrix = this._baseMatrix;
  76955. }
  76956. if (this._parent) {
  76957. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76958. }
  76959. else {
  76960. this._absoluteTransform.copyFrom(rootMatrix);
  76961. }
  76962. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  76963. if (updateChildren) {
  76964. for (var index = 0; index < this.children.length; index++) {
  76965. this.children[index]._updateDifferenceMatrix();
  76966. }
  76967. }
  76968. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  76969. };
  76970. /**
  76971. * Flag the bone as dirty (Forcing it to update everything)
  76972. */
  76973. Bone.prototype.markAsDirty = function () {
  76974. this._currentRenderId++;
  76975. this._childRenderId++;
  76976. this._skeleton._markAsDirty();
  76977. };
  76978. Bone.prototype._markAsDirtyAndCompose = function () {
  76979. this.markAsDirty();
  76980. this._needToCompose = true;
  76981. };
  76982. Bone.prototype._markAsDirtyAndDecompose = function () {
  76983. this.markAsDirty();
  76984. this._needToDecompose = true;
  76985. };
  76986. /**
  76987. * Copy an animation range from another bone
  76988. * @param source defines the source bone
  76989. * @param rangeName defines the range name to copy
  76990. * @param frameOffset defines the frame offset
  76991. * @param rescaleAsRequired defines if rescaling must be applied if required
  76992. * @param skelDimensionsRatio defines the scaling ratio
  76993. * @returns true if operation was successful
  76994. */
  76995. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  76996. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76997. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  76998. // all animation may be coming from a library skeleton, so may need to create animation
  76999. if (this.animations.length === 0) {
  77000. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77001. this.animations[0].setKeys([]);
  77002. }
  77003. // get animation info / verify there is such a range from the source bone
  77004. var sourceRange = source.animations[0].getRange(rangeName);
  77005. if (!sourceRange) {
  77006. return false;
  77007. }
  77008. var from = sourceRange.from;
  77009. var to = sourceRange.to;
  77010. var sourceKeys = source.animations[0].getKeys();
  77011. // rescaling prep
  77012. var sourceBoneLength = source.length;
  77013. var sourceParent = source.getParent();
  77014. var parent = this.getParent();
  77015. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77016. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77017. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77018. var destKeys = this.animations[0].getKeys();
  77019. // loop vars declaration
  77020. var orig;
  77021. var origTranslation;
  77022. var mat;
  77023. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77024. orig = sourceKeys[key];
  77025. if (orig.frame >= from && orig.frame <= to) {
  77026. if (rescaleAsRequired) {
  77027. mat = orig.value.clone();
  77028. // scale based on parent ratio, when bone has parent
  77029. if (parentScalingReqd) {
  77030. origTranslation = mat.getTranslation();
  77031. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77032. // scale based on skeleton dimension ratio when root bone, and value is passed
  77033. }
  77034. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77035. origTranslation = mat.getTranslation();
  77036. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77037. // use original when root bone, and no data for skelDimensionsRatio
  77038. }
  77039. else {
  77040. mat = orig.value;
  77041. }
  77042. }
  77043. else {
  77044. mat = orig.value;
  77045. }
  77046. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77047. }
  77048. }
  77049. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77050. return true;
  77051. };
  77052. /**
  77053. * Translate the bone in local or world space
  77054. * @param vec The amount to translate the bone
  77055. * @param space The space that the translation is in
  77056. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77057. */
  77058. Bone.prototype.translate = function (vec, space, mesh) {
  77059. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77060. var lm = this.getLocalMatrix();
  77061. if (space == BABYLON.Space.LOCAL) {
  77062. lm.m[12] += vec.x;
  77063. lm.m[13] += vec.y;
  77064. lm.m[14] += vec.z;
  77065. }
  77066. else {
  77067. var wm = null;
  77068. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77069. if (mesh) {
  77070. wm = mesh.getWorldMatrix();
  77071. }
  77072. this._skeleton.computeAbsoluteTransforms();
  77073. var tmat = Bone._tmpMats[0];
  77074. var tvec = Bone._tmpVecs[0];
  77075. if (this._parent) {
  77076. if (mesh && wm) {
  77077. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77078. tmat.multiplyToRef(wm, tmat);
  77079. }
  77080. else {
  77081. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77082. }
  77083. }
  77084. tmat.m[12] = 0;
  77085. tmat.m[13] = 0;
  77086. tmat.m[14] = 0;
  77087. tmat.invert();
  77088. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77089. lm.m[12] += tvec.x;
  77090. lm.m[13] += tvec.y;
  77091. lm.m[14] += tvec.z;
  77092. }
  77093. this._markAsDirtyAndDecompose();
  77094. };
  77095. /**
  77096. * Set the postion of the bone in local or world space
  77097. * @param position The position to set the bone
  77098. * @param space The space that the position is in
  77099. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77100. */
  77101. Bone.prototype.setPosition = function (position, space, mesh) {
  77102. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77103. var lm = this.getLocalMatrix();
  77104. if (space == BABYLON.Space.LOCAL) {
  77105. lm.m[12] = position.x;
  77106. lm.m[13] = position.y;
  77107. lm.m[14] = position.z;
  77108. }
  77109. else {
  77110. var wm = null;
  77111. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77112. if (mesh) {
  77113. wm = mesh.getWorldMatrix();
  77114. }
  77115. this._skeleton.computeAbsoluteTransforms();
  77116. var tmat = Bone._tmpMats[0];
  77117. var vec = Bone._tmpVecs[0];
  77118. if (this._parent) {
  77119. if (mesh && wm) {
  77120. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77121. tmat.multiplyToRef(wm, tmat);
  77122. }
  77123. else {
  77124. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77125. }
  77126. }
  77127. tmat.invert();
  77128. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77129. lm.m[12] = vec.x;
  77130. lm.m[13] = vec.y;
  77131. lm.m[14] = vec.z;
  77132. }
  77133. this._markAsDirtyAndDecompose();
  77134. };
  77135. /**
  77136. * Set the absolute position of the bone (world space)
  77137. * @param position The position to set the bone
  77138. * @param mesh The mesh that this bone is attached to
  77139. */
  77140. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77141. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77142. };
  77143. /**
  77144. * Scale the bone on the x, y and z axes (in local space)
  77145. * @param x The amount to scale the bone on the x axis
  77146. * @param y The amount to scale the bone on the y axis
  77147. * @param z The amount to scale the bone on the z axis
  77148. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77149. */
  77150. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77151. if (scaleChildren === void 0) { scaleChildren = false; }
  77152. var locMat = this.getLocalMatrix();
  77153. // Apply new scaling on top of current local matrix
  77154. var scaleMat = Bone._tmpMats[0];
  77155. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77156. scaleMat.multiplyToRef(locMat, locMat);
  77157. // Invert scaling matrix and apply the inverse to all children
  77158. scaleMat.invert();
  77159. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77160. var child = _a[_i];
  77161. var cm = child.getLocalMatrix();
  77162. cm.multiplyToRef(scaleMat, cm);
  77163. cm.m[12] *= x;
  77164. cm.m[13] *= y;
  77165. cm.m[14] *= z;
  77166. child._markAsDirtyAndDecompose();
  77167. }
  77168. this._markAsDirtyAndDecompose();
  77169. if (scaleChildren) {
  77170. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77171. var child = _c[_b];
  77172. child.scale(x, y, z, scaleChildren);
  77173. }
  77174. }
  77175. };
  77176. /**
  77177. * Set the bone scaling in local space
  77178. * @param scale defines the scaling vector
  77179. */
  77180. Bone.prototype.setScale = function (scale) {
  77181. this._decompose();
  77182. this._localScaling.copyFrom(scale);
  77183. this._markAsDirtyAndCompose();
  77184. };
  77185. /**
  77186. * Gets the current scaling in local space
  77187. * @returns the current scaling vector
  77188. */
  77189. Bone.prototype.getScale = function () {
  77190. this._decompose();
  77191. return this._localScaling;
  77192. };
  77193. /**
  77194. * Gets the current scaling in local space and stores it in a target vector
  77195. * @param result defines the target vector
  77196. */
  77197. Bone.prototype.getScaleToRef = function (result) {
  77198. this._decompose();
  77199. result.copyFrom(this._localScaling);
  77200. };
  77201. /**
  77202. * Set the yaw, pitch, and roll of the bone in local or world space
  77203. * @param yaw The rotation of the bone on the y axis
  77204. * @param pitch The rotation of the bone on the x axis
  77205. * @param roll The rotation of the bone on the z axis
  77206. * @param space The space that the axes of rotation are in
  77207. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77208. */
  77209. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77210. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77211. if (space === BABYLON.Space.LOCAL) {
  77212. var quat = Bone._tmpQuat;
  77213. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77214. this.setRotationQuaternion(quat, space, mesh);
  77215. return;
  77216. }
  77217. var rotMatInv = Bone._tmpMats[0];
  77218. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77219. return;
  77220. }
  77221. var rotMat = Bone._tmpMats[1];
  77222. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77223. rotMatInv.multiplyToRef(rotMat, rotMat);
  77224. this._rotateWithMatrix(rotMat, space, mesh);
  77225. };
  77226. /**
  77227. * Add a rotation to the bone on an axis in local or world space
  77228. * @param axis The axis to rotate the bone on
  77229. * @param amount The amount to rotate the bone
  77230. * @param space The space that the axis is in
  77231. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77232. */
  77233. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77234. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77235. var rmat = Bone._tmpMats[0];
  77236. rmat.m[12] = 0;
  77237. rmat.m[13] = 0;
  77238. rmat.m[14] = 0;
  77239. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77240. this._rotateWithMatrix(rmat, space, mesh);
  77241. };
  77242. /**
  77243. * Set the rotation of the bone to a particular axis angle in local or world space
  77244. * @param axis The axis to rotate the bone on
  77245. * @param angle The angle that the bone should be rotated to
  77246. * @param space The space that the axis is in
  77247. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77248. */
  77249. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77250. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77251. if (space === BABYLON.Space.LOCAL) {
  77252. var quat = Bone._tmpQuat;
  77253. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77254. this.setRotationQuaternion(quat, space, mesh);
  77255. return;
  77256. }
  77257. var rotMatInv = Bone._tmpMats[0];
  77258. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77259. return;
  77260. }
  77261. var rotMat = Bone._tmpMats[1];
  77262. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77263. rotMatInv.multiplyToRef(rotMat, rotMat);
  77264. this._rotateWithMatrix(rotMat, space, mesh);
  77265. };
  77266. /**
  77267. * Set the euler rotation of the bone in local of world space
  77268. * @param rotation The euler rotation that the bone should be set to
  77269. * @param space The space that the rotation is in
  77270. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77271. */
  77272. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77273. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77274. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77275. };
  77276. /**
  77277. * Set the quaternion rotation of the bone in local of world space
  77278. * @param quat The quaternion rotation that the bone should be set to
  77279. * @param space The space that the rotation is in
  77280. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77281. */
  77282. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77283. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77284. if (space === BABYLON.Space.LOCAL) {
  77285. this._decompose();
  77286. this._localRotation.copyFrom(quat);
  77287. this._markAsDirtyAndCompose();
  77288. return;
  77289. }
  77290. var rotMatInv = Bone._tmpMats[0];
  77291. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77292. return;
  77293. }
  77294. var rotMat = Bone._tmpMats[1];
  77295. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77296. rotMatInv.multiplyToRef(rotMat, rotMat);
  77297. this._rotateWithMatrix(rotMat, space, mesh);
  77298. };
  77299. /**
  77300. * Set the rotation matrix of the bone in local of world space
  77301. * @param rotMat The rotation matrix that the bone should be set to
  77302. * @param space The space that the rotation is in
  77303. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77304. */
  77305. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77306. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77307. if (space === BABYLON.Space.LOCAL) {
  77308. var quat = Bone._tmpQuat;
  77309. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77310. this.setRotationQuaternion(quat, space, mesh);
  77311. return;
  77312. }
  77313. var rotMatInv = Bone._tmpMats[0];
  77314. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77315. return;
  77316. }
  77317. var rotMat2 = Bone._tmpMats[1];
  77318. rotMat2.copyFrom(rotMat);
  77319. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77320. this._rotateWithMatrix(rotMat2, space, mesh);
  77321. };
  77322. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77324. var lmat = this.getLocalMatrix();
  77325. var lx = lmat.m[12];
  77326. var ly = lmat.m[13];
  77327. var lz = lmat.m[14];
  77328. var parent = this.getParent();
  77329. var parentScale = Bone._tmpMats[3];
  77330. var parentScaleInv = Bone._tmpMats[4];
  77331. if (parent && space == BABYLON.Space.WORLD) {
  77332. if (mesh) {
  77333. parentScale.copyFrom(mesh.getWorldMatrix());
  77334. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77335. }
  77336. else {
  77337. parentScale.copyFrom(parent.getAbsoluteTransform());
  77338. }
  77339. parentScaleInv.copyFrom(parentScale);
  77340. parentScaleInv.invert();
  77341. lmat.multiplyToRef(parentScale, lmat);
  77342. lmat.multiplyToRef(rmat, lmat);
  77343. lmat.multiplyToRef(parentScaleInv, lmat);
  77344. }
  77345. else {
  77346. if (space == BABYLON.Space.WORLD && mesh) {
  77347. parentScale.copyFrom(mesh.getWorldMatrix());
  77348. parentScaleInv.copyFrom(parentScale);
  77349. parentScaleInv.invert();
  77350. lmat.multiplyToRef(parentScale, lmat);
  77351. lmat.multiplyToRef(rmat, lmat);
  77352. lmat.multiplyToRef(parentScaleInv, lmat);
  77353. }
  77354. else {
  77355. lmat.multiplyToRef(rmat, lmat);
  77356. }
  77357. }
  77358. lmat.m[12] = lx;
  77359. lmat.m[13] = ly;
  77360. lmat.m[14] = lz;
  77361. this.computeAbsoluteTransforms();
  77362. this._markAsDirtyAndDecompose();
  77363. };
  77364. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77365. var scaleMatrix = Bone._tmpMats[2];
  77366. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77367. if (mesh) {
  77368. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77369. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77370. }
  77371. rotMatInv.invert();
  77372. if (isNaN(rotMatInv.m[0])) {
  77373. // Matrix failed to invert.
  77374. // This can happen if scale is zero for example.
  77375. return false;
  77376. }
  77377. scaleMatrix.m[0] *= this._scalingDeterminant;
  77378. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77379. return true;
  77380. };
  77381. /**
  77382. * Get the position of the bone in local or world space
  77383. * @param space The space that the returned position is in
  77384. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77385. * @returns The position of the bone
  77386. */
  77387. Bone.prototype.getPosition = function (space, mesh) {
  77388. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77389. if (mesh === void 0) { mesh = null; }
  77390. var pos = BABYLON.Vector3.Zero();
  77391. this.getPositionToRef(space, mesh, pos);
  77392. return pos;
  77393. };
  77394. /**
  77395. * Copy the position of the bone to a vector3 in local or world space
  77396. * @param space The space that the returned position is in
  77397. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77398. * @param result The vector3 to copy the position to
  77399. */
  77400. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77401. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77402. if (space == BABYLON.Space.LOCAL) {
  77403. var lm = this.getLocalMatrix();
  77404. result.x = lm.m[12];
  77405. result.y = lm.m[13];
  77406. result.z = lm.m[14];
  77407. }
  77408. else {
  77409. var wm = null;
  77410. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77411. if (mesh) {
  77412. wm = mesh.getWorldMatrix();
  77413. }
  77414. this._skeleton.computeAbsoluteTransforms();
  77415. var tmat = Bone._tmpMats[0];
  77416. if (mesh && wm) {
  77417. tmat.copyFrom(this.getAbsoluteTransform());
  77418. tmat.multiplyToRef(wm, tmat);
  77419. }
  77420. else {
  77421. tmat = this.getAbsoluteTransform();
  77422. }
  77423. result.x = tmat.m[12];
  77424. result.y = tmat.m[13];
  77425. result.z = tmat.m[14];
  77426. }
  77427. };
  77428. /**
  77429. * Get the absolute position of the bone (world space)
  77430. * @param mesh The mesh that this bone is attached to
  77431. * @returns The absolute position of the bone
  77432. */
  77433. Bone.prototype.getAbsolutePosition = function (mesh) {
  77434. if (mesh === void 0) { mesh = null; }
  77435. var pos = BABYLON.Vector3.Zero();
  77436. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77437. return pos;
  77438. };
  77439. /**
  77440. * Copy the absolute position of the bone (world space) to the result param
  77441. * @param mesh The mesh that this bone is attached to
  77442. * @param result The vector3 to copy the absolute position to
  77443. */
  77444. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77445. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77446. };
  77447. /**
  77448. * Compute the absolute transforms of this bone and its children
  77449. */
  77450. Bone.prototype.computeAbsoluteTransforms = function () {
  77451. this._compose();
  77452. if (this._parent) {
  77453. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77454. }
  77455. else {
  77456. this._absoluteTransform.copyFrom(this._localMatrix);
  77457. var poseMatrix = this._skeleton.getPoseMatrix();
  77458. if (poseMatrix) {
  77459. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  77460. }
  77461. }
  77462. var children = this.children;
  77463. var len = children.length;
  77464. for (var i = 0; i < len; i++) {
  77465. children[i].computeAbsoluteTransforms();
  77466. }
  77467. };
  77468. /**
  77469. * Get the world direction from an axis that is in the local space of the bone
  77470. * @param localAxis The local direction that is used to compute the world direction
  77471. * @param mesh The mesh that this bone is attached to
  77472. * @returns The world direction
  77473. */
  77474. Bone.prototype.getDirection = function (localAxis, mesh) {
  77475. if (mesh === void 0) { mesh = null; }
  77476. var result = BABYLON.Vector3.Zero();
  77477. this.getDirectionToRef(localAxis, mesh, result);
  77478. return result;
  77479. };
  77480. /**
  77481. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  77482. * @param localAxis The local direction that is used to compute the world direction
  77483. * @param mesh The mesh that this bone is attached to
  77484. * @param result The vector3 that the world direction will be copied to
  77485. */
  77486. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  77487. if (mesh === void 0) { mesh = null; }
  77488. var wm = null;
  77489. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77490. if (mesh) {
  77491. wm = mesh.getWorldMatrix();
  77492. }
  77493. this._skeleton.computeAbsoluteTransforms();
  77494. var mat = Bone._tmpMats[0];
  77495. mat.copyFrom(this.getAbsoluteTransform());
  77496. if (mesh && wm) {
  77497. mat.multiplyToRef(wm, mat);
  77498. }
  77499. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  77500. result.normalize();
  77501. };
  77502. /**
  77503. * Get the euler rotation of the bone in local or world space
  77504. * @param space The space that the rotation should be in
  77505. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77506. * @returns The euler rotation
  77507. */
  77508. Bone.prototype.getRotation = function (space, mesh) {
  77509. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77510. if (mesh === void 0) { mesh = null; }
  77511. var result = BABYLON.Vector3.Zero();
  77512. this.getRotationToRef(space, mesh, result);
  77513. return result;
  77514. };
  77515. /**
  77516. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  77517. * @param space The space that the rotation should be in
  77518. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77519. * @param result The vector3 that the rotation should be copied to
  77520. */
  77521. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  77522. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77523. if (mesh === void 0) { mesh = null; }
  77524. var quat = Bone._tmpQuat;
  77525. this.getRotationQuaternionToRef(space, mesh, quat);
  77526. quat.toEulerAnglesToRef(result);
  77527. };
  77528. /**
  77529. * Get the quaternion rotation of the bone in either local or world space
  77530. * @param space The space that the rotation should be in
  77531. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77532. * @returns The quaternion rotation
  77533. */
  77534. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  77535. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77536. if (mesh === void 0) { mesh = null; }
  77537. var result = BABYLON.Quaternion.Identity();
  77538. this.getRotationQuaternionToRef(space, mesh, result);
  77539. return result;
  77540. };
  77541. /**
  77542. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  77543. * @param space The space that the rotation should be in
  77544. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77545. * @param result The quaternion that the rotation should be copied to
  77546. */
  77547. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  77548. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77549. if (mesh === void 0) { mesh = null; }
  77550. if (space == BABYLON.Space.LOCAL) {
  77551. this._decompose();
  77552. result.copyFrom(this._localRotation);
  77553. }
  77554. else {
  77555. var mat = Bone._tmpMats[0];
  77556. var amat = this.getAbsoluteTransform();
  77557. if (mesh) {
  77558. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77559. }
  77560. else {
  77561. mat.copyFrom(amat);
  77562. }
  77563. mat.m[0] *= this._scalingDeterminant;
  77564. mat.m[1] *= this._scalingDeterminant;
  77565. mat.m[2] *= this._scalingDeterminant;
  77566. mat.decompose(undefined, result, undefined);
  77567. }
  77568. };
  77569. /**
  77570. * Get the rotation matrix of the bone in local or world space
  77571. * @param space The space that the rotation should be in
  77572. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77573. * @returns The rotation matrix
  77574. */
  77575. Bone.prototype.getRotationMatrix = function (space, mesh) {
  77576. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77577. var result = BABYLON.Matrix.Identity();
  77578. this.getRotationMatrixToRef(space, mesh, result);
  77579. return result;
  77580. };
  77581. /**
  77582. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  77583. * @param space The space that the rotation should be in
  77584. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77585. * @param result The quaternion that the rotation should be copied to
  77586. */
  77587. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  77588. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77589. if (space == BABYLON.Space.LOCAL) {
  77590. this.getLocalMatrix().getRotationMatrixToRef(result);
  77591. }
  77592. else {
  77593. var mat = Bone._tmpMats[0];
  77594. var amat = this.getAbsoluteTransform();
  77595. if (mesh) {
  77596. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77597. }
  77598. else {
  77599. mat.copyFrom(amat);
  77600. }
  77601. mat.m[0] *= this._scalingDeterminant;
  77602. mat.m[1] *= this._scalingDeterminant;
  77603. mat.m[2] *= this._scalingDeterminant;
  77604. mat.getRotationMatrixToRef(result);
  77605. }
  77606. };
  77607. /**
  77608. * Get the world position of a point that is in the local space of the bone
  77609. * @param position The local position
  77610. * @param mesh The mesh that this bone is attached to
  77611. * @returns The world position
  77612. */
  77613. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  77614. if (mesh === void 0) { mesh = null; }
  77615. var result = BABYLON.Vector3.Zero();
  77616. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  77617. return result;
  77618. };
  77619. /**
  77620. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  77621. * @param position The local position
  77622. * @param mesh The mesh that this bone is attached to
  77623. * @param result The vector3 that the world position should be copied to
  77624. */
  77625. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  77626. if (mesh === void 0) { mesh = null; }
  77627. var wm = null;
  77628. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77629. if (mesh) {
  77630. wm = mesh.getWorldMatrix();
  77631. }
  77632. this._skeleton.computeAbsoluteTransforms();
  77633. var tmat = Bone._tmpMats[0];
  77634. if (mesh && wm) {
  77635. tmat.copyFrom(this.getAbsoluteTransform());
  77636. tmat.multiplyToRef(wm, tmat);
  77637. }
  77638. else {
  77639. tmat = this.getAbsoluteTransform();
  77640. }
  77641. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77642. };
  77643. /**
  77644. * Get the local position of a point that is in world space
  77645. * @param position The world position
  77646. * @param mesh The mesh that this bone is attached to
  77647. * @returns The local position
  77648. */
  77649. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  77650. if (mesh === void 0) { mesh = null; }
  77651. var result = BABYLON.Vector3.Zero();
  77652. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  77653. return result;
  77654. };
  77655. /**
  77656. * Get the local position of a point that is in world space and copy it to the result param
  77657. * @param position The world position
  77658. * @param mesh The mesh that this bone is attached to
  77659. * @param result The vector3 that the local position should be copied to
  77660. */
  77661. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  77662. if (mesh === void 0) { mesh = null; }
  77663. var wm = null;
  77664. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77665. if (mesh) {
  77666. wm = mesh.getWorldMatrix();
  77667. }
  77668. this._skeleton.computeAbsoluteTransforms();
  77669. var tmat = Bone._tmpMats[0];
  77670. tmat.copyFrom(this.getAbsoluteTransform());
  77671. if (mesh && wm) {
  77672. tmat.multiplyToRef(wm, tmat);
  77673. }
  77674. tmat.invert();
  77675. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77676. };
  77677. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77678. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  77679. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77680. return Bone;
  77681. }(BABYLON.Node));
  77682. BABYLON.Bone = Bone;
  77683. })(BABYLON || (BABYLON = {}));
  77684. //# sourceMappingURL=babylon.bone.js.map
  77685. var BABYLON;
  77686. (function (BABYLON) {
  77687. /**
  77688. * Class used to apply inverse kinematics to bones
  77689. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  77690. */
  77691. var BoneIKController = /** @class */ (function () {
  77692. /**
  77693. * Creates a new BoneIKController
  77694. * @param mesh defines the mesh to control
  77695. * @param bone defines the bone to control
  77696. * @param options defines options to set up the controller
  77697. */
  77698. function BoneIKController(mesh, bone, options) {
  77699. /**
  77700. * Gets or sets the target position
  77701. */
  77702. this.targetPosition = BABYLON.Vector3.Zero();
  77703. /**
  77704. * Gets or sets the pole target position
  77705. */
  77706. this.poleTargetPosition = BABYLON.Vector3.Zero();
  77707. /**
  77708. * Gets or sets the pole target local offset
  77709. */
  77710. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  77711. /**
  77712. * Gets or sets the pole angle
  77713. */
  77714. this.poleAngle = 0;
  77715. /**
  77716. * 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)
  77717. */
  77718. this.slerpAmount = 1;
  77719. this._bone1Quat = BABYLON.Quaternion.Identity();
  77720. this._bone1Mat = BABYLON.Matrix.Identity();
  77721. this._bone2Ang = Math.PI;
  77722. this._maxAngle = Math.PI;
  77723. this._rightHandedSystem = false;
  77724. this._bendAxis = BABYLON.Vector3.Right();
  77725. this._slerping = false;
  77726. this._adjustRoll = 0;
  77727. this._bone2 = bone;
  77728. this._bone1 = bone.getParent();
  77729. if (!this._bone1) {
  77730. return;
  77731. }
  77732. this.mesh = mesh;
  77733. var bonePos = bone.getPosition();
  77734. if (bone.getAbsoluteTransform().determinant() > 0) {
  77735. this._rightHandedSystem = true;
  77736. this._bendAxis.x = 0;
  77737. this._bendAxis.y = 0;
  77738. this._bendAxis.z = -1;
  77739. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  77740. this._adjustRoll = Math.PI * .5;
  77741. this._bendAxis.z = 1;
  77742. }
  77743. }
  77744. if (this._bone1.length) {
  77745. var boneScale1 = this._bone1.getScale();
  77746. var boneScale2 = this._bone2.getScale();
  77747. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  77748. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  77749. }
  77750. else if (this._bone1.children[0]) {
  77751. mesh.computeWorldMatrix(true);
  77752. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  77753. var pos2 = this._bone2.getAbsolutePosition(mesh);
  77754. var pos3 = this._bone1.getAbsolutePosition(mesh);
  77755. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  77756. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  77757. }
  77758. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  77759. this.maxAngle = Math.PI;
  77760. if (options) {
  77761. if (options.targetMesh) {
  77762. this.targetMesh = options.targetMesh;
  77763. this.targetMesh.computeWorldMatrix(true);
  77764. }
  77765. if (options.poleTargetMesh) {
  77766. this.poleTargetMesh = options.poleTargetMesh;
  77767. this.poleTargetMesh.computeWorldMatrix(true);
  77768. }
  77769. else if (options.poleTargetBone) {
  77770. this.poleTargetBone = options.poleTargetBone;
  77771. }
  77772. else if (this._bone1.getParent()) {
  77773. this.poleTargetBone = this._bone1.getParent();
  77774. }
  77775. if (options.poleTargetLocalOffset) {
  77776. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  77777. }
  77778. if (options.poleAngle) {
  77779. this.poleAngle = options.poleAngle;
  77780. }
  77781. if (options.bendAxis) {
  77782. this._bendAxis.copyFrom(options.bendAxis);
  77783. }
  77784. if (options.maxAngle) {
  77785. this.maxAngle = options.maxAngle;
  77786. }
  77787. if (options.slerpAmount) {
  77788. this.slerpAmount = options.slerpAmount;
  77789. }
  77790. }
  77791. }
  77792. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  77793. /**
  77794. * Gets or sets maximum allowed angle
  77795. */
  77796. get: function () {
  77797. return this._maxAngle;
  77798. },
  77799. set: function (value) {
  77800. this._setMaxAngle(value);
  77801. },
  77802. enumerable: true,
  77803. configurable: true
  77804. });
  77805. BoneIKController.prototype._setMaxAngle = function (ang) {
  77806. if (ang < 0) {
  77807. ang = 0;
  77808. }
  77809. if (ang > Math.PI || ang == undefined) {
  77810. ang = Math.PI;
  77811. }
  77812. this._maxAngle = ang;
  77813. var a = this._bone1Length;
  77814. var b = this._bone2Length;
  77815. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  77816. };
  77817. /**
  77818. * Force the controller to update the bones
  77819. */
  77820. BoneIKController.prototype.update = function () {
  77821. var bone1 = this._bone1;
  77822. if (!bone1) {
  77823. return;
  77824. }
  77825. var target = this.targetPosition;
  77826. var poleTarget = this.poleTargetPosition;
  77827. var mat1 = BoneIKController._tmpMats[0];
  77828. var mat2 = BoneIKController._tmpMats[1];
  77829. if (this.targetMesh) {
  77830. target.copyFrom(this.targetMesh.getAbsolutePosition());
  77831. }
  77832. if (this.poleTargetBone) {
  77833. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  77834. }
  77835. else if (this.poleTargetMesh) {
  77836. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  77837. }
  77838. var bonePos = BoneIKController._tmpVecs[0];
  77839. var zaxis = BoneIKController._tmpVecs[1];
  77840. var xaxis = BoneIKController._tmpVecs[2];
  77841. var yaxis = BoneIKController._tmpVecs[3];
  77842. var upAxis = BoneIKController._tmpVecs[4];
  77843. var _tmpQuat = BoneIKController._tmpQuat;
  77844. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  77845. poleTarget.subtractToRef(bonePos, upAxis);
  77846. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  77847. upAxis.y = 1;
  77848. }
  77849. else {
  77850. upAxis.normalize();
  77851. }
  77852. target.subtractToRef(bonePos, yaxis);
  77853. yaxis.normalize();
  77854. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  77855. zaxis.normalize();
  77856. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  77857. xaxis.normalize();
  77858. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  77859. var a = this._bone1Length;
  77860. var b = this._bone2Length;
  77861. var c = BABYLON.Vector3.Distance(bonePos, target);
  77862. if (this._maxReach > 0) {
  77863. c = Math.min(this._maxReach, c);
  77864. }
  77865. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  77866. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  77867. if (acosa > 1) {
  77868. acosa = 1;
  77869. }
  77870. if (acosb > 1) {
  77871. acosb = 1;
  77872. }
  77873. if (acosa < -1) {
  77874. acosa = -1;
  77875. }
  77876. if (acosb < -1) {
  77877. acosb = -1;
  77878. }
  77879. var angA = Math.acos(acosa);
  77880. var angB = Math.acos(acosb);
  77881. var angC = -angA - angB;
  77882. if (this._rightHandedSystem) {
  77883. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  77884. mat2.multiplyToRef(mat1, mat1);
  77885. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  77886. mat2.multiplyToRef(mat1, mat1);
  77887. }
  77888. else {
  77889. var _tmpVec = BoneIKController._tmpVecs[5];
  77890. _tmpVec.copyFrom(this._bendAxis);
  77891. _tmpVec.x *= -1;
  77892. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  77893. mat2.multiplyToRef(mat1, mat1);
  77894. }
  77895. if (this.poleAngle) {
  77896. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  77897. mat1.multiplyToRef(mat2, mat1);
  77898. }
  77899. if (this._bone1) {
  77900. if (this.slerpAmount < 1) {
  77901. if (!this._slerping) {
  77902. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  77903. }
  77904. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  77905. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  77906. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  77907. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  77908. this._slerping = true;
  77909. }
  77910. else {
  77911. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  77912. this._bone1Mat.copyFrom(mat1);
  77913. this._slerping = false;
  77914. }
  77915. }
  77916. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  77917. this._bone2Ang = angC;
  77918. };
  77919. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77920. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  77921. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77922. return BoneIKController;
  77923. }());
  77924. BABYLON.BoneIKController = BoneIKController;
  77925. })(BABYLON || (BABYLON = {}));
  77926. //# sourceMappingURL=babylon.boneIKController.js.map
  77927. var BABYLON;
  77928. (function (BABYLON) {
  77929. /**
  77930. * Class used to make a bone look toward a point in space
  77931. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  77932. */
  77933. var BoneLookController = /** @class */ (function () {
  77934. /**
  77935. * Create a BoneLookController
  77936. * @param mesh the mesh that the bone belongs to
  77937. * @param bone the bone that will be looking to the target
  77938. * @param target the target Vector3 to look at
  77939. * @param settings optional settings:
  77940. * * maxYaw: the maximum angle the bone will yaw to
  77941. * * minYaw: the minimum angle the bone will yaw to
  77942. * * maxPitch: the maximum angle the bone will pitch to
  77943. * * minPitch: the minimum angle the bone will yaw to
  77944. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  77945. * * upAxis: the up axis of the coordinate system
  77946. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77947. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  77948. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  77949. * * adjustYaw: used to make an adjustment to the yaw of the bone
  77950. * * adjustPitch: used to make an adjustment to the pitch of the bone
  77951. * * adjustRoll: used to make an adjustment to the roll of the bone
  77952. **/
  77953. function BoneLookController(mesh, bone, target, options) {
  77954. /**
  77955. * The up axis of the coordinate system that is used when the bone is rotated
  77956. */
  77957. this.upAxis = BABYLON.Vector3.Up();
  77958. /**
  77959. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  77960. */
  77961. this.upAxisSpace = BABYLON.Space.LOCAL;
  77962. /**
  77963. * Used to make an adjustment to the yaw of the bone
  77964. */
  77965. this.adjustYaw = 0;
  77966. /**
  77967. * Used to make an adjustment to the pitch of the bone
  77968. */
  77969. this.adjustPitch = 0;
  77970. /**
  77971. * Used to make an adjustment to the roll of the bone
  77972. */
  77973. this.adjustRoll = 0;
  77974. /**
  77975. * 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)
  77976. */
  77977. this.slerpAmount = 1;
  77978. this._boneQuat = BABYLON.Quaternion.Identity();
  77979. this._slerping = false;
  77980. this._firstFrameSkipped = false;
  77981. this._fowardAxis = BABYLON.Vector3.Forward();
  77982. this.mesh = mesh;
  77983. this.bone = bone;
  77984. this.target = target;
  77985. if (options) {
  77986. if (options.adjustYaw) {
  77987. this.adjustYaw = options.adjustYaw;
  77988. }
  77989. if (options.adjustPitch) {
  77990. this.adjustPitch = options.adjustPitch;
  77991. }
  77992. if (options.adjustRoll) {
  77993. this.adjustRoll = options.adjustRoll;
  77994. }
  77995. if (options.maxYaw != null) {
  77996. this.maxYaw = options.maxYaw;
  77997. }
  77998. else {
  77999. this.maxYaw = Math.PI;
  78000. }
  78001. if (options.minYaw != null) {
  78002. this.minYaw = options.minYaw;
  78003. }
  78004. else {
  78005. this.minYaw = -Math.PI;
  78006. }
  78007. if (options.maxPitch != null) {
  78008. this.maxPitch = options.maxPitch;
  78009. }
  78010. else {
  78011. this.maxPitch = Math.PI;
  78012. }
  78013. if (options.minPitch != null) {
  78014. this.minPitch = options.minPitch;
  78015. }
  78016. else {
  78017. this.minPitch = -Math.PI;
  78018. }
  78019. if (options.slerpAmount != null) {
  78020. this.slerpAmount = options.slerpAmount;
  78021. }
  78022. if (options.upAxis != null) {
  78023. this.upAxis = options.upAxis;
  78024. }
  78025. if (options.upAxisSpace != null) {
  78026. this.upAxisSpace = options.upAxisSpace;
  78027. }
  78028. if (options.yawAxis != null || options.pitchAxis != null) {
  78029. var newYawAxis = BABYLON.Axis.Y;
  78030. var newPitchAxis = BABYLON.Axis.X;
  78031. if (options.yawAxis != null) {
  78032. newYawAxis = options.yawAxis.clone();
  78033. newYawAxis.normalize();
  78034. }
  78035. if (options.pitchAxis != null) {
  78036. newPitchAxis = options.pitchAxis.clone();
  78037. newPitchAxis.normalize();
  78038. }
  78039. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78040. this._transformYawPitch = BABYLON.Matrix.Identity();
  78041. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78042. this._transformYawPitchInv = this._transformYawPitch.clone();
  78043. this._transformYawPitch.invert();
  78044. }
  78045. }
  78046. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78047. this.upAxisSpace = BABYLON.Space.LOCAL;
  78048. }
  78049. }
  78050. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78051. /**
  78052. * Gets or sets the minimum yaw angle that the bone can look to
  78053. */
  78054. get: function () {
  78055. return this._minYaw;
  78056. },
  78057. set: function (value) {
  78058. this._minYaw = value;
  78059. this._minYawSin = Math.sin(value);
  78060. this._minYawCos = Math.cos(value);
  78061. if (this._maxYaw != null) {
  78062. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78063. this._yawRange = this._maxYaw - this._minYaw;
  78064. }
  78065. },
  78066. enumerable: true,
  78067. configurable: true
  78068. });
  78069. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78070. /**
  78071. * Gets or sets the maximum yaw angle that the bone can look to
  78072. */
  78073. get: function () {
  78074. return this._maxYaw;
  78075. },
  78076. set: function (value) {
  78077. this._maxYaw = value;
  78078. this._maxYawSin = Math.sin(value);
  78079. this._maxYawCos = Math.cos(value);
  78080. if (this._minYaw != null) {
  78081. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78082. this._yawRange = this._maxYaw - this._minYaw;
  78083. }
  78084. },
  78085. enumerable: true,
  78086. configurable: true
  78087. });
  78088. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78089. /**
  78090. * Gets or sets the minimum pitch angle that the bone can look to
  78091. */
  78092. get: function () {
  78093. return this._minPitch;
  78094. },
  78095. set: function (value) {
  78096. this._minPitch = value;
  78097. this._minPitchTan = Math.tan(value);
  78098. },
  78099. enumerable: true,
  78100. configurable: true
  78101. });
  78102. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78103. /**
  78104. * Gets or sets the maximum pitch angle that the bone can look to
  78105. */
  78106. get: function () {
  78107. return this._maxPitch;
  78108. },
  78109. set: function (value) {
  78110. this._maxPitch = value;
  78111. this._maxPitchTan = Math.tan(value);
  78112. },
  78113. enumerable: true,
  78114. configurable: true
  78115. });
  78116. /**
  78117. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78118. */
  78119. BoneLookController.prototype.update = function () {
  78120. //skip the first frame when slerping so that the mesh rotation is correct
  78121. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78122. this._firstFrameSkipped = true;
  78123. return;
  78124. }
  78125. var bone = this.bone;
  78126. var bonePos = BoneLookController._tmpVecs[0];
  78127. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78128. var target = this.target;
  78129. var _tmpMat1 = BoneLookController._tmpMats[0];
  78130. var _tmpMat2 = BoneLookController._tmpMats[1];
  78131. var mesh = this.mesh;
  78132. var parentBone = bone.getParent();
  78133. var upAxis = BoneLookController._tmpVecs[1];
  78134. upAxis.copyFrom(this.upAxis);
  78135. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78136. if (this._transformYawPitch) {
  78137. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78138. }
  78139. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78140. }
  78141. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78142. mesh.getDirectionToRef(upAxis, upAxis);
  78143. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78144. upAxis.normalize();
  78145. }
  78146. }
  78147. var checkYaw = false;
  78148. var checkPitch = false;
  78149. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78150. checkYaw = true;
  78151. }
  78152. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78153. checkPitch = true;
  78154. }
  78155. if (checkYaw || checkPitch) {
  78156. var spaceMat = BoneLookController._tmpMats[2];
  78157. var spaceMatInv = BoneLookController._tmpMats[3];
  78158. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78159. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78160. }
  78161. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78162. spaceMat.copyFrom(mesh.getWorldMatrix());
  78163. }
  78164. else {
  78165. var forwardAxis = BoneLookController._tmpVecs[2];
  78166. forwardAxis.copyFrom(this._fowardAxis);
  78167. if (this._transformYawPitch) {
  78168. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78169. }
  78170. if (parentBone) {
  78171. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78172. }
  78173. else {
  78174. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78175. }
  78176. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78177. rightAxis.normalize();
  78178. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78179. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78180. }
  78181. spaceMat.invertToRef(spaceMatInv);
  78182. var xzlen = null;
  78183. if (checkPitch) {
  78184. var localTarget = BoneLookController._tmpVecs[3];
  78185. target.subtractToRef(bonePos, localTarget);
  78186. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78187. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78188. var pitch = Math.atan2(localTarget.y, xzlen);
  78189. var newPitch = pitch;
  78190. if (pitch > this._maxPitch) {
  78191. localTarget.y = this._maxPitchTan * xzlen;
  78192. newPitch = this._maxPitch;
  78193. }
  78194. else if (pitch < this._minPitch) {
  78195. localTarget.y = this._minPitchTan * xzlen;
  78196. newPitch = this._minPitch;
  78197. }
  78198. if (pitch != newPitch) {
  78199. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78200. localTarget.addInPlace(bonePos);
  78201. target = localTarget;
  78202. }
  78203. }
  78204. if (checkYaw) {
  78205. var localTarget = BoneLookController._tmpVecs[4];
  78206. target.subtractToRef(bonePos, localTarget);
  78207. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78208. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78209. var newYaw = yaw;
  78210. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78211. if (xzlen == null) {
  78212. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78213. }
  78214. if (this._yawRange > Math.PI) {
  78215. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78216. localTarget.z = this._maxYawCos * xzlen;
  78217. localTarget.x = this._maxYawSin * xzlen;
  78218. newYaw = this._maxYaw;
  78219. }
  78220. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78221. localTarget.z = this._minYawCos * xzlen;
  78222. localTarget.x = this._minYawSin * xzlen;
  78223. newYaw = this._minYaw;
  78224. }
  78225. }
  78226. else {
  78227. if (yaw > this._maxYaw) {
  78228. localTarget.z = this._maxYawCos * xzlen;
  78229. localTarget.x = this._maxYawSin * xzlen;
  78230. newYaw = this._maxYaw;
  78231. }
  78232. else if (yaw < this._minYaw) {
  78233. localTarget.z = this._minYawCos * xzlen;
  78234. localTarget.x = this._minYawSin * xzlen;
  78235. newYaw = this._minYaw;
  78236. }
  78237. }
  78238. }
  78239. if (this._slerping && this._yawRange > Math.PI) {
  78240. //are we going to be crossing into the min/max region?
  78241. var boneFwd = BoneLookController._tmpVecs[8];
  78242. boneFwd.copyFrom(BABYLON.Axis.Z);
  78243. if (this._transformYawPitch) {
  78244. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78245. }
  78246. var boneRotMat = BoneLookController._tmpMats[4];
  78247. this._boneQuat.toRotationMatrix(boneRotMat);
  78248. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78249. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78250. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78251. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78252. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78253. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78254. if (angBtwTar > angBtwMidYaw) {
  78255. if (xzlen == null) {
  78256. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78257. }
  78258. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78259. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78260. if (angBtwMin < angBtwMax) {
  78261. newYaw = boneYaw + Math.PI * .75;
  78262. localTarget.z = Math.cos(newYaw) * xzlen;
  78263. localTarget.x = Math.sin(newYaw) * xzlen;
  78264. }
  78265. else {
  78266. newYaw = boneYaw - Math.PI * .75;
  78267. localTarget.z = Math.cos(newYaw) * xzlen;
  78268. localTarget.x = Math.sin(newYaw) * xzlen;
  78269. }
  78270. }
  78271. }
  78272. if (yaw != newYaw) {
  78273. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78274. localTarget.addInPlace(bonePos);
  78275. target = localTarget;
  78276. }
  78277. }
  78278. }
  78279. var zaxis = BoneLookController._tmpVecs[5];
  78280. var xaxis = BoneLookController._tmpVecs[6];
  78281. var yaxis = BoneLookController._tmpVecs[7];
  78282. var _tmpQuat = BoneLookController._tmpQuat;
  78283. target.subtractToRef(bonePos, zaxis);
  78284. zaxis.normalize();
  78285. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78286. xaxis.normalize();
  78287. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78288. yaxis.normalize();
  78289. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78290. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78291. return;
  78292. }
  78293. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78294. return;
  78295. }
  78296. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78297. return;
  78298. }
  78299. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78300. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78301. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78302. }
  78303. if (this.slerpAmount < 1) {
  78304. if (!this._slerping) {
  78305. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78306. }
  78307. if (this._transformYawPitch) {
  78308. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78309. }
  78310. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78311. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78312. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78313. this._slerping = true;
  78314. }
  78315. else {
  78316. if (this._transformYawPitch) {
  78317. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78318. }
  78319. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78320. this._slerping = false;
  78321. }
  78322. };
  78323. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78324. var angDiff = ang2 - ang1;
  78325. angDiff %= Math.PI * 2;
  78326. if (angDiff > Math.PI) {
  78327. angDiff -= Math.PI * 2;
  78328. }
  78329. else if (angDiff < -Math.PI) {
  78330. angDiff += Math.PI * 2;
  78331. }
  78332. return angDiff;
  78333. };
  78334. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78335. ang1 %= (2 * Math.PI);
  78336. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78337. ang2 %= (2 * Math.PI);
  78338. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78339. var ab = 0;
  78340. if (ang1 < ang2) {
  78341. ab = ang2 - ang1;
  78342. }
  78343. else {
  78344. ab = ang1 - ang2;
  78345. }
  78346. if (ab > Math.PI) {
  78347. ab = Math.PI * 2 - ab;
  78348. }
  78349. return ab;
  78350. };
  78351. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78352. ang %= (2 * Math.PI);
  78353. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78354. ang1 %= (2 * Math.PI);
  78355. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78356. ang2 %= (2 * Math.PI);
  78357. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78358. if (ang1 < ang2) {
  78359. if (ang > ang1 && ang < ang2) {
  78360. return true;
  78361. }
  78362. }
  78363. else {
  78364. if (ang > ang2 && ang < ang1) {
  78365. return true;
  78366. }
  78367. }
  78368. return false;
  78369. };
  78370. 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()];
  78371. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78372. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78373. return BoneLookController;
  78374. }());
  78375. BABYLON.BoneLookController = BoneLookController;
  78376. })(BABYLON || (BABYLON = {}));
  78377. //# sourceMappingURL=babylon.boneLookController.js.map
  78378. var BABYLON;
  78379. (function (BABYLON) {
  78380. /**
  78381. * Class used to handle skinning animations
  78382. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78383. */
  78384. var Skeleton = /** @class */ (function () {
  78385. /**
  78386. * Creates a new skeleton
  78387. * @param name defines the skeleton name
  78388. * @param id defines the skeleton Id
  78389. * @param scene defines the hosting scene
  78390. */
  78391. function Skeleton(
  78392. /** defines the skeleton name */
  78393. name,
  78394. /** defines the skeleton Id */
  78395. id, scene) {
  78396. this.name = name;
  78397. this.id = id;
  78398. /**
  78399. * Gets the list of child bones
  78400. */
  78401. this.bones = new Array();
  78402. /**
  78403. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78404. */
  78405. this.needInitialSkinMatrix = false;
  78406. this._isDirty = true;
  78407. this._meshesWithPoseMatrix = new Array();
  78408. this._identity = BABYLON.Matrix.Identity();
  78409. this._ranges = {};
  78410. this._lastAbsoluteTransformsUpdateId = -1;
  78411. /**
  78412. * Specifies if the skeleton should be serialized
  78413. */
  78414. this.doNotSerialize = false;
  78415. this._animationPropertiesOverride = null;
  78416. // Events
  78417. /**
  78418. * An observable triggered before computing the skeleton's matrices
  78419. */
  78420. this.onBeforeComputeObservable = new BABYLON.Observable();
  78421. this.bones = [];
  78422. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78423. scene.skeletons.push(this);
  78424. //make sure it will recalculate the matrix next time prepare is called.
  78425. this._isDirty = true;
  78426. }
  78427. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78428. /**
  78429. * Gets or sets the animation properties override
  78430. */
  78431. get: function () {
  78432. if (!this._animationPropertiesOverride) {
  78433. return this._scene.animationPropertiesOverride;
  78434. }
  78435. return this._animationPropertiesOverride;
  78436. },
  78437. set: function (value) {
  78438. this._animationPropertiesOverride = value;
  78439. },
  78440. enumerable: true,
  78441. configurable: true
  78442. });
  78443. // Members
  78444. /**
  78445. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78446. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  78447. * @returns a Float32Array containing matrices data
  78448. */
  78449. Skeleton.prototype.getTransformMatrices = function (mesh) {
  78450. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  78451. return mesh._bonesTransformMatrices;
  78452. }
  78453. if (!this._transformMatrices) {
  78454. this.prepare();
  78455. }
  78456. return this._transformMatrices;
  78457. };
  78458. /**
  78459. * Gets the current hosting scene
  78460. * @returns a scene object
  78461. */
  78462. Skeleton.prototype.getScene = function () {
  78463. return this._scene;
  78464. };
  78465. // Methods
  78466. /**
  78467. * Gets a string representing the current skeleton data
  78468. * @param fullDetails defines a boolean indicating if we want a verbose version
  78469. * @returns a string representing the current skeleton data
  78470. */
  78471. Skeleton.prototype.toString = function (fullDetails) {
  78472. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  78473. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  78474. if (fullDetails) {
  78475. ret += ", Ranges: {";
  78476. var first = true;
  78477. for (var name_1 in this._ranges) {
  78478. if (first) {
  78479. ret += ", ";
  78480. first = false;
  78481. }
  78482. ret += name_1;
  78483. }
  78484. ret += "}";
  78485. }
  78486. return ret;
  78487. };
  78488. /**
  78489. * Get bone's index searching by name
  78490. * @param name defines bone's name to search for
  78491. * @return the indice of the bone. Returns -1 if not found
  78492. */
  78493. Skeleton.prototype.getBoneIndexByName = function (name) {
  78494. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  78495. if (this.bones[boneIndex].name === name) {
  78496. return boneIndex;
  78497. }
  78498. }
  78499. return -1;
  78500. };
  78501. /**
  78502. * Creater a new animation range
  78503. * @param name defines the name of the range
  78504. * @param from defines the start key
  78505. * @param to defines the end key
  78506. */
  78507. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  78508. // check name not already in use
  78509. if (!this._ranges[name]) {
  78510. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  78511. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78512. if (this.bones[i].animations[0]) {
  78513. this.bones[i].animations[0].createRange(name, from, to);
  78514. }
  78515. }
  78516. }
  78517. };
  78518. /**
  78519. * Delete a specific animation range
  78520. * @param name defines the name of the range
  78521. * @param deleteFrames defines if frames must be removed as well
  78522. */
  78523. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  78524. if (deleteFrames === void 0) { deleteFrames = true; }
  78525. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78526. if (this.bones[i].animations[0]) {
  78527. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  78528. }
  78529. }
  78530. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  78531. };
  78532. /**
  78533. * Gets a specific animation range
  78534. * @param name defines the name of the range to look for
  78535. * @returns the requested animation range or null if not found
  78536. */
  78537. Skeleton.prototype.getAnimationRange = function (name) {
  78538. return this._ranges[name];
  78539. };
  78540. /**
  78541. * Gets the list of all animation ranges defined on this skeleton
  78542. * @returns an array
  78543. */
  78544. Skeleton.prototype.getAnimationRanges = function () {
  78545. var animationRanges = [];
  78546. var name;
  78547. var i = 0;
  78548. for (name in this._ranges) {
  78549. animationRanges[i] = this._ranges[name];
  78550. i++;
  78551. }
  78552. return animationRanges;
  78553. };
  78554. /**
  78555. * Copy animation range from a source skeleton.
  78556. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  78557. * @param source defines the source skeleton
  78558. * @param name defines the name of the range to copy
  78559. * @param rescaleAsRequired defines if rescaling must be applied if required
  78560. * @returns true if operation was successful
  78561. */
  78562. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  78563. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78564. if (this._ranges[name] || !source.getAnimationRange(name)) {
  78565. return false;
  78566. }
  78567. var ret = true;
  78568. var frameOffset = this._getHighestAnimationFrame() + 1;
  78569. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  78570. var boneDict = {};
  78571. var sourceBones = source.bones;
  78572. var nBones;
  78573. var i;
  78574. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  78575. boneDict[sourceBones[i].name] = sourceBones[i];
  78576. }
  78577. if (this.bones.length !== sourceBones.length) {
  78578. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  78579. ret = false;
  78580. }
  78581. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  78582. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  78583. var boneName = this.bones[i].name;
  78584. var sourceBone = boneDict[boneName];
  78585. if (sourceBone) {
  78586. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  78587. }
  78588. else {
  78589. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  78590. ret = false;
  78591. }
  78592. }
  78593. // do not call createAnimationRange(), since it also is done to bones, which was already done
  78594. var range = source.getAnimationRange(name);
  78595. if (range) {
  78596. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  78597. }
  78598. return ret;
  78599. };
  78600. /**
  78601. * Forces the skeleton to go to rest pose
  78602. */
  78603. Skeleton.prototype.returnToRest = function () {
  78604. for (var index = 0; index < this.bones.length; index++) {
  78605. this.bones[index].returnToRest();
  78606. }
  78607. };
  78608. Skeleton.prototype._getHighestAnimationFrame = function () {
  78609. var ret = 0;
  78610. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78611. if (this.bones[i].animations[0]) {
  78612. var highest = this.bones[i].animations[0].getHighestFrame();
  78613. if (ret < highest) {
  78614. ret = highest;
  78615. }
  78616. }
  78617. }
  78618. return ret;
  78619. };
  78620. /**
  78621. * Begin a specific animation range
  78622. * @param name defines the name of the range to start
  78623. * @param loop defines if looping must be turned on (false by default)
  78624. * @param speedRatio defines the speed ratio to apply (1 by default)
  78625. * @param onAnimationEnd defines a callback which will be called when animation will end
  78626. * @returns a new animatable
  78627. */
  78628. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  78629. var range = this.getAnimationRange(name);
  78630. if (!range) {
  78631. return null;
  78632. }
  78633. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  78634. };
  78635. /** @ignore */
  78636. Skeleton.prototype._markAsDirty = function () {
  78637. this._isDirty = true;
  78638. };
  78639. /** @ignore */
  78640. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  78641. this._meshesWithPoseMatrix.push(mesh);
  78642. };
  78643. /** @ignore */
  78644. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  78645. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  78646. if (index > -1) {
  78647. this._meshesWithPoseMatrix.splice(index, 1);
  78648. }
  78649. };
  78650. /** @ignore */
  78651. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  78652. this.onBeforeComputeObservable.notifyObservers(this);
  78653. for (var index = 0; index < this.bones.length; index++) {
  78654. var bone = this.bones[index];
  78655. var parentBone = bone.getParent();
  78656. if (parentBone) {
  78657. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  78658. }
  78659. else {
  78660. if (initialSkinMatrix) {
  78661. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  78662. }
  78663. else {
  78664. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  78665. }
  78666. }
  78667. if (bone._index !== -1) {
  78668. var mappedIndex = bone._index === null ? index : bone._index;
  78669. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  78670. }
  78671. }
  78672. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  78673. };
  78674. /**
  78675. * Build all resources required to render a skeleton
  78676. */
  78677. Skeleton.prototype.prepare = function () {
  78678. if (!this._isDirty) {
  78679. return;
  78680. }
  78681. if (this.needInitialSkinMatrix) {
  78682. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  78683. var mesh = this._meshesWithPoseMatrix[index];
  78684. var poseMatrix = mesh.getPoseMatrix();
  78685. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  78686. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78687. }
  78688. if (this._synchronizedWithMesh !== mesh) {
  78689. this._synchronizedWithMesh = mesh;
  78690. // Prepare bones
  78691. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  78692. var bone = this.bones[boneIndex];
  78693. if (!bone.getParent()) {
  78694. var matrix = bone.getBaseMatrix();
  78695. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  78696. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  78697. }
  78698. }
  78699. }
  78700. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  78701. }
  78702. }
  78703. else {
  78704. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  78705. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78706. }
  78707. this._computeTransformMatrices(this._transformMatrices, null);
  78708. }
  78709. this._isDirty = false;
  78710. this._scene._activeBones.addCount(this.bones.length, false);
  78711. };
  78712. /**
  78713. * Gets the list of animatables currently running for this skeleton
  78714. * @returns an array of animatables
  78715. */
  78716. Skeleton.prototype.getAnimatables = function () {
  78717. if (!this._animatables || this._animatables.length !== this.bones.length) {
  78718. this._animatables = [];
  78719. for (var index = 0; index < this.bones.length; index++) {
  78720. this._animatables.push(this.bones[index]);
  78721. }
  78722. }
  78723. return this._animatables;
  78724. };
  78725. /**
  78726. * Clone the current skeleton
  78727. * @param name defines the name of the new skeleton
  78728. * @param id defines the id of the enw skeleton
  78729. * @returns the new skeleton
  78730. */
  78731. Skeleton.prototype.clone = function (name, id) {
  78732. var result = new Skeleton(name, id || name, this._scene);
  78733. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78734. for (var index = 0; index < this.bones.length; index++) {
  78735. var source = this.bones[index];
  78736. var parentBone = null;
  78737. var parent_1 = source.getParent();
  78738. if (parent_1) {
  78739. var parentIndex = this.bones.indexOf(parent_1);
  78740. parentBone = result.bones[parentIndex];
  78741. }
  78742. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  78743. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  78744. }
  78745. if (this._ranges) {
  78746. result._ranges = {};
  78747. for (var rangeName in this._ranges) {
  78748. var range = this._ranges[rangeName];
  78749. if (range) {
  78750. result._ranges[rangeName] = range.clone();
  78751. }
  78752. }
  78753. }
  78754. this._isDirty = true;
  78755. return result;
  78756. };
  78757. /**
  78758. * Enable animation blending for this skeleton
  78759. * @param blendingSpeed defines the blending speed to apply
  78760. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  78761. */
  78762. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  78763. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  78764. this.bones.forEach(function (bone) {
  78765. bone.animations.forEach(function (animation) {
  78766. animation.enableBlending = true;
  78767. animation.blendingSpeed = blendingSpeed;
  78768. });
  78769. });
  78770. };
  78771. /**
  78772. * Releases all resources associated with the current skeleton
  78773. */
  78774. Skeleton.prototype.dispose = function () {
  78775. this._meshesWithPoseMatrix = [];
  78776. // Animations
  78777. this.getScene().stopAnimation(this);
  78778. // Remove from scene
  78779. this.getScene().removeSkeleton(this);
  78780. };
  78781. /**
  78782. * Serialize the skeleton in a JSON object
  78783. * @returns a JSON object
  78784. */
  78785. Skeleton.prototype.serialize = function () {
  78786. var serializationObject = {};
  78787. serializationObject.name = this.name;
  78788. serializationObject.id = this.id;
  78789. if (this.dimensionsAtRest) {
  78790. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  78791. }
  78792. serializationObject.bones = [];
  78793. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78794. for (var index = 0; index < this.bones.length; index++) {
  78795. var bone = this.bones[index];
  78796. var parent_2 = bone.getParent();
  78797. var serializedBone = {
  78798. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  78799. name: bone.name,
  78800. matrix: bone.getBaseMatrix().toArray(),
  78801. rest: bone.getRestPose().toArray()
  78802. };
  78803. serializationObject.bones.push(serializedBone);
  78804. if (bone.length) {
  78805. serializedBone.length = bone.length;
  78806. }
  78807. if (bone.animations && bone.animations.length > 0) {
  78808. serializedBone.animation = bone.animations[0].serialize();
  78809. }
  78810. serializationObject.ranges = [];
  78811. for (var name in this._ranges) {
  78812. var source = this._ranges[name];
  78813. if (!source) {
  78814. continue;
  78815. }
  78816. var range = {};
  78817. range.name = name;
  78818. range.from = source.from;
  78819. range.to = source.to;
  78820. serializationObject.ranges.push(range);
  78821. }
  78822. }
  78823. return serializationObject;
  78824. };
  78825. /**
  78826. * Creates a new skeleton from serialized data
  78827. * @param parsedSkeleton defines the serialized data
  78828. * @param scene defines the hosting scene
  78829. * @returns a new skeleton
  78830. */
  78831. Skeleton.Parse = function (parsedSkeleton, scene) {
  78832. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  78833. if (parsedSkeleton.dimensionsAtRest) {
  78834. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  78835. }
  78836. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  78837. var index;
  78838. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  78839. var parsedBone = parsedSkeleton.bones[index];
  78840. var parentBone = null;
  78841. if (parsedBone.parentBoneIndex > -1) {
  78842. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  78843. }
  78844. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  78845. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  78846. if (parsedBone.length) {
  78847. bone.length = parsedBone.length;
  78848. }
  78849. if (parsedBone.animation) {
  78850. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  78851. }
  78852. }
  78853. // placed after bones, so createAnimationRange can cascade down
  78854. if (parsedSkeleton.ranges) {
  78855. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  78856. var data = parsedSkeleton.ranges[index];
  78857. skeleton.createAnimationRange(data.name, data.from, data.to);
  78858. }
  78859. }
  78860. return skeleton;
  78861. };
  78862. /**
  78863. * Compute all node absolute transforms
  78864. * @param forceUpdate defines if computation must be done even if cache is up to date
  78865. */
  78866. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  78867. if (forceUpdate === void 0) { forceUpdate = false; }
  78868. var renderId = this._scene.getRenderId();
  78869. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  78870. this.bones[0].computeAbsoluteTransforms();
  78871. this._lastAbsoluteTransformsUpdateId = renderId;
  78872. }
  78873. };
  78874. /**
  78875. * Gets the root pose matrix
  78876. * @returns a matrix
  78877. */
  78878. Skeleton.prototype.getPoseMatrix = function () {
  78879. var poseMatrix = null;
  78880. if (this._meshesWithPoseMatrix.length > 0) {
  78881. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  78882. }
  78883. return poseMatrix;
  78884. };
  78885. /**
  78886. * Sorts bones per internal index
  78887. */
  78888. Skeleton.prototype.sortBones = function () {
  78889. var bones = new Array();
  78890. var visited = new Array(this.bones.length);
  78891. for (var index = 0; index < this.bones.length; index++) {
  78892. this._sortBones(index, bones, visited);
  78893. }
  78894. this.bones = bones;
  78895. };
  78896. Skeleton.prototype._sortBones = function (index, bones, visited) {
  78897. if (visited[index]) {
  78898. return;
  78899. }
  78900. visited[index] = true;
  78901. var bone = this.bones[index];
  78902. if (bone._index === undefined) {
  78903. bone._index = index;
  78904. }
  78905. var parentBone = bone.getParent();
  78906. if (parentBone) {
  78907. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  78908. }
  78909. bones.push(bone);
  78910. };
  78911. return Skeleton;
  78912. }());
  78913. BABYLON.Skeleton = Skeleton;
  78914. })(BABYLON || (BABYLON = {}));
  78915. //# sourceMappingURL=babylon.skeleton.js.map
  78916. var BABYLON;
  78917. (function (BABYLON) {
  78918. var SphericalPolynomial = /** @class */ (function () {
  78919. function SphericalPolynomial() {
  78920. this.x = BABYLON.Vector3.Zero();
  78921. this.y = BABYLON.Vector3.Zero();
  78922. this.z = BABYLON.Vector3.Zero();
  78923. this.xx = BABYLON.Vector3.Zero();
  78924. this.yy = BABYLON.Vector3.Zero();
  78925. this.zz = BABYLON.Vector3.Zero();
  78926. this.xy = BABYLON.Vector3.Zero();
  78927. this.yz = BABYLON.Vector3.Zero();
  78928. this.zx = BABYLON.Vector3.Zero();
  78929. }
  78930. SphericalPolynomial.prototype.addAmbient = function (color) {
  78931. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78932. this.xx = this.xx.add(colorVector);
  78933. this.yy = this.yy.add(colorVector);
  78934. this.zz = this.zz.add(colorVector);
  78935. };
  78936. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  78937. var result = new SphericalPolynomial();
  78938. result.x = harmonics.L11.scale(1.02333);
  78939. result.y = harmonics.L1_1.scale(1.02333);
  78940. result.z = harmonics.L10.scale(1.02333);
  78941. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  78942. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  78943. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  78944. result.yz = harmonics.L2_1.scale(0.858086);
  78945. result.zx = harmonics.L21.scale(0.858086);
  78946. result.xy = harmonics.L2_2.scale(0.858086);
  78947. result.scale(1.0 / Math.PI);
  78948. return result;
  78949. };
  78950. SphericalPolynomial.prototype.scale = function (scale) {
  78951. this.x = this.x.scale(scale);
  78952. this.y = this.y.scale(scale);
  78953. this.z = this.z.scale(scale);
  78954. this.xx = this.xx.scale(scale);
  78955. this.yy = this.yy.scale(scale);
  78956. this.zz = this.zz.scale(scale);
  78957. this.yz = this.yz.scale(scale);
  78958. this.zx = this.zx.scale(scale);
  78959. this.xy = this.xy.scale(scale);
  78960. };
  78961. return SphericalPolynomial;
  78962. }());
  78963. BABYLON.SphericalPolynomial = SphericalPolynomial;
  78964. var SphericalHarmonics = /** @class */ (function () {
  78965. function SphericalHarmonics() {
  78966. this.L00 = BABYLON.Vector3.Zero();
  78967. this.L1_1 = BABYLON.Vector3.Zero();
  78968. this.L10 = BABYLON.Vector3.Zero();
  78969. this.L11 = BABYLON.Vector3.Zero();
  78970. this.L2_2 = BABYLON.Vector3.Zero();
  78971. this.L2_1 = BABYLON.Vector3.Zero();
  78972. this.L20 = BABYLON.Vector3.Zero();
  78973. this.L21 = BABYLON.Vector3.Zero();
  78974. this.L22 = BABYLON.Vector3.Zero();
  78975. }
  78976. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  78977. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78978. var c = colorVector.scale(deltaSolidAngle);
  78979. this.L00 = this.L00.add(c.scale(0.282095));
  78980. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  78981. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  78982. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  78983. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  78984. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  78985. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  78986. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  78987. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  78988. };
  78989. SphericalHarmonics.prototype.scale = function (scale) {
  78990. this.L00 = this.L00.scale(scale);
  78991. this.L1_1 = this.L1_1.scale(scale);
  78992. this.L10 = this.L10.scale(scale);
  78993. this.L11 = this.L11.scale(scale);
  78994. this.L2_2 = this.L2_2.scale(scale);
  78995. this.L2_1 = this.L2_1.scale(scale);
  78996. this.L20 = this.L20.scale(scale);
  78997. this.L21 = this.L21.scale(scale);
  78998. this.L22 = this.L22.scale(scale);
  78999. };
  79000. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79001. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79002. //
  79003. // E_lm = A_l * L_lm
  79004. //
  79005. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79006. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79007. // the scaling factors are given in equation 9.
  79008. // Constant (Band 0)
  79009. this.L00 = this.L00.scale(3.141593);
  79010. // Linear (Band 1)
  79011. this.L1_1 = this.L1_1.scale(2.094395);
  79012. this.L10 = this.L10.scale(2.094395);
  79013. this.L11 = this.L11.scale(2.094395);
  79014. // Quadratic (Band 2)
  79015. this.L2_2 = this.L2_2.scale(0.785398);
  79016. this.L2_1 = this.L2_1.scale(0.785398);
  79017. this.L20 = this.L20.scale(0.785398);
  79018. this.L21 = this.L21.scale(0.785398);
  79019. this.L22 = this.L22.scale(0.785398);
  79020. };
  79021. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79022. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79023. // L = (1/pi) * E * rho
  79024. //
  79025. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79026. this.scale(1.0 / Math.PI);
  79027. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79028. // (The pixel shader must apply albedo after texture fetches, etc).
  79029. };
  79030. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79031. var result = new SphericalHarmonics();
  79032. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79033. result.L1_1 = polynomial.y.scale(0.977204);
  79034. result.L10 = polynomial.z.scale(0.977204);
  79035. result.L11 = polynomial.x.scale(0.977204);
  79036. result.L2_2 = polynomial.xy.scale(1.16538);
  79037. result.L2_1 = polynomial.yz.scale(1.16538);
  79038. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79039. result.L21 = polynomial.zx.scale(1.16538);
  79040. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79041. result.scale(Math.PI);
  79042. return result;
  79043. };
  79044. return SphericalHarmonics;
  79045. }());
  79046. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79047. })(BABYLON || (BABYLON = {}));
  79048. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79049. var BABYLON;
  79050. (function (BABYLON) {
  79051. var FileFaceOrientation = /** @class */ (function () {
  79052. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79053. this.name = name;
  79054. this.worldAxisForNormal = worldAxisForNormal;
  79055. this.worldAxisForFileX = worldAxisForFileX;
  79056. this.worldAxisForFileY = worldAxisForFileY;
  79057. }
  79058. return FileFaceOrientation;
  79059. }());
  79060. ;
  79061. /**
  79062. * Helper class dealing with the extraction of spherical polynomial dataArray
  79063. * from a cube map.
  79064. */
  79065. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79066. function CubeMapToSphericalPolynomialTools() {
  79067. }
  79068. /**
  79069. * Converts a texture to the according Spherical Polynomial data.
  79070. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79071. *
  79072. * @param texture The texture to extract the information from.
  79073. * @return The Spherical Polynomial data.
  79074. */
  79075. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79076. if (!texture.isCube) {
  79077. // Only supports cube Textures currently.
  79078. return null;
  79079. }
  79080. var size = texture.getSize().width;
  79081. var right = texture.readPixels(0);
  79082. var left = texture.readPixels(1);
  79083. var up;
  79084. var down;
  79085. if (texture.isRenderTarget) {
  79086. up = texture.readPixels(3);
  79087. down = texture.readPixels(2);
  79088. }
  79089. else {
  79090. up = texture.readPixels(2);
  79091. down = texture.readPixels(3);
  79092. }
  79093. var front = texture.readPixels(4);
  79094. var back = texture.readPixels(5);
  79095. var gammaSpace = texture.gammaSpace;
  79096. // Always read as RGBA.
  79097. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79098. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79099. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79100. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79101. }
  79102. var cubeInfo = {
  79103. size: size,
  79104. right: right,
  79105. left: left,
  79106. up: up,
  79107. down: down,
  79108. front: front,
  79109. back: back,
  79110. format: format,
  79111. type: type,
  79112. gammaSpace: gammaSpace,
  79113. };
  79114. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79115. };
  79116. /**
  79117. * Converts a cubemap to the according Spherical Polynomial data.
  79118. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79119. *
  79120. * @param cubeInfo The Cube map to extract the information from.
  79121. * @return The Spherical Polynomial data.
  79122. */
  79123. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79124. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79125. var totalSolidAngle = 0.0;
  79126. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79127. var du = 2.0 / cubeInfo.size;
  79128. var dv = du;
  79129. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79130. var minUV = du * 0.5 - 1.0;
  79131. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79132. var fileFace = this.FileFaces[faceIndex];
  79133. var dataArray = cubeInfo[fileFace.name];
  79134. var v = minUV;
  79135. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79136. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79137. // Because SP is still linear, so summation is fine in that basis.
  79138. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79139. for (var y = 0; y < cubeInfo.size; y++) {
  79140. var u = minUV;
  79141. for (var x = 0; x < cubeInfo.size; x++) {
  79142. // World direction (not normalised)
  79143. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79144. worldDirection.normalize();
  79145. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79146. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79147. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79148. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79149. // Handle Integer types.
  79150. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79151. r /= 255;
  79152. g /= 255;
  79153. b /= 255;
  79154. }
  79155. // Handle Gamma space textures.
  79156. if (cubeInfo.gammaSpace) {
  79157. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79158. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79159. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79160. }
  79161. var color = new BABYLON.Color3(r, g, b);
  79162. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79163. totalSolidAngle += deltaSolidAngle;
  79164. u += du;
  79165. }
  79166. v += dv;
  79167. }
  79168. }
  79169. // Solid angle for entire sphere is 4*pi
  79170. var sphereSolidAngle = 4.0 * Math.PI;
  79171. // Adjust the solid angle to allow for how many faces we processed.
  79172. var facesProcessed = 6.0;
  79173. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79174. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79175. // This is needed because the numerical integration over the cube uses a
  79176. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79177. // and also to compensate for accumulative error due to float precision in the summation.
  79178. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79179. sphericalHarmonics.scale(correctionFactor);
  79180. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79181. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79182. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79183. };
  79184. CubeMapToSphericalPolynomialTools.FileFaces = [
  79185. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79186. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79187. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79188. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79189. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79190. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79191. ];
  79192. return CubeMapToSphericalPolynomialTools;
  79193. }());
  79194. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79195. })(BABYLON || (BABYLON = {}));
  79196. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79197. var BABYLON;
  79198. (function (BABYLON) {
  79199. /**
  79200. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79201. */
  79202. var PanoramaToCubeMapTools = /** @class */ (function () {
  79203. function PanoramaToCubeMapTools() {
  79204. }
  79205. /**
  79206. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79207. *
  79208. * @param float32Array The source data.
  79209. * @param inputWidth The width of the input panorama.
  79210. * @param inputhHeight The height of the input panorama.
  79211. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79212. * @return The cubemap data
  79213. */
  79214. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79215. if (!float32Array) {
  79216. throw "ConvertPanoramaToCubemap: input cannot be null";
  79217. }
  79218. if (float32Array.length != inputWidth * inputHeight * 3) {
  79219. throw "ConvertPanoramaToCubemap: input size is wrong";
  79220. }
  79221. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79222. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79223. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79224. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79225. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79226. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79227. return {
  79228. front: textureFront,
  79229. back: textureBack,
  79230. left: textureLeft,
  79231. right: textureRight,
  79232. up: textureUp,
  79233. down: textureDown,
  79234. size: size,
  79235. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79236. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79237. gammaSpace: false,
  79238. };
  79239. };
  79240. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79241. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79242. var textureArray = new Float32Array(buffer);
  79243. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79244. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79245. var dy = 1 / texSize;
  79246. var fy = 0;
  79247. for (var y = 0; y < texSize; y++) {
  79248. var xv1 = faceData[0];
  79249. var xv2 = faceData[2];
  79250. for (var x = 0; x < texSize; x++) {
  79251. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79252. v.normalize();
  79253. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79254. // 3 channels per pixels
  79255. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79256. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79257. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79258. xv1 = xv1.add(rotDX1);
  79259. xv2 = xv2.add(rotDX2);
  79260. }
  79261. fy += dy;
  79262. }
  79263. return textureArray;
  79264. };
  79265. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79266. var theta = Math.atan2(vDir.z, vDir.x);
  79267. var phi = Math.acos(vDir.y);
  79268. while (theta < -Math.PI)
  79269. theta += 2 * Math.PI;
  79270. while (theta > Math.PI)
  79271. theta -= 2 * Math.PI;
  79272. var dx = theta / Math.PI;
  79273. var dy = phi / Math.PI;
  79274. // recenter.
  79275. dx = dx * 0.5 + 0.5;
  79276. var px = Math.round(dx * inputWidth);
  79277. if (px < 0)
  79278. px = 0;
  79279. else if (px >= inputWidth)
  79280. px = inputWidth - 1;
  79281. var py = Math.round(dy * inputHeight);
  79282. if (py < 0)
  79283. py = 0;
  79284. else if (py >= inputHeight)
  79285. py = inputHeight - 1;
  79286. var inputY = (inputHeight - py - 1);
  79287. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79288. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79289. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79290. return {
  79291. r: r,
  79292. g: g,
  79293. b: b
  79294. };
  79295. };
  79296. PanoramaToCubeMapTools.FACE_FRONT = [
  79297. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79298. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79299. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79300. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79301. ];
  79302. PanoramaToCubeMapTools.FACE_BACK = [
  79303. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79304. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79305. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79306. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79307. ];
  79308. PanoramaToCubeMapTools.FACE_RIGHT = [
  79309. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79310. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79311. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79312. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79313. ];
  79314. PanoramaToCubeMapTools.FACE_LEFT = [
  79315. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79316. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79317. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79318. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79319. ];
  79320. PanoramaToCubeMapTools.FACE_DOWN = [
  79321. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79322. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79323. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79324. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79325. ];
  79326. PanoramaToCubeMapTools.FACE_UP = [
  79327. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79328. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79329. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79330. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79331. ];
  79332. return PanoramaToCubeMapTools;
  79333. }());
  79334. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79335. })(BABYLON || (BABYLON = {}));
  79336. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79337. var BABYLON;
  79338. (function (BABYLON) {
  79339. ;
  79340. /**
  79341. * This groups tools to convert HDR texture to native colors array.
  79342. */
  79343. var HDRTools = /** @class */ (function () {
  79344. function HDRTools() {
  79345. }
  79346. HDRTools.Ldexp = function (mantissa, exponent) {
  79347. if (exponent > 1023) {
  79348. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79349. }
  79350. if (exponent < -1074) {
  79351. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79352. }
  79353. return mantissa * Math.pow(2, exponent);
  79354. };
  79355. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79356. if (exponent > 0) { /*nonzero pixel*/
  79357. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79358. float32array[index + 0] = red * exponent;
  79359. float32array[index + 1] = green * exponent;
  79360. float32array[index + 2] = blue * exponent;
  79361. }
  79362. else {
  79363. float32array[index + 0] = 0;
  79364. float32array[index + 1] = 0;
  79365. float32array[index + 2] = 0;
  79366. }
  79367. };
  79368. HDRTools.readStringLine = function (uint8array, startIndex) {
  79369. var line = "";
  79370. var character = "";
  79371. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79372. character = String.fromCharCode(uint8array[i]);
  79373. if (character == "\n") {
  79374. break;
  79375. }
  79376. line += character;
  79377. }
  79378. return line;
  79379. };
  79380. /**
  79381. * Reads header information from an RGBE texture stored in a native array.
  79382. * More information on this format are available here:
  79383. * https://en.wikipedia.org/wiki/RGBE_image_format
  79384. *
  79385. * @param uint8array The binary file stored in native array.
  79386. * @return The header information.
  79387. */
  79388. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79389. var height = 0;
  79390. var width = 0;
  79391. var line = this.readStringLine(uint8array, 0);
  79392. if (line[0] != '#' || line[1] != '?') {
  79393. throw "Bad HDR Format.";
  79394. }
  79395. var endOfHeader = false;
  79396. var findFormat = false;
  79397. var lineIndex = 0;
  79398. do {
  79399. lineIndex += (line.length + 1);
  79400. line = this.readStringLine(uint8array, lineIndex);
  79401. if (line == "FORMAT=32-bit_rle_rgbe") {
  79402. findFormat = true;
  79403. }
  79404. else if (line.length == 0) {
  79405. endOfHeader = true;
  79406. }
  79407. } while (!endOfHeader);
  79408. if (!findFormat) {
  79409. throw "HDR Bad header format, unsupported FORMAT";
  79410. }
  79411. lineIndex += (line.length + 1);
  79412. line = this.readStringLine(uint8array, lineIndex);
  79413. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79414. var match = sizeRegexp.exec(line);
  79415. // TODO. Support +Y and -X if needed.
  79416. if (!match || match.length < 3) {
  79417. throw "HDR Bad header format, no size";
  79418. }
  79419. width = parseInt(match[2]);
  79420. height = parseInt(match[1]);
  79421. if (width < 8 || width > 0x7fff) {
  79422. throw "HDR Bad header format, unsupported size";
  79423. }
  79424. lineIndex += (line.length + 1);
  79425. return {
  79426. height: height,
  79427. width: width,
  79428. dataPosition: lineIndex
  79429. };
  79430. };
  79431. /**
  79432. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79433. * This RGBE texture needs to store the information as a panorama.
  79434. *
  79435. * More information on this format are available here:
  79436. * https://en.wikipedia.org/wiki/RGBE_image_format
  79437. *
  79438. * @param buffer The binary file stored in an array buffer.
  79439. * @param size The expected size of the extracted cubemap.
  79440. * @return The Cube Map information.
  79441. */
  79442. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79443. var uint8array = new Uint8Array(buffer);
  79444. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79445. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79446. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  79447. return cubeMapData;
  79448. };
  79449. /**
  79450. * Returns the pixels data extracted from an RGBE texture.
  79451. * This pixels will be stored left to right up to down in the R G B order in one array.
  79452. *
  79453. * More information on this format are available here:
  79454. * https://en.wikipedia.org/wiki/RGBE_image_format
  79455. *
  79456. * @param uint8array The binary file stored in an array buffer.
  79457. * @param hdrInfo The header information of the file.
  79458. * @return The pixels data in RGB right to left up to down order.
  79459. */
  79460. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  79461. // Keep for multi format supports.
  79462. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79463. };
  79464. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  79465. var num_scanlines = hdrInfo.height;
  79466. var scanline_width = hdrInfo.width;
  79467. var a, b, c, d, count;
  79468. var dataIndex = hdrInfo.dataPosition;
  79469. var index = 0, endIndex = 0, i = 0;
  79470. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  79471. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  79472. // 3 channels of 4 bytes per pixel in float.
  79473. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  79474. var resultArray = new Float32Array(resultBuffer);
  79475. // read in each successive scanline
  79476. while (num_scanlines > 0) {
  79477. a = uint8array[dataIndex++];
  79478. b = uint8array[dataIndex++];
  79479. c = uint8array[dataIndex++];
  79480. d = uint8array[dataIndex++];
  79481. if (a != 2 || b != 2 || (c & 0x80)) {
  79482. // this file is not run length encoded
  79483. throw "HDR Bad header format, not RLE";
  79484. }
  79485. if (((c << 8) | d) != scanline_width) {
  79486. throw "HDR Bad header format, wrong scan line width";
  79487. }
  79488. index = 0;
  79489. // read each of the four channels for the scanline into the buffer
  79490. for (i = 0; i < 4; i++) {
  79491. endIndex = (i + 1) * scanline_width;
  79492. while (index < endIndex) {
  79493. a = uint8array[dataIndex++];
  79494. b = uint8array[dataIndex++];
  79495. if (a > 128) {
  79496. // a run of the same value
  79497. count = a - 128;
  79498. if ((count == 0) || (count > endIndex - index)) {
  79499. throw "HDR Bad Format, bad scanline data (run)";
  79500. }
  79501. while (count-- > 0) {
  79502. scanLineArray[index++] = b;
  79503. }
  79504. }
  79505. else {
  79506. // a non-run
  79507. count = a;
  79508. if ((count == 0) || (count > endIndex - index)) {
  79509. throw "HDR Bad Format, bad scanline data (non-run)";
  79510. }
  79511. scanLineArray[index++] = b;
  79512. if (--count > 0) {
  79513. for (var j = 0; j < count; j++) {
  79514. scanLineArray[index++] = uint8array[dataIndex++];
  79515. }
  79516. }
  79517. }
  79518. }
  79519. }
  79520. // now convert data from buffer into floats
  79521. for (i = 0; i < scanline_width; i++) {
  79522. a = scanLineArray[i];
  79523. b = scanLineArray[i + scanline_width];
  79524. c = scanLineArray[i + 2 * scanline_width];
  79525. d = scanLineArray[i + 3 * scanline_width];
  79526. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  79527. }
  79528. num_scanlines--;
  79529. }
  79530. return resultArray;
  79531. };
  79532. return HDRTools;
  79533. }());
  79534. BABYLON.HDRTools = HDRTools;
  79535. })(BABYLON || (BABYLON = {}));
  79536. //# sourceMappingURL=babylon.hdr.js.map
  79537. var BABYLON;
  79538. (function (BABYLON) {
  79539. /**
  79540. * This represents a texture coming from an HDR input.
  79541. *
  79542. * The only supported format is currently panorama picture stored in RGBE format.
  79543. * Example of such files can be found on HDRLib: http://hdrlib.com/
  79544. */
  79545. var HDRCubeTexture = /** @class */ (function (_super) {
  79546. __extends(HDRCubeTexture, _super);
  79547. /**
  79548. * Instantiates an HDRTexture from the following parameters.
  79549. *
  79550. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  79551. * @param scene The scene the texture will be used in
  79552. * @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.
  79553. * @param noMipmap Forces to not generate the mipmap if true
  79554. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  79555. * @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)
  79556. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  79557. */
  79558. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  79559. if (noMipmap === void 0) { noMipmap = false; }
  79560. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79561. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79562. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79563. if (onLoad === void 0) { onLoad = null; }
  79564. if (onError === void 0) { onError = null; }
  79565. var _this = _super.call(this, scene) || this;
  79566. _this._useInGammaSpace = false;
  79567. _this._generateHarmonics = true;
  79568. _this._isBABYLONPreprocessed = false;
  79569. _this._onLoad = null;
  79570. _this._onError = null;
  79571. /**
  79572. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  79573. */
  79574. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  79575. /**
  79576. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  79577. * This is usefull at run time to apply the good shader.
  79578. */
  79579. _this.isPMREM = false;
  79580. _this._isBlocking = true;
  79581. _this._rotationY = 0;
  79582. /**
  79583. * Gets or sets the center of the bounding box associated with the cube texture
  79584. * It must define where the camera used to render the texture was set
  79585. */
  79586. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  79587. if (!url) {
  79588. return _this;
  79589. }
  79590. _this.name = url;
  79591. _this.url = url;
  79592. _this.hasAlpha = false;
  79593. _this.isCube = true;
  79594. _this._textureMatrix = BABYLON.Matrix.Identity();
  79595. _this._onLoad = onLoad;
  79596. _this._onError = onError;
  79597. _this.gammaSpace = false;
  79598. var caps = scene.getEngine().getCaps();
  79599. if (size) {
  79600. _this._isBABYLONPreprocessed = false;
  79601. _this._noMipmap = noMipmap;
  79602. _this._size = size;
  79603. _this._useInGammaSpace = useInGammaSpace;
  79604. _this._usePMREMGenerator = usePMREMGenerator &&
  79605. caps.textureLOD &&
  79606. caps.textureFloat &&
  79607. !_this._useInGammaSpace;
  79608. }
  79609. else {
  79610. _this._isBABYLONPreprocessed = true;
  79611. _this._noMipmap = false;
  79612. _this._useInGammaSpace = false;
  79613. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  79614. !_this._useInGammaSpace;
  79615. }
  79616. _this.isPMREM = _this._usePMREMGenerator;
  79617. _this._texture = _this._getFromCache(url, _this._noMipmap);
  79618. if (!_this._texture) {
  79619. if (!scene.useDelayedTextureLoading) {
  79620. _this.loadTexture();
  79621. }
  79622. else {
  79623. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79624. }
  79625. }
  79626. return _this;
  79627. }
  79628. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  79629. /**
  79630. * Gets wether or not the texture is blocking during loading.
  79631. */
  79632. get: function () {
  79633. return this._isBlocking;
  79634. },
  79635. /**
  79636. * Sets wether or not the texture is blocking during loading.
  79637. */
  79638. set: function (value) {
  79639. this._isBlocking = value;
  79640. },
  79641. enumerable: true,
  79642. configurable: true
  79643. });
  79644. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  79645. /**
  79646. * Gets texture matrix rotation angle around Y axis radians.
  79647. */
  79648. get: function () {
  79649. return this._rotationY;
  79650. },
  79651. /**
  79652. * Sets texture matrix rotation angle around Y axis in radians.
  79653. */
  79654. set: function (value) {
  79655. this._rotationY = value;
  79656. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  79657. },
  79658. enumerable: true,
  79659. configurable: true
  79660. });
  79661. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  79662. get: function () {
  79663. return this._boundingBoxSize;
  79664. },
  79665. /**
  79666. * Gets or sets the size of the bounding box associated with the cube texture
  79667. * When defined, the cubemap will switch to local mode
  79668. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  79669. * @example https://www.babylonjs-playground.com/#RNASML
  79670. */
  79671. set: function (value) {
  79672. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  79673. return;
  79674. }
  79675. this._boundingBoxSize = value;
  79676. var scene = this.getScene();
  79677. if (scene) {
  79678. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  79679. }
  79680. },
  79681. enumerable: true,
  79682. configurable: true
  79683. });
  79684. /**
  79685. * Occurs when the file is a preprocessed .babylon.hdr file.
  79686. */
  79687. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  79688. var _this = this;
  79689. var mipLevels = 0;
  79690. var floatArrayView = null;
  79691. var scene = this.getScene();
  79692. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  79693. var mips = new Array();
  79694. if (!floatArrayView) {
  79695. return mips;
  79696. }
  79697. var startIndex = 30;
  79698. for (var level = 0; level < mipLevels; level++) {
  79699. mips.push([]);
  79700. // Fill each pixel of the mip level.
  79701. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  79702. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79703. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  79704. mips[level].push(faceData);
  79705. startIndex += faceSize;
  79706. }
  79707. }
  79708. return mips;
  79709. } : null;
  79710. var callback = function (buffer) {
  79711. var scene = _this.getScene();
  79712. if (!scene) {
  79713. return null;
  79714. }
  79715. // Create Native Array Views
  79716. var intArrayView = new Int32Array(buffer);
  79717. floatArrayView = new Float32Array(buffer);
  79718. // Fill header.
  79719. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  79720. _this._size = intArrayView[1]; // CubeMap max mip face size.
  79721. // Update Texture Information.
  79722. if (!_this._texture) {
  79723. return null;
  79724. }
  79725. _this._texture.updateSize(_this._size, _this._size);
  79726. // Fill polynomial information.
  79727. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  79728. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  79729. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  79730. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  79731. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  79732. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  79733. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  79734. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  79735. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  79736. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  79737. _this.sphericalPolynomial = sphericalPolynomial;
  79738. // Fill pixel data.
  79739. mipLevels = intArrayView[29]; // Number of mip levels.
  79740. var startIndex = 30;
  79741. var data = [];
  79742. var faceSize = Math.pow(_this._size, 2) * 3;
  79743. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79744. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  79745. startIndex += faceSize;
  79746. }
  79747. var results = [];
  79748. var byteArray = null;
  79749. // Push each faces.
  79750. for (var k = 0; k < 6; k++) {
  79751. var dataFace = null;
  79752. // To be deprecated.
  79753. if (version === 1) {
  79754. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  79755. dataFace = data[j];
  79756. }
  79757. // If special cases.
  79758. if (!mipmapGenerator && dataFace) {
  79759. if (!scene.getEngine().getCaps().textureFloat) {
  79760. // 3 channels of 1 bytes per pixel in bytes.
  79761. var byteBuffer = new ArrayBuffer(faceSize);
  79762. byteArray = new Uint8Array(byteBuffer);
  79763. }
  79764. for (var i = 0; i < _this._size * _this._size; i++) {
  79765. // Put in gamma space if requested.
  79766. if (_this._useInGammaSpace) {
  79767. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79768. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79769. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79770. }
  79771. // Convert to int texture for fallback.
  79772. if (byteArray) {
  79773. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79774. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79775. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79776. // May use luminance instead if the result is not accurate.
  79777. var max = Math.max(Math.max(r, g), b);
  79778. if (max > 255) {
  79779. var scale = 255 / max;
  79780. r *= scale;
  79781. g *= scale;
  79782. b *= scale;
  79783. }
  79784. byteArray[(i * 3) + 0] = r;
  79785. byteArray[(i * 3) + 1] = g;
  79786. byteArray[(i * 3) + 2] = b;
  79787. }
  79788. }
  79789. }
  79790. // Fill the array accordingly.
  79791. if (byteArray) {
  79792. results.push(byteArray);
  79793. }
  79794. else {
  79795. results.push(dataFace);
  79796. }
  79797. }
  79798. return results;
  79799. };
  79800. if (scene) {
  79801. 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);
  79802. }
  79803. };
  79804. /**
  79805. * Occurs when the file is raw .hdr file.
  79806. */
  79807. HDRCubeTexture.prototype.loadHDRTexture = function () {
  79808. var _this = this;
  79809. var callback = function (buffer) {
  79810. var scene = _this.getScene();
  79811. if (!scene) {
  79812. return null;
  79813. }
  79814. // Extract the raw linear data.
  79815. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  79816. // Generate harmonics if needed.
  79817. if (_this._generateHarmonics) {
  79818. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  79819. _this.sphericalPolynomial = sphericalPolynomial;
  79820. }
  79821. var results = [];
  79822. var byteArray = null;
  79823. // Push each faces.
  79824. for (var j = 0; j < 6; j++) {
  79825. // Create uintarray fallback.
  79826. if (!scene.getEngine().getCaps().textureFloat) {
  79827. // 3 channels of 1 bytes per pixel in bytes.
  79828. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  79829. byteArray = new Uint8Array(byteBuffer);
  79830. }
  79831. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  79832. // If special cases.
  79833. if (_this._useInGammaSpace || byteArray) {
  79834. for (var i = 0; i < _this._size * _this._size; i++) {
  79835. // Put in gamma space if requested.
  79836. if (_this._useInGammaSpace) {
  79837. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79838. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79839. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79840. }
  79841. // Convert to int texture for fallback.
  79842. if (byteArray) {
  79843. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79844. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79845. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79846. // May use luminance instead if the result is not accurate.
  79847. var max = Math.max(Math.max(r, g), b);
  79848. if (max > 255) {
  79849. var scale = 255 / max;
  79850. r *= scale;
  79851. g *= scale;
  79852. b *= scale;
  79853. }
  79854. byteArray[(i * 3) + 0] = r;
  79855. byteArray[(i * 3) + 1] = g;
  79856. byteArray[(i * 3) + 2] = b;
  79857. }
  79858. }
  79859. }
  79860. if (byteArray) {
  79861. results.push(byteArray);
  79862. }
  79863. else {
  79864. results.push(dataFace);
  79865. }
  79866. }
  79867. return results;
  79868. };
  79869. var mipmapGenerator = null;
  79870. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  79871. // if (!this._noMipmap &&
  79872. // this._usePMREMGenerator) {
  79873. // mipmapGenerator = (data: ArrayBufferView[]) => {
  79874. // // Custom setup of the generator matching with the PBR shader values.
  79875. // var generator = new BABYLON.PMREMGenerator(data,
  79876. // this._size,
  79877. // this._size,
  79878. // 0,
  79879. // 3,
  79880. // this.getScene().getEngine().getCaps().textureFloat,
  79881. // 2048,
  79882. // 0.25,
  79883. // false,
  79884. // true);
  79885. // return generator.filterCubeMap();
  79886. // };
  79887. // }
  79888. var scene = this.getScene();
  79889. if (scene) {
  79890. 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);
  79891. }
  79892. };
  79893. /**
  79894. * Starts the loading process of the texture.
  79895. */
  79896. HDRCubeTexture.prototype.loadTexture = function () {
  79897. if (this._isBABYLONPreprocessed) {
  79898. this.loadBabylonTexture();
  79899. }
  79900. else {
  79901. this.loadHDRTexture();
  79902. }
  79903. };
  79904. HDRCubeTexture.prototype.clone = function () {
  79905. var scene = this.getScene();
  79906. if (!scene) {
  79907. return this;
  79908. }
  79909. var size = (this._isBABYLONPreprocessed ? null : this._size);
  79910. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  79911. // Base texture
  79912. newTexture.level = this.level;
  79913. newTexture.wrapU = this.wrapU;
  79914. newTexture.wrapV = this.wrapV;
  79915. newTexture.coordinatesIndex = this.coordinatesIndex;
  79916. newTexture.coordinatesMode = this.coordinatesMode;
  79917. return newTexture;
  79918. };
  79919. // Methods
  79920. HDRCubeTexture.prototype.delayLoad = function () {
  79921. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79922. return;
  79923. }
  79924. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79925. this._texture = this._getFromCache(this.url, this._noMipmap);
  79926. if (!this._texture) {
  79927. this.loadTexture();
  79928. }
  79929. };
  79930. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  79931. return this._textureMatrix;
  79932. };
  79933. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  79934. this._textureMatrix = value;
  79935. };
  79936. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79937. var texture = null;
  79938. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79939. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  79940. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  79941. texture.name = parsedTexture.name;
  79942. texture.hasAlpha = parsedTexture.hasAlpha;
  79943. texture.level = parsedTexture.level;
  79944. texture.coordinatesMode = parsedTexture.coordinatesMode;
  79945. texture.isBlocking = parsedTexture.isBlocking;
  79946. }
  79947. if (texture) {
  79948. if (parsedTexture.boundingBoxPosition) {
  79949. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  79950. }
  79951. if (parsedTexture.boundingBoxSize) {
  79952. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  79953. }
  79954. if (parsedTexture.rotationY) {
  79955. texture.rotationY = parsedTexture.rotationY;
  79956. }
  79957. }
  79958. return texture;
  79959. };
  79960. HDRCubeTexture.prototype.serialize = function () {
  79961. if (!this.name) {
  79962. return null;
  79963. }
  79964. var serializationObject = {};
  79965. serializationObject.name = this.name;
  79966. serializationObject.hasAlpha = this.hasAlpha;
  79967. serializationObject.isCube = true;
  79968. serializationObject.level = this.level;
  79969. serializationObject.size = this._size;
  79970. serializationObject.coordinatesMode = this.coordinatesMode;
  79971. serializationObject.useInGammaSpace = this._useInGammaSpace;
  79972. serializationObject.generateHarmonics = this._generateHarmonics;
  79973. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  79974. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  79975. serializationObject.customType = "BABYLON.HDRCubeTexture";
  79976. serializationObject.noMipmap = this._noMipmap;
  79977. serializationObject.isBlocking = this._isBlocking;
  79978. serializationObject.rotationY = this._rotationY;
  79979. return serializationObject;
  79980. };
  79981. /**
  79982. * Saves as a file the data contained in the texture in a binary format.
  79983. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79984. * as the spherical used in the lighting.
  79985. * @param url The HDR file url.
  79986. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79987. * @param onError Method called if any error happens during download.
  79988. * @return The packed binary data.
  79989. */
  79990. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  79991. if (onError === void 0) { onError = null; }
  79992. var callback = function (buffer) {
  79993. var data = new Blob([buffer], { type: 'application/octet-stream' });
  79994. // Returns a URL you can use as a href.
  79995. var objUrl = window.URL.createObjectURL(data);
  79996. // Simulates a link to it and click to dowload.
  79997. var a = document.createElement("a");
  79998. document.body.appendChild(a);
  79999. a.style.display = "none";
  80000. a.href = objUrl;
  80001. a.download = "envmap.babylon.hdr";
  80002. a.click();
  80003. };
  80004. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  80005. };
  80006. /**
  80007. * Serializes the data contained in the texture in a binary format.
  80008. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  80009. * as the spherical used in the lighting.
  80010. * @param url The HDR file url.
  80011. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  80012. * @param onError Method called if any error happens during download.
  80013. * @return The packed binary data.
  80014. */
  80015. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  80016. if (onError === void 0) { onError = null; }
  80017. // Needs the url tho create the texture.
  80018. if (!url) {
  80019. return;
  80020. }
  80021. // Check Power of two size.
  80022. if (!BABYLON.Tools.IsExponentOfTwo(size)) { // Need to check engine.needPOTTextures
  80023. return;
  80024. }
  80025. // Coming Back in 3.x.
  80026. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  80027. };
  80028. HDRCubeTexture._facesMapping = [
  80029. "right",
  80030. "left",
  80031. "up",
  80032. "down",
  80033. "front",
  80034. "back"
  80035. ];
  80036. return HDRCubeTexture;
  80037. }(BABYLON.BaseTexture));
  80038. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80039. })(BABYLON || (BABYLON = {}));
  80040. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80041. var BABYLON;
  80042. (function (BABYLON) {
  80043. var IndexedVector2 = /** @class */ (function (_super) {
  80044. __extends(IndexedVector2, _super);
  80045. function IndexedVector2(original, index) {
  80046. var _this = _super.call(this, original.x, original.y) || this;
  80047. _this.index = index;
  80048. return _this;
  80049. }
  80050. return IndexedVector2;
  80051. }(BABYLON.Vector2));
  80052. var PolygonPoints = /** @class */ (function () {
  80053. function PolygonPoints() {
  80054. this.elements = new Array();
  80055. }
  80056. PolygonPoints.prototype.add = function (originalPoints) {
  80057. var _this = this;
  80058. var result = new Array();
  80059. originalPoints.forEach(function (point) {
  80060. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80061. var newPoint = new IndexedVector2(point, _this.elements.length);
  80062. result.push(newPoint);
  80063. _this.elements.push(newPoint);
  80064. }
  80065. });
  80066. return result;
  80067. };
  80068. PolygonPoints.prototype.computeBounds = function () {
  80069. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80070. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80071. this.elements.forEach(function (point) {
  80072. // x
  80073. if (point.x < lmin.x) {
  80074. lmin.x = point.x;
  80075. }
  80076. else if (point.x > lmax.x) {
  80077. lmax.x = point.x;
  80078. }
  80079. // y
  80080. if (point.y < lmin.y) {
  80081. lmin.y = point.y;
  80082. }
  80083. else if (point.y > lmax.y) {
  80084. lmax.y = point.y;
  80085. }
  80086. });
  80087. return {
  80088. min: lmin,
  80089. max: lmax,
  80090. width: lmax.x - lmin.x,
  80091. height: lmax.y - lmin.y
  80092. };
  80093. };
  80094. return PolygonPoints;
  80095. }());
  80096. var Polygon = /** @class */ (function () {
  80097. function Polygon() {
  80098. }
  80099. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80100. return [
  80101. new BABYLON.Vector2(xmin, ymin),
  80102. new BABYLON.Vector2(xmax, ymin),
  80103. new BABYLON.Vector2(xmax, ymax),
  80104. new BABYLON.Vector2(xmin, ymax)
  80105. ];
  80106. };
  80107. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80108. if (cx === void 0) { cx = 0; }
  80109. if (cy === void 0) { cy = 0; }
  80110. if (numberOfSides === void 0) { numberOfSides = 32; }
  80111. var result = new Array();
  80112. var angle = 0;
  80113. var increment = (Math.PI * 2) / numberOfSides;
  80114. for (var i = 0; i < numberOfSides; i++) {
  80115. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80116. angle -= increment;
  80117. }
  80118. return result;
  80119. };
  80120. Polygon.Parse = function (input) {
  80121. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80122. var i, result = [];
  80123. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80124. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80125. }
  80126. return result;
  80127. };
  80128. Polygon.StartingAt = function (x, y) {
  80129. return BABYLON.Path2.StartingAt(x, y);
  80130. };
  80131. return Polygon;
  80132. }());
  80133. BABYLON.Polygon = Polygon;
  80134. var PolygonMeshBuilder = /** @class */ (function () {
  80135. function PolygonMeshBuilder(name, contours, scene) {
  80136. this._points = new PolygonPoints();
  80137. this._outlinepoints = new PolygonPoints();
  80138. this._holes = new Array();
  80139. this._epoints = new Array();
  80140. this._eholes = new Array();
  80141. this._name = name;
  80142. this._scene = scene;
  80143. var points;
  80144. if (contours instanceof BABYLON.Path2) {
  80145. points = contours.getPoints();
  80146. }
  80147. else {
  80148. points = contours;
  80149. }
  80150. this._addToepoint(points);
  80151. this._points.add(points);
  80152. this._outlinepoints.add(points);
  80153. if (typeof earcut === 'undefined') {
  80154. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80155. }
  80156. }
  80157. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80158. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80159. var p = points_1[_i];
  80160. this._epoints.push(p.x, p.y);
  80161. }
  80162. };
  80163. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80164. this._points.add(hole);
  80165. var holepoints = new PolygonPoints();
  80166. holepoints.add(hole);
  80167. this._holes.push(holepoints);
  80168. this._eholes.push(this._epoints.length / 2);
  80169. this._addToepoint(hole);
  80170. return this;
  80171. };
  80172. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80173. var _this = this;
  80174. if (updatable === void 0) { updatable = false; }
  80175. if (depth === void 0) { depth = 0; }
  80176. var result = new BABYLON.Mesh(this._name, this._scene);
  80177. var normals = new Array();
  80178. var positions = new Array();
  80179. var uvs = new Array();
  80180. var bounds = this._points.computeBounds();
  80181. this._points.elements.forEach(function (p) {
  80182. normals.push(0, 1.0, 0);
  80183. positions.push(p.x, 0, p.y);
  80184. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80185. });
  80186. var indices = new Array();
  80187. var res = earcut(this._epoints, this._eholes, 2);
  80188. for (var i = 0; i < res.length; i++) {
  80189. indices.push(res[i]);
  80190. }
  80191. if (depth > 0) {
  80192. var positionscount = (positions.length / 3); //get the current pointcount
  80193. this._points.elements.forEach(function (p) {
  80194. normals.push(0, -1.0, 0);
  80195. positions.push(p.x, -depth, p.y);
  80196. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80197. });
  80198. var totalCount = indices.length;
  80199. for (var i = 0; i < totalCount; i += 3) {
  80200. var i0 = indices[i + 0];
  80201. var i1 = indices[i + 1];
  80202. var i2 = indices[i + 2];
  80203. indices.push(i2 + positionscount);
  80204. indices.push(i1 + positionscount);
  80205. indices.push(i0 + positionscount);
  80206. }
  80207. //Add the sides
  80208. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80209. this._holes.forEach(function (hole) {
  80210. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80211. });
  80212. }
  80213. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80214. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80215. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80216. result.setIndices(indices);
  80217. return result;
  80218. };
  80219. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80220. var StartIndex = positions.length / 3;
  80221. var ulength = 0;
  80222. for (var i = 0; i < points.elements.length; i++) {
  80223. var p = points.elements[i];
  80224. var p1;
  80225. if ((i + 1) > points.elements.length - 1) {
  80226. p1 = points.elements[0];
  80227. }
  80228. else {
  80229. p1 = points.elements[i + 1];
  80230. }
  80231. positions.push(p.x, 0, p.y);
  80232. positions.push(p.x, -depth, p.y);
  80233. positions.push(p1.x, 0, p1.y);
  80234. positions.push(p1.x, -depth, p1.y);
  80235. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80236. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80237. var v3 = v2.subtract(v1);
  80238. var v4 = new BABYLON.Vector3(0, 1, 0);
  80239. var vn = BABYLON.Vector3.Cross(v3, v4);
  80240. vn = vn.normalize();
  80241. uvs.push(ulength / bounds.width, 0);
  80242. uvs.push(ulength / bounds.width, 1);
  80243. ulength += v3.length();
  80244. uvs.push((ulength / bounds.width), 0);
  80245. uvs.push((ulength / bounds.width), 1);
  80246. if (!flip) {
  80247. normals.push(-vn.x, -vn.y, -vn.z);
  80248. normals.push(-vn.x, -vn.y, -vn.z);
  80249. normals.push(-vn.x, -vn.y, -vn.z);
  80250. normals.push(-vn.x, -vn.y, -vn.z);
  80251. indices.push(StartIndex);
  80252. indices.push(StartIndex + 1);
  80253. indices.push(StartIndex + 2);
  80254. indices.push(StartIndex + 1);
  80255. indices.push(StartIndex + 3);
  80256. indices.push(StartIndex + 2);
  80257. }
  80258. else {
  80259. normals.push(vn.x, vn.y, vn.z);
  80260. normals.push(vn.x, vn.y, vn.z);
  80261. normals.push(vn.x, vn.y, vn.z);
  80262. normals.push(vn.x, vn.y, vn.z);
  80263. indices.push(StartIndex);
  80264. indices.push(StartIndex + 2);
  80265. indices.push(StartIndex + 1);
  80266. indices.push(StartIndex + 1);
  80267. indices.push(StartIndex + 2);
  80268. indices.push(StartIndex + 3);
  80269. }
  80270. StartIndex += 4;
  80271. }
  80272. ;
  80273. };
  80274. return PolygonMeshBuilder;
  80275. }());
  80276. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80277. })(BABYLON || (BABYLON = {}));
  80278. //# sourceMappingURL=babylon.polygonMesh.js.map
  80279. var BABYLON;
  80280. (function (BABYLON) {
  80281. // Unique ID when we import meshes from Babylon to CSG
  80282. var currentCSGMeshId = 0;
  80283. // # class Vertex
  80284. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80285. // one to provide additional features like texture coordinates and vertex
  80286. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80287. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80288. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80289. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80290. // is not used anywhere else.
  80291. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80292. var Vertex = /** @class */ (function () {
  80293. function Vertex(pos, normal, uv) {
  80294. this.pos = pos;
  80295. this.normal = normal;
  80296. this.uv = uv;
  80297. }
  80298. Vertex.prototype.clone = function () {
  80299. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80300. };
  80301. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80302. // orientation of a polygon is flipped.
  80303. Vertex.prototype.flip = function () {
  80304. this.normal = this.normal.scale(-1);
  80305. };
  80306. // Create a new vertex between this vertex and `other` by linearly
  80307. // interpolating all properties using a parameter of `t`. Subclasses should
  80308. // override this to interpolate additional properties.
  80309. Vertex.prototype.interpolate = function (other, t) {
  80310. 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));
  80311. };
  80312. return Vertex;
  80313. }());
  80314. // # class Plane
  80315. // Represents a plane in 3D space.
  80316. var Plane = /** @class */ (function () {
  80317. function Plane(normal, w) {
  80318. this.normal = normal;
  80319. this.w = w;
  80320. }
  80321. Plane.FromPoints = function (a, b, c) {
  80322. var v0 = c.subtract(a);
  80323. var v1 = b.subtract(a);
  80324. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80325. return null;
  80326. }
  80327. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80328. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80329. };
  80330. Plane.prototype.clone = function () {
  80331. return new Plane(this.normal.clone(), this.w);
  80332. };
  80333. Plane.prototype.flip = function () {
  80334. this.normal.scaleInPlace(-1);
  80335. this.w = -this.w;
  80336. };
  80337. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80338. // fragments in the appropriate lists. Coplanar polygons go into either
  80339. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80340. // respect to this plane. Polygons in front or in back of this plane go into
  80341. // either `front` or `back`.
  80342. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80343. var COPLANAR = 0;
  80344. var FRONT = 1;
  80345. var BACK = 2;
  80346. var SPANNING = 3;
  80347. // Classify each point as well as the entire polygon into one of the above
  80348. // four classes.
  80349. var polygonType = 0;
  80350. var types = [];
  80351. var i;
  80352. var t;
  80353. for (i = 0; i < polygon.vertices.length; i++) {
  80354. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80355. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80356. polygonType |= type;
  80357. types.push(type);
  80358. }
  80359. // Put the polygon in the correct list, splitting it when necessary.
  80360. switch (polygonType) {
  80361. case COPLANAR:
  80362. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80363. break;
  80364. case FRONT:
  80365. front.push(polygon);
  80366. break;
  80367. case BACK:
  80368. back.push(polygon);
  80369. break;
  80370. case SPANNING:
  80371. var f = [], b = [];
  80372. for (i = 0; i < polygon.vertices.length; i++) {
  80373. var j = (i + 1) % polygon.vertices.length;
  80374. var ti = types[i], tj = types[j];
  80375. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80376. if (ti !== BACK)
  80377. f.push(vi);
  80378. if (ti !== FRONT)
  80379. b.push(ti !== BACK ? vi.clone() : vi);
  80380. if ((ti | tj) === SPANNING) {
  80381. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80382. var v = vi.interpolate(vj, t);
  80383. f.push(v);
  80384. b.push(v.clone());
  80385. }
  80386. }
  80387. var poly;
  80388. if (f.length >= 3) {
  80389. poly = new Polygon(f, polygon.shared);
  80390. if (poly.plane)
  80391. front.push(poly);
  80392. }
  80393. if (b.length >= 3) {
  80394. poly = new Polygon(b, polygon.shared);
  80395. if (poly.plane)
  80396. back.push(poly);
  80397. }
  80398. break;
  80399. }
  80400. };
  80401. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80402. // point is on the plane.
  80403. Plane.EPSILON = 1e-5;
  80404. return Plane;
  80405. }());
  80406. // # class Polygon
  80407. // Represents a convex polygon. The vertices used to initialize a polygon must
  80408. // be coplanar and form a convex loop.
  80409. //
  80410. // Each convex polygon has a `shared` property, which is shared between all
  80411. // polygons that are clones of each other or were split from the same polygon.
  80412. // This can be used to define per-polygon properties (such as surface color).
  80413. var Polygon = /** @class */ (function () {
  80414. function Polygon(vertices, shared) {
  80415. this.vertices = vertices;
  80416. this.shared = shared;
  80417. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80418. }
  80419. Polygon.prototype.clone = function () {
  80420. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80421. return new Polygon(vertices, this.shared);
  80422. };
  80423. Polygon.prototype.flip = function () {
  80424. this.vertices.reverse().map(function (v) { v.flip(); });
  80425. this.plane.flip();
  80426. };
  80427. return Polygon;
  80428. }());
  80429. // # class Node
  80430. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80431. // by picking a polygon to split along. That polygon (and all other coplanar
  80432. // polygons) are added directly to that node and the other polygons are added to
  80433. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80434. // no distinction between internal and leaf nodes.
  80435. var Node = /** @class */ (function () {
  80436. function Node(polygons) {
  80437. this.plane = null;
  80438. this.front = null;
  80439. this.back = null;
  80440. this.polygons = new Array();
  80441. if (polygons) {
  80442. this.build(polygons);
  80443. }
  80444. }
  80445. Node.prototype.clone = function () {
  80446. var node = new Node();
  80447. node.plane = this.plane && this.plane.clone();
  80448. node.front = this.front && this.front.clone();
  80449. node.back = this.back && this.back.clone();
  80450. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80451. return node;
  80452. };
  80453. // Convert solid space to empty space and empty space to solid space.
  80454. Node.prototype.invert = function () {
  80455. for (var i = 0; i < this.polygons.length; i++) {
  80456. this.polygons[i].flip();
  80457. }
  80458. if (this.plane) {
  80459. this.plane.flip();
  80460. }
  80461. if (this.front) {
  80462. this.front.invert();
  80463. }
  80464. if (this.back) {
  80465. this.back.invert();
  80466. }
  80467. var temp = this.front;
  80468. this.front = this.back;
  80469. this.back = temp;
  80470. };
  80471. // Recursively remove all polygons in `polygons` that are inside this BSP
  80472. // tree.
  80473. Node.prototype.clipPolygons = function (polygons) {
  80474. if (!this.plane)
  80475. return polygons.slice();
  80476. var front = new Array(), back = new Array();
  80477. for (var i = 0; i < polygons.length; i++) {
  80478. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80479. }
  80480. if (this.front) {
  80481. front = this.front.clipPolygons(front);
  80482. }
  80483. if (this.back) {
  80484. back = this.back.clipPolygons(back);
  80485. }
  80486. else {
  80487. back = [];
  80488. }
  80489. return front.concat(back);
  80490. };
  80491. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80492. // `bsp`.
  80493. Node.prototype.clipTo = function (bsp) {
  80494. this.polygons = bsp.clipPolygons(this.polygons);
  80495. if (this.front)
  80496. this.front.clipTo(bsp);
  80497. if (this.back)
  80498. this.back.clipTo(bsp);
  80499. };
  80500. // Return a list of all polygons in this BSP tree.
  80501. Node.prototype.allPolygons = function () {
  80502. var polygons = this.polygons.slice();
  80503. if (this.front)
  80504. polygons = polygons.concat(this.front.allPolygons());
  80505. if (this.back)
  80506. polygons = polygons.concat(this.back.allPolygons());
  80507. return polygons;
  80508. };
  80509. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80510. // new polygons are filtered down to the bottom of the tree and become new
  80511. // nodes there. Each set of polygons is partitioned using the first polygon
  80512. // (no heuristic is used to pick a good split).
  80513. Node.prototype.build = function (polygons) {
  80514. if (!polygons.length)
  80515. return;
  80516. if (!this.plane)
  80517. this.plane = polygons[0].plane.clone();
  80518. var front = new Array(), back = new Array();
  80519. for (var i = 0; i < polygons.length; i++) {
  80520. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80521. }
  80522. if (front.length) {
  80523. if (!this.front)
  80524. this.front = new Node();
  80525. this.front.build(front);
  80526. }
  80527. if (back.length) {
  80528. if (!this.back)
  80529. this.back = new Node();
  80530. this.back.build(back);
  80531. }
  80532. };
  80533. return Node;
  80534. }());
  80535. var CSG = /** @class */ (function () {
  80536. function CSG() {
  80537. this.polygons = new Array();
  80538. }
  80539. // Convert BABYLON.Mesh to BABYLON.CSG
  80540. CSG.FromMesh = function (mesh) {
  80541. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80542. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80543. if (mesh instanceof BABYLON.Mesh) {
  80544. mesh.computeWorldMatrix(true);
  80545. matrix = mesh.getWorldMatrix();
  80546. meshPosition = mesh.position.clone();
  80547. meshRotation = mesh.rotation.clone();
  80548. if (mesh.rotationQuaternion) {
  80549. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80550. }
  80551. meshScaling = mesh.scaling.clone();
  80552. }
  80553. else {
  80554. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80555. }
  80556. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80557. var subMeshes = mesh.subMeshes;
  80558. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80559. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80560. vertices = [];
  80561. for (var j = 0; j < 3; j++) {
  80562. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80563. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80564. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80565. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80566. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80567. vertex = new Vertex(position, normal, uv);
  80568. vertices.push(vertex);
  80569. }
  80570. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80571. // To handle the case of degenerated triangle
  80572. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80573. if (polygon.plane)
  80574. polygons.push(polygon);
  80575. }
  80576. }
  80577. var csg = CSG.FromPolygons(polygons);
  80578. csg.matrix = matrix;
  80579. csg.position = meshPosition;
  80580. csg.rotation = meshRotation;
  80581. csg.scaling = meshScaling;
  80582. csg.rotationQuaternion = meshRotationQuaternion;
  80583. currentCSGMeshId++;
  80584. return csg;
  80585. };
  80586. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80587. CSG.FromPolygons = function (polygons) {
  80588. var csg = new CSG();
  80589. csg.polygons = polygons;
  80590. return csg;
  80591. };
  80592. CSG.prototype.clone = function () {
  80593. var csg = new CSG();
  80594. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80595. csg.copyTransformAttributes(this);
  80596. return csg;
  80597. };
  80598. CSG.prototype.union = function (csg) {
  80599. var a = new Node(this.clone().polygons);
  80600. var b = new Node(csg.clone().polygons);
  80601. a.clipTo(b);
  80602. b.clipTo(a);
  80603. b.invert();
  80604. b.clipTo(a);
  80605. b.invert();
  80606. a.build(b.allPolygons());
  80607. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80608. };
  80609. CSG.prototype.unionInPlace = function (csg) {
  80610. var a = new Node(this.polygons);
  80611. var b = new Node(csg.polygons);
  80612. a.clipTo(b);
  80613. b.clipTo(a);
  80614. b.invert();
  80615. b.clipTo(a);
  80616. b.invert();
  80617. a.build(b.allPolygons());
  80618. this.polygons = a.allPolygons();
  80619. };
  80620. CSG.prototype.subtract = function (csg) {
  80621. var a = new Node(this.clone().polygons);
  80622. var b = new Node(csg.clone().polygons);
  80623. a.invert();
  80624. a.clipTo(b);
  80625. b.clipTo(a);
  80626. b.invert();
  80627. b.clipTo(a);
  80628. b.invert();
  80629. a.build(b.allPolygons());
  80630. a.invert();
  80631. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80632. };
  80633. CSG.prototype.subtractInPlace = function (csg) {
  80634. var a = new Node(this.polygons);
  80635. var b = new Node(csg.polygons);
  80636. a.invert();
  80637. a.clipTo(b);
  80638. b.clipTo(a);
  80639. b.invert();
  80640. b.clipTo(a);
  80641. b.invert();
  80642. a.build(b.allPolygons());
  80643. a.invert();
  80644. this.polygons = a.allPolygons();
  80645. };
  80646. CSG.prototype.intersect = function (csg) {
  80647. var a = new Node(this.clone().polygons);
  80648. var b = new Node(csg.clone().polygons);
  80649. a.invert();
  80650. b.clipTo(a);
  80651. b.invert();
  80652. a.clipTo(b);
  80653. b.clipTo(a);
  80654. a.build(b.allPolygons());
  80655. a.invert();
  80656. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80657. };
  80658. CSG.prototype.intersectInPlace = function (csg) {
  80659. var a = new Node(this.polygons);
  80660. var b = new Node(csg.polygons);
  80661. a.invert();
  80662. b.clipTo(a);
  80663. b.invert();
  80664. a.clipTo(b);
  80665. b.clipTo(a);
  80666. a.build(b.allPolygons());
  80667. a.invert();
  80668. this.polygons = a.allPolygons();
  80669. };
  80670. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  80671. // not modified.
  80672. CSG.prototype.inverse = function () {
  80673. var csg = this.clone();
  80674. csg.inverseInPlace();
  80675. return csg;
  80676. };
  80677. CSG.prototype.inverseInPlace = function () {
  80678. this.polygons.map(function (p) { p.flip(); });
  80679. };
  80680. // This is used to keep meshes transformations so they can be restored
  80681. // when we build back a Babylon Mesh
  80682. // NB : All CSG operations are performed in world coordinates
  80683. CSG.prototype.copyTransformAttributes = function (csg) {
  80684. this.matrix = csg.matrix;
  80685. this.position = csg.position;
  80686. this.rotation = csg.rotation;
  80687. this.scaling = csg.scaling;
  80688. this.rotationQuaternion = csg.rotationQuaternion;
  80689. return this;
  80690. };
  80691. // Build Raw mesh from CSG
  80692. // Coordinates here are in world space
  80693. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  80694. var matrix = this.matrix.clone();
  80695. matrix.invert();
  80696. 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;
  80697. if (keepSubMeshes) {
  80698. // Sort Polygons, since subMeshes are indices range
  80699. polygons.sort(function (a, b) {
  80700. if (a.shared.meshId === b.shared.meshId) {
  80701. return a.shared.subMeshId - b.shared.subMeshId;
  80702. }
  80703. else {
  80704. return a.shared.meshId - b.shared.meshId;
  80705. }
  80706. });
  80707. }
  80708. for (var i = 0, il = polygons.length; i < il; i++) {
  80709. polygon = polygons[i];
  80710. // Building SubMeshes
  80711. if (!subMesh_dict[polygon.shared.meshId]) {
  80712. subMesh_dict[polygon.shared.meshId] = {};
  80713. }
  80714. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  80715. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  80716. indexStart: +Infinity,
  80717. indexEnd: -Infinity,
  80718. materialIndex: polygon.shared.materialIndex
  80719. };
  80720. }
  80721. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  80722. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  80723. polygonIndices[0] = 0;
  80724. polygonIndices[1] = j - 1;
  80725. polygonIndices[2] = j;
  80726. for (var k = 0; k < 3; k++) {
  80727. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  80728. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  80729. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  80730. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  80731. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  80732. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  80733. // Check if 2 points can be merged
  80734. if (!(typeof vertex_idx !== 'undefined' &&
  80735. normals[vertex_idx * 3] === localNormal.x &&
  80736. normals[vertex_idx * 3 + 1] === localNormal.y &&
  80737. normals[vertex_idx * 3 + 2] === localNormal.z &&
  80738. uvs[vertex_idx * 2] === uv.x &&
  80739. uvs[vertex_idx * 2 + 1] === uv.y)) {
  80740. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  80741. uvs.push(uv.x, uv.y);
  80742. normals.push(normal.x, normal.y, normal.z);
  80743. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  80744. }
  80745. indices.push(vertex_idx);
  80746. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  80747. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  80748. currentIndex++;
  80749. }
  80750. }
  80751. }
  80752. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  80753. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  80754. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  80755. mesh.setIndices(indices, null);
  80756. if (keepSubMeshes) {
  80757. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  80758. var materialIndexOffset = 0, materialMaxIndex;
  80759. mesh.subMeshes = new Array();
  80760. for (var m in subMesh_dict) {
  80761. materialMaxIndex = -1;
  80762. for (var sm in subMesh_dict[m]) {
  80763. subMesh_obj = subMesh_dict[m][sm];
  80764. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  80765. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  80766. }
  80767. materialIndexOffset += ++materialMaxIndex;
  80768. }
  80769. }
  80770. return mesh;
  80771. };
  80772. // Build Mesh from CSG taking material and transforms into account
  80773. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  80774. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  80775. mesh.material = material;
  80776. mesh.position.copyFrom(this.position);
  80777. mesh.rotation.copyFrom(this.rotation);
  80778. if (this.rotationQuaternion) {
  80779. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  80780. }
  80781. mesh.scaling.copyFrom(this.scaling);
  80782. mesh.computeWorldMatrix(true);
  80783. return mesh;
  80784. };
  80785. return CSG;
  80786. }());
  80787. BABYLON.CSG = CSG;
  80788. })(BABYLON || (BABYLON = {}));
  80789. //# sourceMappingURL=babylon.csg.js.map
  80790. var BABYLON;
  80791. (function (BABYLON) {
  80792. var LensFlare = /** @class */ (function () {
  80793. function LensFlare(size, position, color, imgUrl, system) {
  80794. this.size = size;
  80795. this.position = position;
  80796. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  80797. this.color = color || new BABYLON.Color3(1, 1, 1);
  80798. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  80799. this._system = system;
  80800. system.lensFlares.push(this);
  80801. }
  80802. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  80803. return new LensFlare(size, position, color, imgUrl, system);
  80804. };
  80805. LensFlare.prototype.dispose = function () {
  80806. if (this.texture) {
  80807. this.texture.dispose();
  80808. }
  80809. // Remove from scene
  80810. var index = this._system.lensFlares.indexOf(this);
  80811. this._system.lensFlares.splice(index, 1);
  80812. };
  80813. ;
  80814. return LensFlare;
  80815. }());
  80816. BABYLON.LensFlare = LensFlare;
  80817. })(BABYLON || (BABYLON = {}));
  80818. //# sourceMappingURL=babylon.lensFlare.js.map
  80819. var BABYLON;
  80820. (function (BABYLON) {
  80821. var LensFlareSystem = /** @class */ (function () {
  80822. function LensFlareSystem(name, emitter, scene) {
  80823. this.name = name;
  80824. this.lensFlares = new Array();
  80825. this.borderLimit = 300;
  80826. this.viewportBorder = 0;
  80827. this.layerMask = 0x0FFFFFFF;
  80828. this._vertexBuffers = {};
  80829. this._isEnabled = true;
  80830. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80831. this._emitter = emitter;
  80832. this.id = name;
  80833. scene.lensFlareSystems.push(this);
  80834. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  80835. var engine = scene.getEngine();
  80836. // VBO
  80837. var vertices = [];
  80838. vertices.push(1, 1);
  80839. vertices.push(-1, 1);
  80840. vertices.push(-1, -1);
  80841. vertices.push(1, -1);
  80842. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80843. // Indices
  80844. var indices = [];
  80845. indices.push(0);
  80846. indices.push(1);
  80847. indices.push(2);
  80848. indices.push(0);
  80849. indices.push(2);
  80850. indices.push(3);
  80851. this._indexBuffer = engine.createIndexBuffer(indices);
  80852. // Effects
  80853. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  80854. }
  80855. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  80856. get: function () {
  80857. return this._isEnabled;
  80858. },
  80859. set: function (value) {
  80860. this._isEnabled = value;
  80861. },
  80862. enumerable: true,
  80863. configurable: true
  80864. });
  80865. LensFlareSystem.prototype.getScene = function () {
  80866. return this._scene;
  80867. };
  80868. LensFlareSystem.prototype.getEmitter = function () {
  80869. return this._emitter;
  80870. };
  80871. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  80872. this._emitter = newEmitter;
  80873. };
  80874. LensFlareSystem.prototype.getEmitterPosition = function () {
  80875. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  80876. };
  80877. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  80878. var position = this.getEmitterPosition();
  80879. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  80880. this._positionX = position.x;
  80881. this._positionY = position.y;
  80882. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  80883. if (this.viewportBorder > 0) {
  80884. globalViewport.x -= this.viewportBorder;
  80885. globalViewport.y -= this.viewportBorder;
  80886. globalViewport.width += this.viewportBorder * 2;
  80887. globalViewport.height += this.viewportBorder * 2;
  80888. position.x += this.viewportBorder;
  80889. position.y += this.viewportBorder;
  80890. this._positionX += this.viewportBorder;
  80891. this._positionY += this.viewportBorder;
  80892. }
  80893. if (position.z > 0) {
  80894. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  80895. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  80896. return true;
  80897. }
  80898. return true;
  80899. }
  80900. return false;
  80901. };
  80902. LensFlareSystem.prototype._isVisible = function () {
  80903. if (!this._isEnabled || !this._scene.activeCamera) {
  80904. return false;
  80905. }
  80906. var emitterPosition = this.getEmitterPosition();
  80907. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  80908. var distance = direction.length();
  80909. direction.normalize();
  80910. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  80911. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  80912. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  80913. };
  80914. LensFlareSystem.prototype.render = function () {
  80915. if (!this._effect.isReady() || !this._scene.activeCamera)
  80916. return false;
  80917. var engine = this._scene.getEngine();
  80918. var viewport = this._scene.activeCamera.viewport;
  80919. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  80920. // Position
  80921. if (!this.computeEffectivePosition(globalViewport)) {
  80922. return false;
  80923. }
  80924. // Visibility
  80925. if (!this._isVisible()) {
  80926. return false;
  80927. }
  80928. // Intensity
  80929. var awayX;
  80930. var awayY;
  80931. if (this._positionX < this.borderLimit + globalViewport.x) {
  80932. awayX = this.borderLimit + globalViewport.x - this._positionX;
  80933. }
  80934. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  80935. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  80936. }
  80937. else {
  80938. awayX = 0;
  80939. }
  80940. if (this._positionY < this.borderLimit + globalViewport.y) {
  80941. awayY = this.borderLimit + globalViewport.y - this._positionY;
  80942. }
  80943. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  80944. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  80945. }
  80946. else {
  80947. awayY = 0;
  80948. }
  80949. var away = (awayX > awayY) ? awayX : awayY;
  80950. away -= this.viewportBorder;
  80951. if (away > this.borderLimit) {
  80952. away = this.borderLimit;
  80953. }
  80954. var intensity = 1.0 - (away / this.borderLimit);
  80955. if (intensity < 0) {
  80956. return false;
  80957. }
  80958. if (intensity > 1.0) {
  80959. intensity = 1.0;
  80960. }
  80961. if (this.viewportBorder > 0) {
  80962. globalViewport.x += this.viewportBorder;
  80963. globalViewport.y += this.viewportBorder;
  80964. globalViewport.width -= this.viewportBorder * 2;
  80965. globalViewport.height -= this.viewportBorder * 2;
  80966. this._positionX -= this.viewportBorder;
  80967. this._positionY -= this.viewportBorder;
  80968. }
  80969. // Position
  80970. var centerX = globalViewport.x + globalViewport.width / 2;
  80971. var centerY = globalViewport.y + globalViewport.height / 2;
  80972. var distX = centerX - this._positionX;
  80973. var distY = centerY - this._positionY;
  80974. // Effects
  80975. engine.enableEffect(this._effect);
  80976. engine.setState(false);
  80977. engine.setDepthBuffer(false);
  80978. // VBOs
  80979. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80980. // Flares
  80981. for (var index = 0; index < this.lensFlares.length; index++) {
  80982. var flare = this.lensFlares[index];
  80983. engine.setAlphaMode(flare.alphaMode);
  80984. var x = centerX - (distX * flare.position);
  80985. var y = centerY - (distY * flare.position);
  80986. var cw = flare.size;
  80987. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  80988. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  80989. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  80990. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  80991. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  80992. // Texture
  80993. this._effect.setTexture("textureSampler", flare.texture);
  80994. // Color
  80995. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  80996. // Draw order
  80997. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80998. }
  80999. engine.setDepthBuffer(true);
  81000. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81001. return true;
  81002. };
  81003. LensFlareSystem.prototype.dispose = function () {
  81004. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81005. if (vertexBuffer) {
  81006. vertexBuffer.dispose();
  81007. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81008. }
  81009. if (this._indexBuffer) {
  81010. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81011. this._indexBuffer = null;
  81012. }
  81013. while (this.lensFlares.length) {
  81014. this.lensFlares[0].dispose();
  81015. }
  81016. // Remove from scene
  81017. var index = this._scene.lensFlareSystems.indexOf(this);
  81018. this._scene.lensFlareSystems.splice(index, 1);
  81019. };
  81020. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81021. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81022. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81023. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81024. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81025. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81026. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81027. var parsedFlare = parsedLensFlareSystem.flares[index];
  81028. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81029. }
  81030. return lensFlareSystem;
  81031. };
  81032. LensFlareSystem.prototype.serialize = function () {
  81033. var serializationObject = {};
  81034. serializationObject.id = this.id;
  81035. serializationObject.name = this.name;
  81036. serializationObject.emitterId = this.getEmitter().id;
  81037. serializationObject.borderLimit = this.borderLimit;
  81038. serializationObject.flares = [];
  81039. for (var index = 0; index < this.lensFlares.length; index++) {
  81040. var flare = this.lensFlares[index];
  81041. serializationObject.flares.push({
  81042. size: flare.size,
  81043. position: flare.position,
  81044. color: flare.color.asArray(),
  81045. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81046. });
  81047. }
  81048. return serializationObject;
  81049. };
  81050. return LensFlareSystem;
  81051. }());
  81052. BABYLON.LensFlareSystem = LensFlareSystem;
  81053. })(BABYLON || (BABYLON = {}));
  81054. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81055. var BABYLON;
  81056. (function (BABYLON) {
  81057. /**
  81058. * This is a holder class for the physics joint created by the physics plugin.
  81059. * It holds a set of functions to control the underlying joint.
  81060. */
  81061. var PhysicsJoint = /** @class */ (function () {
  81062. function PhysicsJoint(type, jointData) {
  81063. this.type = type;
  81064. this.jointData = jointData;
  81065. jointData.nativeParams = jointData.nativeParams || {};
  81066. }
  81067. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81068. get: function () {
  81069. return this._physicsJoint;
  81070. },
  81071. set: function (newJoint) {
  81072. if (this._physicsJoint) {
  81073. //remove from the wolrd
  81074. }
  81075. this._physicsJoint = newJoint;
  81076. },
  81077. enumerable: true,
  81078. configurable: true
  81079. });
  81080. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81081. set: function (physicsPlugin) {
  81082. this._physicsPlugin = physicsPlugin;
  81083. },
  81084. enumerable: true,
  81085. configurable: true
  81086. });
  81087. /**
  81088. * Execute a function that is physics-plugin specific.
  81089. * @param {Function} func the function that will be executed.
  81090. * It accepts two parameters: the physics world and the physics joint.
  81091. */
  81092. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81093. func(this._physicsPlugin.world, this._physicsJoint);
  81094. };
  81095. //TODO check if the native joints are the same
  81096. //Joint Types
  81097. PhysicsJoint.DistanceJoint = 0;
  81098. PhysicsJoint.HingeJoint = 1;
  81099. PhysicsJoint.BallAndSocketJoint = 2;
  81100. PhysicsJoint.WheelJoint = 3;
  81101. PhysicsJoint.SliderJoint = 4;
  81102. //OIMO
  81103. PhysicsJoint.PrismaticJoint = 5;
  81104. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81105. PhysicsJoint.UniversalJoint = 6;
  81106. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81107. //Cannon
  81108. //Similar to a Ball-Joint. Different in params
  81109. PhysicsJoint.PointToPointJoint = 8;
  81110. //Cannon only at the moment
  81111. PhysicsJoint.SpringJoint = 9;
  81112. PhysicsJoint.LockJoint = 10;
  81113. return PhysicsJoint;
  81114. }());
  81115. BABYLON.PhysicsJoint = PhysicsJoint;
  81116. /**
  81117. * A class representing a physics distance joint.
  81118. */
  81119. var DistanceJoint = /** @class */ (function (_super) {
  81120. __extends(DistanceJoint, _super);
  81121. function DistanceJoint(jointData) {
  81122. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81123. }
  81124. /**
  81125. * Update the predefined distance.
  81126. */
  81127. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81128. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81129. };
  81130. return DistanceJoint;
  81131. }(PhysicsJoint));
  81132. BABYLON.DistanceJoint = DistanceJoint;
  81133. var MotorEnabledJoint = /** @class */ (function (_super) {
  81134. __extends(MotorEnabledJoint, _super);
  81135. function MotorEnabledJoint(type, jointData) {
  81136. return _super.call(this, type, jointData) || this;
  81137. }
  81138. /**
  81139. * Set the motor values.
  81140. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81141. * @param {number} force the force to apply
  81142. * @param {number} maxForce max force for this motor.
  81143. */
  81144. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81145. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81146. };
  81147. /**
  81148. * Set the motor's limits.
  81149. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81150. */
  81151. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81152. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81153. };
  81154. return MotorEnabledJoint;
  81155. }(PhysicsJoint));
  81156. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81157. /**
  81158. * This class represents a single hinge physics joint
  81159. */
  81160. var HingeJoint = /** @class */ (function (_super) {
  81161. __extends(HingeJoint, _super);
  81162. function HingeJoint(jointData) {
  81163. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81164. }
  81165. /**
  81166. * Set the motor values.
  81167. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81168. * @param {number} force the force to apply
  81169. * @param {number} maxForce max force for this motor.
  81170. */
  81171. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81172. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81173. };
  81174. /**
  81175. * Set the motor's limits.
  81176. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81177. */
  81178. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81179. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81180. };
  81181. return HingeJoint;
  81182. }(MotorEnabledJoint));
  81183. BABYLON.HingeJoint = HingeJoint;
  81184. /**
  81185. * This class represents a dual hinge physics joint (same as wheel joint)
  81186. */
  81187. var Hinge2Joint = /** @class */ (function (_super) {
  81188. __extends(Hinge2Joint, _super);
  81189. function Hinge2Joint(jointData) {
  81190. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81191. }
  81192. /**
  81193. * Set the motor values.
  81194. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81195. * @param {number} force the force to apply
  81196. * @param {number} maxForce max force for this motor.
  81197. * @param {motorIndex} the motor's index, 0 or 1.
  81198. */
  81199. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81200. if (motorIndex === void 0) { motorIndex = 0; }
  81201. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81202. };
  81203. /**
  81204. * Set the motor limits.
  81205. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81206. * @param {number} upperLimit the upper limit
  81207. * @param {number} lowerLimit lower limit
  81208. * @param {motorIndex} the motor's index, 0 or 1.
  81209. */
  81210. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81211. if (motorIndex === void 0) { motorIndex = 0; }
  81212. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81213. };
  81214. return Hinge2Joint;
  81215. }(MotorEnabledJoint));
  81216. BABYLON.Hinge2Joint = Hinge2Joint;
  81217. })(BABYLON || (BABYLON = {}));
  81218. //# sourceMappingURL=babylon.physicsJoint.js.map
  81219. var BABYLON;
  81220. (function (BABYLON) {
  81221. var PhysicsImpostor = /** @class */ (function () {
  81222. function PhysicsImpostor(object, type, _options, _scene) {
  81223. if (_options === void 0) { _options = { mass: 0 }; }
  81224. var _this = this;
  81225. this.object = object;
  81226. this.type = type;
  81227. this._options = _options;
  81228. this._scene = _scene;
  81229. this._bodyUpdateRequired = false;
  81230. this._onBeforePhysicsStepCallbacks = new Array();
  81231. this._onAfterPhysicsStepCallbacks = new Array();
  81232. this._onPhysicsCollideCallbacks = [];
  81233. this._deltaPosition = BABYLON.Vector3.Zero();
  81234. this._isDisposed = false;
  81235. //temp variables for parent rotation calculations
  81236. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81237. this._tmpQuat = new BABYLON.Quaternion();
  81238. this._tmpQuat2 = new BABYLON.Quaternion();
  81239. /**
  81240. * this function is executed by the physics engine.
  81241. */
  81242. this.beforeStep = function () {
  81243. if (!_this._physicsEngine) {
  81244. return;
  81245. }
  81246. _this.object.translate(_this._deltaPosition, -1);
  81247. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81248. _this.object.computeWorldMatrix(false);
  81249. if (_this.object.parent && _this.object.rotationQuaternion) {
  81250. _this.getParentsRotation();
  81251. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81252. }
  81253. else {
  81254. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81255. }
  81256. if (!_this._options.disableBidirectionalTransformation) {
  81257. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81258. }
  81259. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81260. func(_this);
  81261. });
  81262. };
  81263. /**
  81264. * this function is executed by the physics engine.
  81265. */
  81266. this.afterStep = function () {
  81267. if (!_this._physicsEngine) {
  81268. return;
  81269. }
  81270. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81271. func(_this);
  81272. });
  81273. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81274. // object has now its world rotation. needs to be converted to local.
  81275. if (_this.object.parent && _this.object.rotationQuaternion) {
  81276. _this.getParentsRotation();
  81277. _this._tmpQuat.conjugateInPlace();
  81278. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81279. }
  81280. // take the position set and make it the absolute position of this object.
  81281. _this.object.setAbsolutePosition(_this.object.position);
  81282. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81283. _this.object.translate(_this._deltaPosition, 1);
  81284. };
  81285. /**
  81286. * Legacy collision detection event support
  81287. */
  81288. this.onCollideEvent = null;
  81289. //event and body object due to cannon's event-based architecture.
  81290. this.onCollide = function (e) {
  81291. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81292. return;
  81293. }
  81294. if (!_this._physicsEngine) {
  81295. return;
  81296. }
  81297. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81298. if (otherImpostor) {
  81299. // Legacy collision detection event support
  81300. if (_this.onCollideEvent) {
  81301. _this.onCollideEvent(_this, otherImpostor);
  81302. }
  81303. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81304. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81305. }).forEach(function (obj) {
  81306. obj.callback(_this, otherImpostor);
  81307. });
  81308. }
  81309. };
  81310. //sanity check!
  81311. if (!this.object) {
  81312. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81313. return;
  81314. }
  81315. //legacy support for old syntax.
  81316. if (!this._scene && object.getScene) {
  81317. this._scene = object.getScene();
  81318. }
  81319. if (!this._scene) {
  81320. return;
  81321. }
  81322. this._physicsEngine = this._scene.getPhysicsEngine();
  81323. if (!this._physicsEngine) {
  81324. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81325. }
  81326. else {
  81327. //set the object's quaternion, if not set
  81328. if (!this.object.rotationQuaternion) {
  81329. if (this.object.rotation) {
  81330. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81331. }
  81332. else {
  81333. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81334. }
  81335. }
  81336. //default options params
  81337. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81338. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81339. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81340. this._joints = [];
  81341. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81342. if (!this.object.parent || this._options.ignoreParent) {
  81343. this._init();
  81344. }
  81345. else if (this.object.parent.physicsImpostor) {
  81346. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81347. }
  81348. }
  81349. }
  81350. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81351. get: function () {
  81352. return this._isDisposed;
  81353. },
  81354. enumerable: true,
  81355. configurable: true
  81356. });
  81357. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81358. get: function () {
  81359. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81360. },
  81361. set: function (value) {
  81362. this.setMass(value);
  81363. },
  81364. enumerable: true,
  81365. configurable: true
  81366. });
  81367. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81368. get: function () {
  81369. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81370. },
  81371. set: function (value) {
  81372. if (!this._physicsEngine) {
  81373. return;
  81374. }
  81375. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81376. },
  81377. enumerable: true,
  81378. configurable: true
  81379. });
  81380. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81381. get: function () {
  81382. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81383. },
  81384. set: function (value) {
  81385. if (!this._physicsEngine) {
  81386. return;
  81387. }
  81388. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81389. },
  81390. enumerable: true,
  81391. configurable: true
  81392. });
  81393. /**
  81394. * This function will completly initialize this impostor.
  81395. * It will create a new body - but only if this mesh has no parent.
  81396. * If it has, this impostor will not be used other than to define the impostor
  81397. * of the child mesh.
  81398. */
  81399. PhysicsImpostor.prototype._init = function () {
  81400. if (!this._physicsEngine) {
  81401. return;
  81402. }
  81403. this._physicsEngine.removeImpostor(this);
  81404. this.physicsBody = null;
  81405. this._parent = this._parent || this._getPhysicsParent();
  81406. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81407. this._physicsEngine.addImpostor(this);
  81408. }
  81409. };
  81410. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81411. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81412. var parentMesh = this.object.parent;
  81413. return parentMesh.physicsImpostor;
  81414. }
  81415. return null;
  81416. };
  81417. /**
  81418. * Should a new body be generated.
  81419. */
  81420. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81421. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81422. };
  81423. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81424. this.forceUpdate();
  81425. };
  81426. /**
  81427. * Force a regeneration of this or the parent's impostor's body.
  81428. * Use under cautious - This will remove all joints already implemented.
  81429. */
  81430. PhysicsImpostor.prototype.forceUpdate = function () {
  81431. this._init();
  81432. if (this.parent && !this._options.ignoreParent) {
  81433. this.parent.forceUpdate();
  81434. }
  81435. };
  81436. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81437. /*public get mesh(): AbstractMesh {
  81438. return this._mesh;
  81439. }*/
  81440. /**
  81441. * Gets the body that holds this impostor. Either its own, or its parent.
  81442. */
  81443. get: function () {
  81444. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81445. },
  81446. /**
  81447. * Set the physics body. Used mainly by the physics engine/plugin
  81448. */
  81449. set: function (physicsBody) {
  81450. if (this._physicsBody && this._physicsEngine) {
  81451. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81452. }
  81453. this._physicsBody = physicsBody;
  81454. this.resetUpdateFlags();
  81455. },
  81456. enumerable: true,
  81457. configurable: true
  81458. });
  81459. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81460. get: function () {
  81461. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81462. },
  81463. set: function (value) {
  81464. this._parent = value;
  81465. },
  81466. enumerable: true,
  81467. configurable: true
  81468. });
  81469. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81470. this._bodyUpdateRequired = false;
  81471. };
  81472. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81473. if (this.object.getBoundingInfo) {
  81474. var q = this.object.rotationQuaternion;
  81475. //reset rotation
  81476. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81477. //calculate the world matrix with no rotation
  81478. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81479. var boundingInfo = this.object.getBoundingInfo();
  81480. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81481. //bring back the rotation
  81482. this.object.rotationQuaternion = q;
  81483. //calculate the world matrix with the new rotation
  81484. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81485. return size;
  81486. }
  81487. else {
  81488. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81489. }
  81490. };
  81491. PhysicsImpostor.prototype.getObjectCenter = function () {
  81492. if (this.object.getBoundingInfo) {
  81493. var boundingInfo = this.object.getBoundingInfo();
  81494. return boundingInfo.boundingBox.centerWorld;
  81495. }
  81496. else {
  81497. return this.object.position;
  81498. }
  81499. };
  81500. /**
  81501. * Get a specific parametes from the options parameter.
  81502. */
  81503. PhysicsImpostor.prototype.getParam = function (paramName) {
  81504. return this._options[paramName];
  81505. };
  81506. /**
  81507. * Sets a specific parameter in the options given to the physics plugin
  81508. */
  81509. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81510. this._options[paramName] = value;
  81511. this._bodyUpdateRequired = true;
  81512. };
  81513. /**
  81514. * Specifically change the body's mass option. Won't recreate the physics body object
  81515. */
  81516. PhysicsImpostor.prototype.setMass = function (mass) {
  81517. if (this.getParam("mass") !== mass) {
  81518. this.setParam("mass", mass);
  81519. }
  81520. if (this._physicsEngine) {
  81521. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81522. }
  81523. };
  81524. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81525. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81526. };
  81527. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81528. if (this._physicsEngine) {
  81529. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81530. }
  81531. };
  81532. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81533. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81534. };
  81535. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81536. if (this._physicsEngine) {
  81537. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81538. }
  81539. };
  81540. /**
  81541. * Execute a function with the physics plugin native code.
  81542. * Provide a function the will have two variables - the world object and the physics body object.
  81543. */
  81544. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81545. if (this._physicsEngine) {
  81546. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81547. }
  81548. };
  81549. /**
  81550. * Register a function that will be executed before the physics world is stepping forward.
  81551. */
  81552. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81553. this._onBeforePhysicsStepCallbacks.push(func);
  81554. };
  81555. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81556. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81557. if (index > -1) {
  81558. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81559. }
  81560. else {
  81561. BABYLON.Tools.Warn("Function to remove was not found");
  81562. }
  81563. };
  81564. /**
  81565. * Register a function that will be executed after the physics step
  81566. */
  81567. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81568. this._onAfterPhysicsStepCallbacks.push(func);
  81569. };
  81570. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81571. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81572. if (index > -1) {
  81573. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81574. }
  81575. else {
  81576. BABYLON.Tools.Warn("Function to remove was not found");
  81577. }
  81578. };
  81579. /**
  81580. * register a function that will be executed when this impostor collides against a different body.
  81581. */
  81582. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81583. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81584. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81585. };
  81586. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81587. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81588. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81589. if (index > -1) {
  81590. this._onPhysicsCollideCallbacks.splice(index, 1);
  81591. }
  81592. else {
  81593. BABYLON.Tools.Warn("Function to remove was not found");
  81594. }
  81595. };
  81596. PhysicsImpostor.prototype.getParentsRotation = function () {
  81597. var parent = this.object.parent;
  81598. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  81599. while (parent) {
  81600. if (parent.rotationQuaternion) {
  81601. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  81602. }
  81603. else {
  81604. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  81605. }
  81606. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  81607. parent = parent.parent;
  81608. }
  81609. return this._tmpQuat;
  81610. };
  81611. /**
  81612. * Apply a force
  81613. */
  81614. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  81615. if (this._physicsEngine) {
  81616. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  81617. }
  81618. return this;
  81619. };
  81620. /**
  81621. * Apply an impulse
  81622. */
  81623. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  81624. if (this._physicsEngine) {
  81625. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  81626. }
  81627. return this;
  81628. };
  81629. /**
  81630. * A help function to create a joint.
  81631. */
  81632. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  81633. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  81634. this.addJoint(otherImpostor, joint);
  81635. return this;
  81636. };
  81637. /**
  81638. * Add a joint to this impostor with a different impostor.
  81639. */
  81640. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  81641. this._joints.push({
  81642. otherImpostor: otherImpostor,
  81643. joint: joint
  81644. });
  81645. if (this._physicsEngine) {
  81646. this._physicsEngine.addJoint(this, otherImpostor, joint);
  81647. }
  81648. return this;
  81649. };
  81650. /**
  81651. * Will keep this body still, in a sleep mode.
  81652. */
  81653. PhysicsImpostor.prototype.sleep = function () {
  81654. if (this._physicsEngine) {
  81655. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  81656. }
  81657. return this;
  81658. };
  81659. /**
  81660. * Wake the body up.
  81661. */
  81662. PhysicsImpostor.prototype.wakeUp = function () {
  81663. if (this._physicsEngine) {
  81664. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  81665. }
  81666. return this;
  81667. };
  81668. PhysicsImpostor.prototype.clone = function (newObject) {
  81669. if (!newObject)
  81670. return null;
  81671. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  81672. };
  81673. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  81674. var _this = this;
  81675. //no dispose if no physics engine is available.
  81676. if (!this._physicsEngine) {
  81677. return;
  81678. }
  81679. this._joints.forEach(function (j) {
  81680. if (_this._physicsEngine) {
  81681. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  81682. }
  81683. });
  81684. //dispose the physics body
  81685. this._physicsEngine.removeImpostor(this);
  81686. if (this.parent) {
  81687. this.parent.forceUpdate();
  81688. }
  81689. else {
  81690. /*this._object.getChildMeshes().forEach(function(mesh) {
  81691. if (mesh.physicsImpostor) {
  81692. if (disposeChildren) {
  81693. mesh.physicsImpostor.dispose();
  81694. mesh.physicsImpostor = null;
  81695. }
  81696. }
  81697. })*/
  81698. }
  81699. this._isDisposed = true;
  81700. };
  81701. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  81702. this._deltaPosition.copyFrom(position);
  81703. };
  81704. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  81705. if (!this._deltaRotation) {
  81706. this._deltaRotation = new BABYLON.Quaternion();
  81707. }
  81708. this._deltaRotation.copyFrom(rotation);
  81709. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  81710. };
  81711. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  81712. if (this._physicsEngine) {
  81713. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  81714. }
  81715. return this;
  81716. };
  81717. PhysicsImpostor.prototype.getRadius = function () {
  81718. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  81719. };
  81720. /**
  81721. * Sync a bone with this impostor
  81722. * @param bone The bone to sync to the impostor.
  81723. * @param boneMesh The mesh that the bone is influencing.
  81724. * @param jointPivot The pivot of the joint / bone in local space.
  81725. * @param distToJoint Optional distance from the impostor to the joint.
  81726. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81727. */
  81728. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  81729. var tempVec = PhysicsImpostor._tmpVecs[0];
  81730. var mesh = this.object;
  81731. if (mesh.rotationQuaternion) {
  81732. if (adjustRotation) {
  81733. var tempQuat = PhysicsImpostor._tmpQuat;
  81734. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  81735. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  81736. }
  81737. else {
  81738. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  81739. }
  81740. }
  81741. tempVec.x = 0;
  81742. tempVec.y = 0;
  81743. tempVec.z = 0;
  81744. if (jointPivot) {
  81745. tempVec.x = jointPivot.x;
  81746. tempVec.y = jointPivot.y;
  81747. tempVec.z = jointPivot.z;
  81748. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  81749. if (distToJoint === undefined || distToJoint === null) {
  81750. distToJoint = jointPivot.length();
  81751. }
  81752. tempVec.x *= distToJoint;
  81753. tempVec.y *= distToJoint;
  81754. tempVec.z *= distToJoint;
  81755. }
  81756. if (bone.getParent()) {
  81757. tempVec.addInPlace(mesh.getAbsolutePosition());
  81758. bone.setAbsolutePosition(tempVec, boneMesh);
  81759. }
  81760. else {
  81761. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  81762. boneMesh.position.x -= tempVec.x;
  81763. boneMesh.position.y -= tempVec.y;
  81764. boneMesh.position.z -= tempVec.z;
  81765. }
  81766. };
  81767. /**
  81768. * Sync impostor to a bone
  81769. * @param bone The bone that the impostor will be synced to.
  81770. * @param boneMesh The mesh that the bone is influencing.
  81771. * @param jointPivot The pivot of the joint / bone in local space.
  81772. * @param distToJoint Optional distance from the impostor to the joint.
  81773. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81774. * @param boneAxis Optional vector3 axis the bone is aligned with
  81775. */
  81776. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  81777. var mesh = this.object;
  81778. if (mesh.rotationQuaternion) {
  81779. if (adjustRotation) {
  81780. var tempQuat = PhysicsImpostor._tmpQuat;
  81781. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  81782. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  81783. }
  81784. else {
  81785. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  81786. }
  81787. }
  81788. var pos = PhysicsImpostor._tmpVecs[0];
  81789. var boneDir = PhysicsImpostor._tmpVecs[1];
  81790. if (!boneAxis) {
  81791. boneAxis = PhysicsImpostor._tmpVecs[2];
  81792. boneAxis.x = 0;
  81793. boneAxis.y = 1;
  81794. boneAxis.z = 0;
  81795. }
  81796. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  81797. bone.getAbsolutePositionToRef(boneMesh, pos);
  81798. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  81799. distToJoint = jointPivot.length();
  81800. }
  81801. if (distToJoint !== undefined && distToJoint !== null) {
  81802. pos.x += boneDir.x * distToJoint;
  81803. pos.y += boneDir.y * distToJoint;
  81804. pos.z += boneDir.z * distToJoint;
  81805. }
  81806. mesh.setAbsolutePosition(pos);
  81807. };
  81808. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  81809. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  81810. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81811. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  81812. //Impostor types
  81813. PhysicsImpostor.NoImpostor = 0;
  81814. PhysicsImpostor.SphereImpostor = 1;
  81815. PhysicsImpostor.BoxImpostor = 2;
  81816. PhysicsImpostor.PlaneImpostor = 3;
  81817. PhysicsImpostor.MeshImpostor = 4;
  81818. PhysicsImpostor.CylinderImpostor = 7;
  81819. PhysicsImpostor.ParticleImpostor = 8;
  81820. PhysicsImpostor.HeightmapImpostor = 9;
  81821. return PhysicsImpostor;
  81822. }());
  81823. BABYLON.PhysicsImpostor = PhysicsImpostor;
  81824. })(BABYLON || (BABYLON = {}));
  81825. //# sourceMappingURL=babylon.physicsImpostor.js.map
  81826. var BABYLON;
  81827. (function (BABYLON) {
  81828. var PhysicsEngine = /** @class */ (function () {
  81829. function PhysicsEngine(gravity, _physicsPlugin) {
  81830. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  81831. this._physicsPlugin = _physicsPlugin;
  81832. //new methods and parameters
  81833. this._impostors = [];
  81834. this._joints = [];
  81835. if (!this._physicsPlugin.isSupported()) {
  81836. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  81837. + "Please make sure it is included.");
  81838. }
  81839. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  81840. this.setGravity(gravity);
  81841. this.setTimeStep();
  81842. }
  81843. PhysicsEngine.prototype.setGravity = function (gravity) {
  81844. this.gravity = gravity;
  81845. this._physicsPlugin.setGravity(this.gravity);
  81846. };
  81847. /**
  81848. * Set the time step of the physics engine.
  81849. * default is 1/60.
  81850. * To slow it down, enter 1/600 for example.
  81851. * To speed it up, 1/30
  81852. * @param {number} newTimeStep the new timestep to apply to this world.
  81853. */
  81854. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  81855. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  81856. this._physicsPlugin.setTimeStep(newTimeStep);
  81857. };
  81858. /**
  81859. * Get the time step of the physics engine.
  81860. */
  81861. PhysicsEngine.prototype.getTimeStep = function () {
  81862. return this._physicsPlugin.getTimeStep();
  81863. };
  81864. PhysicsEngine.prototype.dispose = function () {
  81865. this._impostors.forEach(function (impostor) {
  81866. impostor.dispose();
  81867. });
  81868. this._physicsPlugin.dispose();
  81869. };
  81870. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  81871. return this._physicsPlugin.name;
  81872. };
  81873. /**
  81874. * Adding a new impostor for the impostor tracking.
  81875. * This will be done by the impostor itself.
  81876. * @param {PhysicsImpostor} impostor the impostor to add
  81877. */
  81878. PhysicsEngine.prototype.addImpostor = function (impostor) {
  81879. impostor.uniqueId = this._impostors.push(impostor);
  81880. //if no parent, generate the body
  81881. if (!impostor.parent) {
  81882. this._physicsPlugin.generatePhysicsBody(impostor);
  81883. }
  81884. };
  81885. /**
  81886. * Remove an impostor from the engine.
  81887. * This impostor and its mesh will not longer be updated by the physics engine.
  81888. * @param {PhysicsImpostor} impostor the impostor to remove
  81889. */
  81890. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  81891. var index = this._impostors.indexOf(impostor);
  81892. if (index > -1) {
  81893. var removed = this._impostors.splice(index, 1);
  81894. //Is it needed?
  81895. if (removed.length) {
  81896. //this will also remove it from the world.
  81897. removed[0].physicsBody = null;
  81898. }
  81899. }
  81900. };
  81901. /**
  81902. * Add a joint to the physics engine
  81903. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  81904. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  81905. * @param {PhysicsJoint} the joint that will connect both impostors.
  81906. */
  81907. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  81908. var impostorJoint = {
  81909. mainImpostor: mainImpostor,
  81910. connectedImpostor: connectedImpostor,
  81911. joint: joint
  81912. };
  81913. joint.physicsPlugin = this._physicsPlugin;
  81914. this._joints.push(impostorJoint);
  81915. this._physicsPlugin.generateJoint(impostorJoint);
  81916. };
  81917. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  81918. var matchingJoints = this._joints.filter(function (impostorJoint) {
  81919. return (impostorJoint.connectedImpostor === connectedImpostor
  81920. && impostorJoint.joint === joint
  81921. && impostorJoint.mainImpostor === mainImpostor);
  81922. });
  81923. if (matchingJoints.length) {
  81924. this._physicsPlugin.removeJoint(matchingJoints[0]);
  81925. //TODO remove it from the list as well
  81926. }
  81927. };
  81928. /**
  81929. * Called by the scene. no need to call it.
  81930. */
  81931. PhysicsEngine.prototype._step = function (delta) {
  81932. var _this = this;
  81933. //check if any mesh has no body / requires an update
  81934. this._impostors.forEach(function (impostor) {
  81935. if (impostor.isBodyInitRequired()) {
  81936. _this._physicsPlugin.generatePhysicsBody(impostor);
  81937. }
  81938. });
  81939. if (delta > 0.1) {
  81940. delta = 0.1;
  81941. }
  81942. else if (delta <= 0) {
  81943. delta = 1.0 / 60.0;
  81944. }
  81945. this._physicsPlugin.executeStep(delta, this._impostors);
  81946. };
  81947. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  81948. return this._physicsPlugin;
  81949. };
  81950. PhysicsEngine.prototype.getImpostors = function () {
  81951. return this._impostors;
  81952. };
  81953. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  81954. for (var i = 0; i < this._impostors.length; ++i) {
  81955. if (this._impostors[i].object === object) {
  81956. return this._impostors[i];
  81957. }
  81958. }
  81959. return null;
  81960. };
  81961. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  81962. for (var i = 0; i < this._impostors.length; ++i) {
  81963. if (this._impostors[i].physicsBody === body) {
  81964. return this._impostors[i];
  81965. }
  81966. }
  81967. return null;
  81968. };
  81969. // Statics
  81970. PhysicsEngine.Epsilon = 0.001;
  81971. return PhysicsEngine;
  81972. }());
  81973. BABYLON.PhysicsEngine = PhysicsEngine;
  81974. })(BABYLON || (BABYLON = {}));
  81975. //# sourceMappingURL=babylon.physicsEngine.js.map
  81976. var BABYLON;
  81977. (function (BABYLON) {
  81978. var PhysicsHelper = /** @class */ (function () {
  81979. function PhysicsHelper(scene) {
  81980. this._scene = scene;
  81981. this._physicsEngine = this._scene.getPhysicsEngine();
  81982. if (!this._physicsEngine) {
  81983. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  81984. }
  81985. }
  81986. /**
  81987. * @param {Vector3} origin the origin of the explosion
  81988. * @param {number} radius the explosion radius
  81989. * @param {number} strength the explosion strength
  81990. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81991. */
  81992. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  81993. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81994. if (!this._physicsEngine) {
  81995. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  81996. return null;
  81997. }
  81998. var impostors = this._physicsEngine.getImpostors();
  81999. if (impostors.length === 0) {
  82000. return null;
  82001. }
  82002. var event = new PhysicsRadialExplosionEvent(this._scene);
  82003. impostors.forEach(function (impostor) {
  82004. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82005. if (!impostorForceAndContactPoint) {
  82006. return;
  82007. }
  82008. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82009. });
  82010. event.dispose(false);
  82011. return event;
  82012. };
  82013. /**
  82014. * @param {Vector3} origin the origin of the explosion
  82015. * @param {number} radius the explosion radius
  82016. * @param {number} strength the explosion strength
  82017. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82018. */
  82019. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82020. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82021. if (!this._physicsEngine) {
  82022. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82023. return null;
  82024. }
  82025. var impostors = this._physicsEngine.getImpostors();
  82026. if (impostors.length === 0) {
  82027. return null;
  82028. }
  82029. var event = new PhysicsRadialExplosionEvent(this._scene);
  82030. impostors.forEach(function (impostor) {
  82031. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82032. if (!impostorForceAndContactPoint) {
  82033. return;
  82034. }
  82035. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82036. });
  82037. event.dispose(false);
  82038. return event;
  82039. };
  82040. /**
  82041. * @param {Vector3} origin the origin of the explosion
  82042. * @param {number} radius the explosion radius
  82043. * @param {number} strength the explosion strength
  82044. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82045. */
  82046. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82047. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82048. if (!this._physicsEngine) {
  82049. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82050. return null;
  82051. }
  82052. var impostors = this._physicsEngine.getImpostors();
  82053. if (impostors.length === 0) {
  82054. return null;
  82055. }
  82056. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82057. event.dispose(false);
  82058. return event;
  82059. };
  82060. /**
  82061. * @param {Vector3} origin the origin of the updraft
  82062. * @param {number} radius the radius of the updraft
  82063. * @param {number} strength the strength of the updraft
  82064. * @param {number} height the height of the updraft
  82065. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82066. */
  82067. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82068. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82069. if (!this._physicsEngine) {
  82070. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82071. return null;
  82072. }
  82073. if (this._physicsEngine.getImpostors().length === 0) {
  82074. return null;
  82075. }
  82076. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82077. event.dispose(false);
  82078. return event;
  82079. };
  82080. /**
  82081. * @param {Vector3} origin the of the vortex
  82082. * @param {number} radius the radius of the vortex
  82083. * @param {number} strength the strength of the vortex
  82084. * @param {number} height the height of the vortex
  82085. */
  82086. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82087. if (!this._physicsEngine) {
  82088. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82089. return null;
  82090. }
  82091. if (this._physicsEngine.getImpostors().length === 0) {
  82092. return null;
  82093. }
  82094. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82095. event.dispose(false);
  82096. return event;
  82097. };
  82098. return PhysicsHelper;
  82099. }());
  82100. BABYLON.PhysicsHelper = PhysicsHelper;
  82101. /***** Radial explosion *****/
  82102. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82103. function PhysicsRadialExplosionEvent(scene) {
  82104. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82105. this._rays = [];
  82106. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82107. this._scene = scene;
  82108. }
  82109. /**
  82110. * Returns the data related to the radial explosion event (sphere & rays).
  82111. * @returns {PhysicsRadialExplosionEventData}
  82112. */
  82113. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82114. this._dataFetched = true;
  82115. return {
  82116. sphere: this._sphere,
  82117. rays: this._rays,
  82118. };
  82119. };
  82120. /**
  82121. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82122. * @param impostor
  82123. * @param {Vector3} origin the origin of the explosion
  82124. * @param {number} radius the explosion radius
  82125. * @param {number} strength the explosion strength
  82126. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82127. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82128. */
  82129. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82130. if (impostor.mass === 0) {
  82131. return null;
  82132. }
  82133. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82134. return null;
  82135. }
  82136. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82137. return null;
  82138. }
  82139. var impostorObjectCenter = impostor.getObjectCenter();
  82140. var direction = impostorObjectCenter.subtract(origin);
  82141. var ray = new BABYLON.Ray(origin, direction, radius);
  82142. this._rays.push(ray);
  82143. var hit = ray.intersectsMesh(impostor.object);
  82144. var contactPoint = hit.pickedPoint;
  82145. if (!contactPoint) {
  82146. return null;
  82147. }
  82148. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82149. if (distanceFromOrigin > radius) {
  82150. return null;
  82151. }
  82152. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82153. ? strength
  82154. : strength * (1 - (distanceFromOrigin / radius));
  82155. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82156. return { force: force, contactPoint: contactPoint };
  82157. };
  82158. /**
  82159. * Disposes the sphere.
  82160. * @param {bolean} force
  82161. */
  82162. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82163. var _this = this;
  82164. if (force === void 0) { force = true; }
  82165. if (force) {
  82166. this._sphere.dispose();
  82167. }
  82168. else {
  82169. setTimeout(function () {
  82170. if (!_this._dataFetched) {
  82171. _this._sphere.dispose();
  82172. }
  82173. }, 0);
  82174. }
  82175. };
  82176. /*** Helpers ***/
  82177. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82178. if (!this._sphere) {
  82179. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82180. this._sphere.isVisible = false;
  82181. }
  82182. };
  82183. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82184. var impostorObject = impostor.object;
  82185. this._prepareSphere();
  82186. this._sphere.position = origin;
  82187. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82188. this._sphere._updateBoundingInfo();
  82189. this._sphere.computeWorldMatrix(true);
  82190. return this._sphere.intersectsMesh(impostorObject, true);
  82191. };
  82192. return PhysicsRadialExplosionEvent;
  82193. }());
  82194. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82195. /***** Gravitational Field *****/
  82196. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82197. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82198. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82199. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82200. this._physicsHelper = physicsHelper;
  82201. this._scene = scene;
  82202. this._origin = origin;
  82203. this._radius = radius;
  82204. this._strength = strength;
  82205. this._falloff = falloff;
  82206. this._tickCallback = this._tick.bind(this);
  82207. }
  82208. /**
  82209. * Returns the data related to the gravitational field event (sphere).
  82210. * @returns {PhysicsGravitationalFieldEventData}
  82211. */
  82212. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82213. this._dataFetched = true;
  82214. return {
  82215. sphere: this._sphere,
  82216. };
  82217. };
  82218. /**
  82219. * Enables the gravitational field.
  82220. */
  82221. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82222. this._tickCallback.call(this);
  82223. this._scene.registerBeforeRender(this._tickCallback);
  82224. };
  82225. /**
  82226. * Disables the gravitational field.
  82227. */
  82228. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82229. this._scene.unregisterBeforeRender(this._tickCallback);
  82230. };
  82231. /**
  82232. * Disposes the sphere.
  82233. * @param {bolean} force
  82234. */
  82235. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82236. var _this = this;
  82237. if (force === void 0) { force = true; }
  82238. if (force) {
  82239. this._sphere.dispose();
  82240. }
  82241. else {
  82242. setTimeout(function () {
  82243. if (!_this._dataFetched) {
  82244. _this._sphere.dispose();
  82245. }
  82246. }, 0);
  82247. }
  82248. };
  82249. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82250. // Since the params won't change, we fetch the event only once
  82251. if (this._sphere) {
  82252. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82253. }
  82254. else {
  82255. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82256. if (radialExplosionEvent) {
  82257. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82258. }
  82259. }
  82260. };
  82261. return PhysicsGravitationalFieldEvent;
  82262. }());
  82263. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82264. /***** Updraft *****/
  82265. var PhysicsUpdraftEvent = /** @class */ (function () {
  82266. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82267. this._scene = _scene;
  82268. this._origin = _origin;
  82269. this._radius = _radius;
  82270. this._strength = _strength;
  82271. this._height = _height;
  82272. this._updraftMode = _updraftMode;
  82273. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82274. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82275. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82276. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82277. this._physicsEngine = this._scene.getPhysicsEngine();
  82278. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82279. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82280. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82281. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82282. }
  82283. this._tickCallback = this._tick.bind(this);
  82284. }
  82285. /**
  82286. * Returns the data related to the updraft event (cylinder).
  82287. * @returns {PhysicsUpdraftEventData}
  82288. */
  82289. PhysicsUpdraftEvent.prototype.getData = function () {
  82290. this._dataFetched = true;
  82291. return {
  82292. cylinder: this._cylinder,
  82293. };
  82294. };
  82295. /**
  82296. * Enables the updraft.
  82297. */
  82298. PhysicsUpdraftEvent.prototype.enable = function () {
  82299. this._tickCallback.call(this);
  82300. this._scene.registerBeforeRender(this._tickCallback);
  82301. };
  82302. /**
  82303. * Disables the cortex.
  82304. */
  82305. PhysicsUpdraftEvent.prototype.disable = function () {
  82306. this._scene.unregisterBeforeRender(this._tickCallback);
  82307. };
  82308. /**
  82309. * Disposes the sphere.
  82310. * @param {bolean} force
  82311. */
  82312. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82313. var _this = this;
  82314. if (force === void 0) { force = true; }
  82315. if (force) {
  82316. this._cylinder.dispose();
  82317. }
  82318. else {
  82319. setTimeout(function () {
  82320. if (!_this._dataFetched) {
  82321. _this._cylinder.dispose();
  82322. }
  82323. }, 0);
  82324. }
  82325. };
  82326. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82327. if (impostor.mass === 0) {
  82328. return null;
  82329. }
  82330. if (!this._intersectsWithCylinder(impostor)) {
  82331. return null;
  82332. }
  82333. var impostorObjectCenter = impostor.getObjectCenter();
  82334. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82335. var direction = this._originDirection;
  82336. }
  82337. else {
  82338. var direction = impostorObjectCenter.subtract(this._originTop);
  82339. }
  82340. var multiplier = this._strength * -1;
  82341. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82342. return { force: force, contactPoint: impostorObjectCenter };
  82343. };
  82344. PhysicsUpdraftEvent.prototype._tick = function () {
  82345. var _this = this;
  82346. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82347. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82348. if (!impostorForceAndContactPoint) {
  82349. return;
  82350. }
  82351. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82352. });
  82353. };
  82354. /*** Helpers ***/
  82355. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82356. if (!this._cylinder) {
  82357. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82358. height: this._height,
  82359. diameter: this._radius * 2,
  82360. }, this._scene);
  82361. this._cylinder.isVisible = false;
  82362. }
  82363. };
  82364. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82365. var impostorObject = impostor.object;
  82366. this._prepareCylinder();
  82367. this._cylinder.position = this._cylinderPosition;
  82368. return this._cylinder.intersectsMesh(impostorObject, true);
  82369. };
  82370. return PhysicsUpdraftEvent;
  82371. }());
  82372. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82373. /***** Vortex *****/
  82374. var PhysicsVortexEvent = /** @class */ (function () {
  82375. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82376. this._scene = _scene;
  82377. this._origin = _origin;
  82378. this._radius = _radius;
  82379. this._strength = _strength;
  82380. this._height = _height;
  82381. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82382. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82383. this._updraftMultiplier = 0.02;
  82384. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82385. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82386. this._physicsEngine = this._scene.getPhysicsEngine();
  82387. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82388. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82389. this._tickCallback = this._tick.bind(this);
  82390. }
  82391. /**
  82392. * Returns the data related to the vortex event (cylinder).
  82393. * @returns {PhysicsVortexEventData}
  82394. */
  82395. PhysicsVortexEvent.prototype.getData = function () {
  82396. this._dataFetched = true;
  82397. return {
  82398. cylinder: this._cylinder,
  82399. };
  82400. };
  82401. /**
  82402. * Enables the vortex.
  82403. */
  82404. PhysicsVortexEvent.prototype.enable = function () {
  82405. this._tickCallback.call(this);
  82406. this._scene.registerBeforeRender(this._tickCallback);
  82407. };
  82408. /**
  82409. * Disables the cortex.
  82410. */
  82411. PhysicsVortexEvent.prototype.disable = function () {
  82412. this._scene.unregisterBeforeRender(this._tickCallback);
  82413. };
  82414. /**
  82415. * Disposes the sphere.
  82416. * @param {bolean} force
  82417. */
  82418. PhysicsVortexEvent.prototype.dispose = function (force) {
  82419. var _this = this;
  82420. if (force === void 0) { force = true; }
  82421. if (force) {
  82422. this._cylinder.dispose();
  82423. }
  82424. else {
  82425. setTimeout(function () {
  82426. if (!_this._dataFetched) {
  82427. _this._cylinder.dispose();
  82428. }
  82429. }, 0);
  82430. }
  82431. };
  82432. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82433. if (impostor.mass === 0) {
  82434. return null;
  82435. }
  82436. if (!this._intersectsWithCylinder(impostor)) {
  82437. return null;
  82438. }
  82439. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82440. return null;
  82441. }
  82442. var impostorObjectCenter = impostor.getObjectCenter();
  82443. 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)
  82444. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82445. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82446. var hit = ray.intersectsMesh(impostor.object);
  82447. var contactPoint = hit.pickedPoint;
  82448. if (!contactPoint) {
  82449. return null;
  82450. }
  82451. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82452. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82453. var directionToOrigin = contactPoint.normalize();
  82454. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82455. directionToOrigin = directionToOrigin.negate();
  82456. }
  82457. // TODO: find a more physically based solution
  82458. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82459. var forceX = directionToOrigin.x * this._strength / 8;
  82460. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82461. var forceZ = directionToOrigin.z * this._strength / 8;
  82462. }
  82463. else {
  82464. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82465. var forceY = this._originTop.y * this._updraftMultiplier;
  82466. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82467. }
  82468. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82469. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82470. return { force: force, contactPoint: impostorObjectCenter };
  82471. };
  82472. PhysicsVortexEvent.prototype._tick = function () {
  82473. var _this = this;
  82474. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82475. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82476. if (!impostorForceAndContactPoint) {
  82477. return;
  82478. }
  82479. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82480. });
  82481. };
  82482. /*** Helpers ***/
  82483. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82484. if (!this._cylinder) {
  82485. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82486. height: this._height,
  82487. diameter: this._radius * 2,
  82488. }, this._scene);
  82489. this._cylinder.isVisible = false;
  82490. }
  82491. };
  82492. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82493. var impostorObject = impostor.object;
  82494. this._prepareCylinder();
  82495. this._cylinder.position = this._cylinderPosition;
  82496. return this._cylinder.intersectsMesh(impostorObject, true);
  82497. };
  82498. return PhysicsVortexEvent;
  82499. }());
  82500. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82501. /***** Enums *****/
  82502. /**
  82503. * The strenght of the force in correspondence to the distance of the affected object
  82504. */
  82505. var PhysicsRadialImpulseFalloff;
  82506. (function (PhysicsRadialImpulseFalloff) {
  82507. /** Defines that impulse is constant in strength across it's whole radius */
  82508. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82509. /** DEfines that impulse gets weaker if it's further from the origin */
  82510. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82511. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82512. /**
  82513. * The strenght of the force in correspondence to the distance of the affected object
  82514. */
  82515. var PhysicsUpdraftMode;
  82516. (function (PhysicsUpdraftMode) {
  82517. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82518. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82519. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82520. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82521. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82522. })(BABYLON || (BABYLON = {}));
  82523. //# sourceMappingURL=babylon.physicsHelper.js.map
  82524. var BABYLON;
  82525. (function (BABYLON) {
  82526. var CannonJSPlugin = /** @class */ (function () {
  82527. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82528. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82529. if (iterations === void 0) { iterations = 10; }
  82530. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82531. this.name = "CannonJSPlugin";
  82532. this._physicsMaterials = new Array();
  82533. this._fixedTimeStep = 1 / 60;
  82534. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82535. this.BJSCANNON = CANNON;
  82536. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82537. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82538. this._tmpPosition = BABYLON.Vector3.Zero();
  82539. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82540. this._tmpUnityRotation = new BABYLON.Quaternion();
  82541. if (!this.isSupported()) {
  82542. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82543. return;
  82544. }
  82545. this._extendNamespace();
  82546. this.world = new this.BJSCANNON.World();
  82547. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82548. this.world.solver.iterations = iterations;
  82549. }
  82550. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82551. this.world.gravity.copy(gravity);
  82552. };
  82553. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82554. this._fixedTimeStep = timeStep;
  82555. };
  82556. CannonJSPlugin.prototype.getTimeStep = function () {
  82557. return this._fixedTimeStep;
  82558. };
  82559. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82560. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82561. };
  82562. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82563. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82564. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82565. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82566. };
  82567. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82568. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82569. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82570. impostor.physicsBody.applyForce(impulse, worldPoint);
  82571. };
  82572. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82573. //parent-child relationship. Does this impostor has a parent impostor?
  82574. if (impostor.parent) {
  82575. if (impostor.physicsBody) {
  82576. this.removePhysicsBody(impostor);
  82577. //TODO is that needed?
  82578. impostor.forceUpdate();
  82579. }
  82580. return;
  82581. }
  82582. //should a new body be created for this impostor?
  82583. if (impostor.isBodyInitRequired()) {
  82584. var shape = this._createShape(impostor);
  82585. //unregister events, if body is being changed
  82586. var oldBody = impostor.physicsBody;
  82587. if (oldBody) {
  82588. this.removePhysicsBody(impostor);
  82589. }
  82590. //create the body and material
  82591. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82592. var bodyCreationObject = {
  82593. mass: impostor.getParam("mass"),
  82594. material: material
  82595. };
  82596. // A simple extend, in case native options were used.
  82597. var nativeOptions = impostor.getParam("nativeOptions");
  82598. for (var key in nativeOptions) {
  82599. if (nativeOptions.hasOwnProperty(key)) {
  82600. bodyCreationObject[key] = nativeOptions[key];
  82601. }
  82602. }
  82603. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  82604. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  82605. this.world.addEventListener("preStep", impostor.beforeStep);
  82606. this.world.addEventListener("postStep", impostor.afterStep);
  82607. impostor.physicsBody.addShape(shape);
  82608. this.world.add(impostor.physicsBody);
  82609. //try to keep the body moving in the right direction by taking old properties.
  82610. //Should be tested!
  82611. if (oldBody) {
  82612. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  82613. impostor.physicsBody[param].copy(oldBody[param]);
  82614. });
  82615. }
  82616. this._processChildMeshes(impostor);
  82617. }
  82618. //now update the body's transformation
  82619. this._updatePhysicsBodyTransformation(impostor);
  82620. };
  82621. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  82622. var _this = this;
  82623. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  82624. var currentRotation = mainImpostor.object.rotationQuaternion;
  82625. if (meshChildren.length) {
  82626. var processMesh = function (localPosition, mesh) {
  82627. if (!currentRotation || !mesh.rotationQuaternion) {
  82628. return;
  82629. }
  82630. var childImpostor = mesh.getPhysicsImpostor();
  82631. if (childImpostor) {
  82632. var parent = childImpostor.parent;
  82633. if (parent !== mainImpostor) {
  82634. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  82635. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  82636. if (childImpostor.physicsBody) {
  82637. _this.removePhysicsBody(childImpostor);
  82638. childImpostor.physicsBody = null;
  82639. }
  82640. childImpostor.parent = mainImpostor;
  82641. childImpostor.resetUpdateFlags();
  82642. 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));
  82643. //Add the mass of the children.
  82644. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  82645. }
  82646. }
  82647. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  82648. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  82649. };
  82650. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  82651. }
  82652. };
  82653. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82654. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  82655. this.world.removeEventListener("preStep", impostor.beforeStep);
  82656. this.world.removeEventListener("postStep", impostor.afterStep);
  82657. this.world.remove(impostor.physicsBody);
  82658. };
  82659. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82660. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82661. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82662. if (!mainBody || !connectedBody) {
  82663. return;
  82664. }
  82665. var constraint;
  82666. var jointData = impostorJoint.joint.jointData;
  82667. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  82668. var constraintData = {
  82669. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  82670. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  82671. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  82672. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  82673. maxForce: jointData.nativeParams.maxForce,
  82674. collideConnected: !!jointData.collision
  82675. };
  82676. switch (impostorJoint.joint.type) {
  82677. case BABYLON.PhysicsJoint.HingeJoint:
  82678. case BABYLON.PhysicsJoint.Hinge2Joint:
  82679. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  82680. break;
  82681. case BABYLON.PhysicsJoint.DistanceJoint:
  82682. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  82683. break;
  82684. case BABYLON.PhysicsJoint.SpringJoint:
  82685. var springData = jointData;
  82686. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  82687. restLength: springData.length,
  82688. stiffness: springData.stiffness,
  82689. damping: springData.damping,
  82690. localAnchorA: constraintData.pivotA,
  82691. localAnchorB: constraintData.pivotB
  82692. });
  82693. break;
  82694. case BABYLON.PhysicsJoint.LockJoint:
  82695. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  82696. break;
  82697. case BABYLON.PhysicsJoint.PointToPointJoint:
  82698. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82699. default:
  82700. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  82701. break;
  82702. }
  82703. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  82704. constraint.collideConnected = !!jointData.collision;
  82705. impostorJoint.joint.physicsJoint = constraint;
  82706. //don't add spring as constraint, as it is not one.
  82707. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  82708. this.world.addConstraint(constraint);
  82709. }
  82710. else {
  82711. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  82712. constraint.applyForce();
  82713. });
  82714. }
  82715. };
  82716. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82717. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  82718. };
  82719. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  82720. var index;
  82721. var mat;
  82722. for (index = 0; index < this._physicsMaterials.length; index++) {
  82723. mat = this._physicsMaterials[index];
  82724. if (mat.friction === friction && mat.restitution === restitution) {
  82725. return mat;
  82726. }
  82727. }
  82728. var currentMat = new this.BJSCANNON.Material(name);
  82729. currentMat.friction = friction;
  82730. currentMat.restitution = restitution;
  82731. this._physicsMaterials.push(currentMat);
  82732. return currentMat;
  82733. };
  82734. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  82735. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  82736. };
  82737. CannonJSPlugin.prototype._createShape = function (impostor) {
  82738. var object = impostor.object;
  82739. var returnValue;
  82740. var extendSize = impostor.getObjectExtendSize();
  82741. switch (impostor.type) {
  82742. case BABYLON.PhysicsImpostor.SphereImpostor:
  82743. var radiusX = extendSize.x;
  82744. var radiusY = extendSize.y;
  82745. var radiusZ = extendSize.z;
  82746. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  82747. break;
  82748. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  82749. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82750. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  82751. break;
  82752. case BABYLON.PhysicsImpostor.BoxImpostor:
  82753. var box = extendSize.scale(0.5);
  82754. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  82755. break;
  82756. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82757. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  82758. returnValue = new this.BJSCANNON.Plane();
  82759. break;
  82760. case BABYLON.PhysicsImpostor.MeshImpostor:
  82761. // should transform the vertex data to world coordinates!!
  82762. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  82763. var rawFaces = object.getIndices ? object.getIndices() : [];
  82764. if (!rawVerts)
  82765. return;
  82766. // get only scale! so the object could transform correctly.
  82767. var oldPosition = object.position.clone();
  82768. var oldRotation = object.rotation && object.rotation.clone();
  82769. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  82770. object.position.copyFromFloats(0, 0, 0);
  82771. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82772. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82773. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82774. var transform = object.computeWorldMatrix(true);
  82775. // convert rawVerts to object space
  82776. var temp = new Array();
  82777. var index;
  82778. for (index = 0; index < rawVerts.length; index += 3) {
  82779. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  82780. }
  82781. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  82782. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  82783. //now set back the transformation!
  82784. object.position.copyFrom(oldPosition);
  82785. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  82786. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  82787. break;
  82788. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  82789. var oldPosition2 = object.position.clone();
  82790. var oldRotation2 = object.rotation && object.rotation.clone();
  82791. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  82792. object.position.copyFromFloats(0, 0, 0);
  82793. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82794. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82795. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82796. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  82797. returnValue = this._createHeightmap(object);
  82798. object.position.copyFrom(oldPosition2);
  82799. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  82800. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  82801. object.computeWorldMatrix(true);
  82802. break;
  82803. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82804. returnValue = new this.BJSCANNON.Particle();
  82805. break;
  82806. }
  82807. return returnValue;
  82808. };
  82809. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  82810. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  82811. var transform = object.computeWorldMatrix(true);
  82812. // convert rawVerts to object space
  82813. var temp = new Array();
  82814. var index;
  82815. for (index = 0; index < pos.length; index += 3) {
  82816. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  82817. }
  82818. pos = temp;
  82819. var matrix = new Array();
  82820. //For now pointDepth will not be used and will be automatically calculated.
  82821. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  82822. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  82823. var boundingInfo = object.getBoundingInfo();
  82824. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  82825. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  82826. var elementSize = dim * 2 / arraySize;
  82827. for (var i = 0; i < pos.length; i = i + 3) {
  82828. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  82829. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  82830. var y = -pos[i + 2] + minY;
  82831. if (!matrix[x]) {
  82832. matrix[x] = [];
  82833. }
  82834. if (!matrix[x][z]) {
  82835. matrix[x][z] = y;
  82836. }
  82837. matrix[x][z] = Math.max(y, matrix[x][z]);
  82838. }
  82839. for (var x = 0; x <= arraySize; ++x) {
  82840. if (!matrix[x]) {
  82841. var loc = 1;
  82842. while (!matrix[(x + loc) % arraySize]) {
  82843. loc++;
  82844. }
  82845. matrix[x] = matrix[(x + loc) % arraySize].slice();
  82846. //console.log("missing x", x);
  82847. }
  82848. for (var z = 0; z <= arraySize; ++z) {
  82849. if (!matrix[x][z]) {
  82850. var loc = 1;
  82851. var newValue;
  82852. while (newValue === undefined) {
  82853. newValue = matrix[x][(z + loc++) % arraySize];
  82854. }
  82855. matrix[x][z] = newValue;
  82856. }
  82857. }
  82858. }
  82859. var shape = new this.BJSCANNON.Heightfield(matrix, {
  82860. elementSize: elementSize
  82861. });
  82862. //For future reference, needed for body transformation
  82863. shape.minY = minY;
  82864. return shape;
  82865. };
  82866. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  82867. var object = impostor.object;
  82868. //make sure it is updated...
  82869. object.computeWorldMatrix && object.computeWorldMatrix(true);
  82870. // The delta between the mesh position and the mesh bounding box center
  82871. var bInfo = object.getBoundingInfo();
  82872. if (!bInfo)
  82873. return;
  82874. var center = impostor.getObjectCenter();
  82875. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  82876. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  82877. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  82878. this._tmpPosition.copyFrom(center);
  82879. var quaternion = object.rotationQuaternion;
  82880. if (!quaternion) {
  82881. return;
  82882. }
  82883. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  82884. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  82885. //-90 DEG in X, precalculated
  82886. quaternion = quaternion.multiply(this._minus90X);
  82887. //Invert! (Precalculated, 90 deg in X)
  82888. //No need to clone. this will never change.
  82889. impostor.setDeltaRotation(this._plus90X);
  82890. }
  82891. //If it is a heightfield, if should be centered.
  82892. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  82893. var mesh = object;
  82894. var boundingInfo = mesh.getBoundingInfo();
  82895. //calculate the correct body position:
  82896. var rotationQuaternion = mesh.rotationQuaternion;
  82897. mesh.rotationQuaternion = this._tmpUnityRotation;
  82898. mesh.computeWorldMatrix(true);
  82899. //get original center with no rotation
  82900. var c = center.clone();
  82901. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  82902. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  82903. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  82904. mesh.setPreTransformMatrix(p);
  82905. mesh.computeWorldMatrix(true);
  82906. //calculate the translation
  82907. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  82908. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  82909. //add it inverted to the delta
  82910. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  82911. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  82912. //rotation is back
  82913. mesh.rotationQuaternion = rotationQuaternion;
  82914. mesh.setPreTransformMatrix(oldPivot);
  82915. mesh.computeWorldMatrix(true);
  82916. }
  82917. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  82918. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  82919. //this._tmpPosition.copyFrom(object.position);
  82920. }
  82921. impostor.setDeltaPosition(this._tmpDeltaPosition);
  82922. //Now update the impostor object
  82923. impostor.physicsBody.position.copy(this._tmpPosition);
  82924. impostor.physicsBody.quaternion.copy(quaternion);
  82925. };
  82926. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82927. impostor.object.position.copyFrom(impostor.physicsBody.position);
  82928. if (impostor.object.rotationQuaternion) {
  82929. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  82930. }
  82931. };
  82932. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82933. impostor.physicsBody.position.copy(newPosition);
  82934. impostor.physicsBody.quaternion.copy(newRotation);
  82935. };
  82936. CannonJSPlugin.prototype.isSupported = function () {
  82937. return this.BJSCANNON !== undefined;
  82938. };
  82939. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82940. impostor.physicsBody.velocity.copy(velocity);
  82941. };
  82942. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82943. impostor.physicsBody.angularVelocity.copy(velocity);
  82944. };
  82945. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82946. var v = impostor.physicsBody.velocity;
  82947. if (!v) {
  82948. return null;
  82949. }
  82950. return new BABYLON.Vector3(v.x, v.y, v.z);
  82951. };
  82952. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82953. var v = impostor.physicsBody.angularVelocity;
  82954. if (!v) {
  82955. return null;
  82956. }
  82957. return new BABYLON.Vector3(v.x, v.y, v.z);
  82958. };
  82959. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82960. impostor.physicsBody.mass = mass;
  82961. impostor.physicsBody.updateMassProperties();
  82962. };
  82963. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  82964. return impostor.physicsBody.mass;
  82965. };
  82966. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  82967. return impostor.physicsBody.material.friction;
  82968. };
  82969. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82970. impostor.physicsBody.material.friction = friction;
  82971. };
  82972. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82973. return impostor.physicsBody.material.restitution;
  82974. };
  82975. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82976. impostor.physicsBody.material.restitution = restitution;
  82977. };
  82978. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  82979. impostor.physicsBody.sleep();
  82980. };
  82981. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  82982. impostor.physicsBody.wakeUp();
  82983. };
  82984. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82985. joint.physicsJoint.distance = maxDistance;
  82986. };
  82987. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82988. // if (!motorIndex) {
  82989. // joint.physicsJoint.enableMotor();
  82990. // }
  82991. // }
  82992. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82993. // if (!motorIndex) {
  82994. // joint.physicsJoint.disableMotor();
  82995. // }
  82996. // }
  82997. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82998. if (!motorIndex) {
  82999. joint.physicsJoint.enableMotor();
  83000. joint.physicsJoint.setMotorSpeed(speed);
  83001. if (maxForce) {
  83002. this.setLimit(joint, maxForce);
  83003. }
  83004. }
  83005. };
  83006. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83007. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83008. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83009. };
  83010. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83011. var body = impostor.physicsBody;
  83012. mesh.position.x = body.position.x;
  83013. mesh.position.y = body.position.y;
  83014. mesh.position.z = body.position.z;
  83015. if (mesh.rotationQuaternion) {
  83016. mesh.rotationQuaternion.x = body.quaternion.x;
  83017. mesh.rotationQuaternion.y = body.quaternion.y;
  83018. mesh.rotationQuaternion.z = body.quaternion.z;
  83019. mesh.rotationQuaternion.w = body.quaternion.w;
  83020. }
  83021. };
  83022. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83023. var shape = impostor.physicsBody.shapes[0];
  83024. return shape.boundingSphereRadius;
  83025. };
  83026. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83027. var shape = impostor.physicsBody.shapes[0];
  83028. result.x = shape.halfExtents.x * 2;
  83029. result.y = shape.halfExtents.y * 2;
  83030. result.z = shape.halfExtents.z * 2;
  83031. };
  83032. CannonJSPlugin.prototype.dispose = function () {
  83033. };
  83034. CannonJSPlugin.prototype._extendNamespace = function () {
  83035. //this will force cannon to execute at least one step when using interpolation
  83036. var step_tmp1 = new this.BJSCANNON.Vec3();
  83037. var Engine = this.BJSCANNON;
  83038. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83039. maxSubSteps = maxSubSteps || 10;
  83040. timeSinceLastCalled = timeSinceLastCalled || 0;
  83041. if (timeSinceLastCalled === 0) {
  83042. this.internalStep(dt);
  83043. this.time += dt;
  83044. }
  83045. else {
  83046. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83047. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83048. var t0 = performance.now();
  83049. for (var i = 0; i !== internalSteps; i++) {
  83050. this.internalStep(dt);
  83051. if (performance.now() - t0 > dt * 1000) {
  83052. break;
  83053. }
  83054. }
  83055. this.time += timeSinceLastCalled;
  83056. var h = this.time % dt;
  83057. var h_div_dt = h / dt;
  83058. var interpvelo = step_tmp1;
  83059. var bodies = this.bodies;
  83060. for (var j = 0; j !== bodies.length; j++) {
  83061. var b = bodies[j];
  83062. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83063. b.position.vsub(b.previousPosition, interpvelo);
  83064. interpvelo.scale(h_div_dt, interpvelo);
  83065. b.position.vadd(interpvelo, b.interpolatedPosition);
  83066. }
  83067. else {
  83068. b.interpolatedPosition.copy(b.position);
  83069. b.interpolatedQuaternion.copy(b.quaternion);
  83070. }
  83071. }
  83072. }
  83073. };
  83074. };
  83075. return CannonJSPlugin;
  83076. }());
  83077. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83078. })(BABYLON || (BABYLON = {}));
  83079. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83080. var BABYLON;
  83081. (function (BABYLON) {
  83082. var OimoJSPlugin = /** @class */ (function () {
  83083. function OimoJSPlugin(iterations) {
  83084. this.name = "OimoJSPlugin";
  83085. this._tmpImpostorsArray = [];
  83086. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83087. this.BJSOIMO = OIMO;
  83088. this.world = new this.BJSOIMO.World({
  83089. iterations: iterations
  83090. });
  83091. this.world.clear();
  83092. }
  83093. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83094. this.world.gravity.copy(gravity);
  83095. };
  83096. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83097. this.world.timeStep = timeStep;
  83098. };
  83099. OimoJSPlugin.prototype.getTimeStep = function () {
  83100. return this.world.timeStep;
  83101. };
  83102. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83103. var _this = this;
  83104. impostors.forEach(function (impostor) {
  83105. impostor.beforeStep();
  83106. });
  83107. this.world.step();
  83108. impostors.forEach(function (impostor) {
  83109. impostor.afterStep();
  83110. //update the ordered impostors array
  83111. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83112. });
  83113. //check for collisions
  83114. var contact = this.world.contacts;
  83115. while (contact !== null) {
  83116. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83117. contact = contact.next;
  83118. continue;
  83119. }
  83120. //is this body colliding with any other? get the impostor
  83121. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83122. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83123. if (!mainImpostor || !collidingImpostor) {
  83124. contact = contact.next;
  83125. continue;
  83126. }
  83127. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83128. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83129. contact = contact.next;
  83130. }
  83131. };
  83132. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83133. var mass = impostor.physicsBody.mass;
  83134. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83135. };
  83136. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83137. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83138. this.applyImpulse(impostor, force, contactPoint);
  83139. };
  83140. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83141. var _this = this;
  83142. //parent-child relationship. Does this impostor has a parent impostor?
  83143. if (impostor.parent) {
  83144. if (impostor.physicsBody) {
  83145. this.removePhysicsBody(impostor);
  83146. //TODO is that needed?
  83147. impostor.forceUpdate();
  83148. }
  83149. return;
  83150. }
  83151. if (impostor.isBodyInitRequired()) {
  83152. var bodyConfig = {
  83153. name: impostor.uniqueId,
  83154. //Oimo must have mass, also for static objects.
  83155. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83156. size: [],
  83157. type: [],
  83158. pos: [],
  83159. posShape: [],
  83160. rot: [],
  83161. rotShape: [],
  83162. move: impostor.getParam("mass") !== 0,
  83163. density: impostor.getParam("mass"),
  83164. friction: impostor.getParam("friction"),
  83165. restitution: impostor.getParam("restitution"),
  83166. //Supporting older versions of Oimo
  83167. world: this.world
  83168. };
  83169. var impostors = [impostor];
  83170. var addToArray = function (parent) {
  83171. if (!parent.getChildMeshes)
  83172. return;
  83173. parent.getChildMeshes().forEach(function (m) {
  83174. if (m.physicsImpostor) {
  83175. impostors.push(m.physicsImpostor);
  83176. //m.physicsImpostor._init();
  83177. }
  83178. });
  83179. };
  83180. addToArray(impostor.object);
  83181. var checkWithEpsilon_1 = function (value) {
  83182. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83183. };
  83184. impostors.forEach(function (i) {
  83185. if (!i.object.rotationQuaternion) {
  83186. return;
  83187. }
  83188. //get the correct bounding box
  83189. var oldQuaternion = i.object.rotationQuaternion;
  83190. var rot = oldQuaternion.toEulerAngles();
  83191. var extendSize = i.getObjectExtendSize();
  83192. var radToDeg = 57.295779513082320876;
  83193. if (i === impostor) {
  83194. var center = impostor.getObjectCenter();
  83195. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83196. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83197. //Can also use Array.prototype.push.apply
  83198. bodyConfig.pos.push(center.x);
  83199. bodyConfig.pos.push(center.y);
  83200. bodyConfig.pos.push(center.z);
  83201. bodyConfig.posShape.push(0, 0, 0);
  83202. //tmp solution
  83203. bodyConfig.rot.push(rot.x * radToDeg);
  83204. bodyConfig.rot.push(rot.y * radToDeg);
  83205. bodyConfig.rot.push(rot.z * radToDeg);
  83206. bodyConfig.rotShape.push(0, 0, 0);
  83207. }
  83208. else {
  83209. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83210. bodyConfig.posShape.push(localPosition.x);
  83211. bodyConfig.posShape.push(localPosition.y);
  83212. bodyConfig.posShape.push(localPosition.z);
  83213. bodyConfig.pos.push(0, 0, 0);
  83214. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83215. bodyConfig.rot.push(0);
  83216. bodyConfig.rot.push(0);
  83217. bodyConfig.rot.push(0);
  83218. bodyConfig.rotShape.push(rot.x * radToDeg);
  83219. bodyConfig.rotShape.push(rot.y * radToDeg);
  83220. bodyConfig.rotShape.push(rot.z * radToDeg);
  83221. }
  83222. // register mesh
  83223. switch (i.type) {
  83224. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83225. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83226. case BABYLON.PhysicsImpostor.SphereImpostor:
  83227. var radiusX = extendSize.x;
  83228. var radiusY = extendSize.y;
  83229. var radiusZ = extendSize.z;
  83230. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83231. bodyConfig.type.push('sphere');
  83232. //due to the way oimo works with compounds, add 3 times
  83233. bodyConfig.size.push(size);
  83234. bodyConfig.size.push(size);
  83235. bodyConfig.size.push(size);
  83236. break;
  83237. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83238. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83239. var sizeY = checkWithEpsilon_1(extendSize.y);
  83240. bodyConfig.type.push('cylinder');
  83241. bodyConfig.size.push(sizeX);
  83242. bodyConfig.size.push(sizeY);
  83243. //due to the way oimo works with compounds, add one more value.
  83244. bodyConfig.size.push(sizeY);
  83245. break;
  83246. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83247. case BABYLON.PhysicsImpostor.BoxImpostor:
  83248. default:
  83249. var sizeX = checkWithEpsilon_1(extendSize.x);
  83250. var sizeY = checkWithEpsilon_1(extendSize.y);
  83251. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83252. bodyConfig.type.push('box');
  83253. //if (i === impostor) {
  83254. bodyConfig.size.push(sizeX);
  83255. bodyConfig.size.push(sizeY);
  83256. bodyConfig.size.push(sizeZ);
  83257. //} else {
  83258. // bodyConfig.size.push(0,0,0);
  83259. //}
  83260. break;
  83261. }
  83262. //actually not needed, but hey...
  83263. i.object.rotationQuaternion = oldQuaternion;
  83264. });
  83265. impostor.physicsBody = this.world.add(bodyConfig);
  83266. }
  83267. else {
  83268. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83269. }
  83270. impostor.setDeltaPosition(this._tmpPositionVector);
  83271. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83272. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83273. };
  83274. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83275. //impostor.physicsBody.dispose();
  83276. //Same as : (older oimo versions)
  83277. this.world.removeRigidBody(impostor.physicsBody);
  83278. };
  83279. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83280. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83281. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83282. if (!mainBody || !connectedBody) {
  83283. return;
  83284. }
  83285. var jointData = impostorJoint.joint.jointData;
  83286. var options = jointData.nativeParams || {};
  83287. var type;
  83288. var nativeJointData = {
  83289. body1: mainBody,
  83290. body2: connectedBody,
  83291. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83292. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83293. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83294. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83295. min: options.min,
  83296. max: options.max,
  83297. collision: options.collision || jointData.collision,
  83298. spring: options.spring,
  83299. //supporting older version of Oimo
  83300. world: this.world
  83301. };
  83302. switch (impostorJoint.joint.type) {
  83303. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83304. type = "jointBall";
  83305. break;
  83306. case BABYLON.PhysicsJoint.SpringJoint:
  83307. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83308. var springData = jointData;
  83309. nativeJointData.min = springData.length || nativeJointData.min;
  83310. //Max should also be set, just make sure it is at least min
  83311. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83312. case BABYLON.PhysicsJoint.DistanceJoint:
  83313. type = "jointDistance";
  83314. nativeJointData.max = jointData.maxDistance;
  83315. break;
  83316. case BABYLON.PhysicsJoint.PrismaticJoint:
  83317. type = "jointPrisme";
  83318. break;
  83319. case BABYLON.PhysicsJoint.SliderJoint:
  83320. type = "jointSlide";
  83321. break;
  83322. case BABYLON.PhysicsJoint.WheelJoint:
  83323. type = "jointWheel";
  83324. break;
  83325. case BABYLON.PhysicsJoint.HingeJoint:
  83326. default:
  83327. type = "jointHinge";
  83328. break;
  83329. }
  83330. nativeJointData.type = type;
  83331. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83332. };
  83333. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83334. //Bug in Oimo prevents us from disposing a joint in the playground
  83335. //joint.joint.physicsJoint.dispose();
  83336. //So we will bruteforce it!
  83337. try {
  83338. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83339. }
  83340. catch (e) {
  83341. BABYLON.Tools.Warn(e);
  83342. }
  83343. };
  83344. OimoJSPlugin.prototype.isSupported = function () {
  83345. return this.BJSOIMO !== undefined;
  83346. };
  83347. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83348. if (!impostor.physicsBody.sleeping) {
  83349. //TODO check that
  83350. /*if (impostor.physicsBody.shapes.next) {
  83351. var parentShape = this._getLastShape(impostor.physicsBody);
  83352. impostor.object.position.copyFrom(parentShape.position);
  83353. console.log(parentShape.position);
  83354. } else {*/
  83355. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83356. //}
  83357. if (impostor.object.rotationQuaternion) {
  83358. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83359. }
  83360. }
  83361. };
  83362. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83363. var body = impostor.physicsBody;
  83364. body.position.copy(newPosition);
  83365. body.orientation.copy(newRotation);
  83366. body.syncShapes();
  83367. body.awake();
  83368. };
  83369. /*private _getLastShape(body: any): any {
  83370. var lastShape = body.shapes;
  83371. while (lastShape.next) {
  83372. lastShape = lastShape.next;
  83373. }
  83374. return lastShape;
  83375. }*/
  83376. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83377. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83378. };
  83379. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83380. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83381. };
  83382. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83383. var v = impostor.physicsBody.linearVelocity;
  83384. if (!v) {
  83385. return null;
  83386. }
  83387. return new BABYLON.Vector3(v.x, v.y, v.z);
  83388. };
  83389. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83390. var v = impostor.physicsBody.angularVelocity;
  83391. if (!v) {
  83392. return null;
  83393. }
  83394. return new BABYLON.Vector3(v.x, v.y, v.z);
  83395. };
  83396. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83397. var staticBody = mass === 0;
  83398. //this will actually set the body's density and not its mass.
  83399. //But this is how oimo treats the mass variable.
  83400. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83401. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83402. };
  83403. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83404. return impostor.physicsBody.shapes.density;
  83405. };
  83406. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83407. return impostor.physicsBody.shapes.friction;
  83408. };
  83409. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83410. impostor.physicsBody.shapes.friction = friction;
  83411. };
  83412. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83413. return impostor.physicsBody.shapes.restitution;
  83414. };
  83415. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83416. impostor.physicsBody.shapes.restitution = restitution;
  83417. };
  83418. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83419. impostor.physicsBody.sleep();
  83420. };
  83421. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83422. impostor.physicsBody.awake();
  83423. };
  83424. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83425. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83426. if (minDistance !== void 0) {
  83427. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83428. }
  83429. };
  83430. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83431. //TODO separate rotational and transational motors.
  83432. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83433. if (motor) {
  83434. motor.setMotor(speed, maxForce);
  83435. }
  83436. };
  83437. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83438. //TODO separate rotational and transational motors.
  83439. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83440. if (motor) {
  83441. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83442. }
  83443. };
  83444. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83445. var body = impostor.physicsBody;
  83446. mesh.position.x = body.position.x;
  83447. mesh.position.y = body.position.y;
  83448. mesh.position.z = body.position.z;
  83449. if (mesh.rotationQuaternion) {
  83450. mesh.rotationQuaternion.x = body.orientation.x;
  83451. mesh.rotationQuaternion.y = body.orientation.y;
  83452. mesh.rotationQuaternion.z = body.orientation.z;
  83453. mesh.rotationQuaternion.w = body.orientation.s;
  83454. }
  83455. };
  83456. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83457. return impostor.physicsBody.shapes.radius;
  83458. };
  83459. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83460. var shape = impostor.physicsBody.shapes;
  83461. result.x = shape.halfWidth * 2;
  83462. result.y = shape.halfHeight * 2;
  83463. result.z = shape.halfDepth * 2;
  83464. };
  83465. OimoJSPlugin.prototype.dispose = function () {
  83466. this.world.clear();
  83467. };
  83468. return OimoJSPlugin;
  83469. }());
  83470. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83471. })(BABYLON || (BABYLON = {}));
  83472. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83473. var BABYLON;
  83474. (function (BABYLON) {
  83475. /*
  83476. * Based on jsTGALoader - Javascript loader for TGA file
  83477. * By Vincent Thibault
  83478. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83479. */
  83480. var TGATools = /** @class */ (function () {
  83481. function TGATools() {
  83482. }
  83483. TGATools.GetTGAHeader = function (data) {
  83484. var offset = 0;
  83485. var header = {
  83486. id_length: data[offset++],
  83487. colormap_type: data[offset++],
  83488. image_type: data[offset++],
  83489. colormap_index: data[offset++] | data[offset++] << 8,
  83490. colormap_length: data[offset++] | data[offset++] << 8,
  83491. colormap_size: data[offset++],
  83492. origin: [
  83493. data[offset++] | data[offset++] << 8,
  83494. data[offset++] | data[offset++] << 8
  83495. ],
  83496. width: data[offset++] | data[offset++] << 8,
  83497. height: data[offset++] | data[offset++] << 8,
  83498. pixel_size: data[offset++],
  83499. flags: data[offset++]
  83500. };
  83501. return header;
  83502. };
  83503. TGATools.UploadContent = function (gl, data) {
  83504. // Not enough data to contain header ?
  83505. if (data.length < 19) {
  83506. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83507. return;
  83508. }
  83509. // Read Header
  83510. var offset = 18;
  83511. var header = TGATools.GetTGAHeader(data);
  83512. // Assume it's a valid Targa file.
  83513. if (header.id_length + offset > data.length) {
  83514. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83515. return;
  83516. }
  83517. // Skip not needed data
  83518. offset += header.id_length;
  83519. var use_rle = false;
  83520. var use_pal = false;
  83521. var use_grey = false;
  83522. // Get some informations.
  83523. switch (header.image_type) {
  83524. case TGATools._TYPE_RLE_INDEXED:
  83525. use_rle = true;
  83526. case TGATools._TYPE_INDEXED:
  83527. use_pal = true;
  83528. break;
  83529. case TGATools._TYPE_RLE_RGB:
  83530. use_rle = true;
  83531. case TGATools._TYPE_RGB:
  83532. // use_rgb = true;
  83533. break;
  83534. case TGATools._TYPE_RLE_GREY:
  83535. use_rle = true;
  83536. case TGATools._TYPE_GREY:
  83537. use_grey = true;
  83538. break;
  83539. }
  83540. var pixel_data;
  83541. // var numAlphaBits = header.flags & 0xf;
  83542. var pixel_size = header.pixel_size >> 3;
  83543. var pixel_total = header.width * header.height * pixel_size;
  83544. // Read palettes
  83545. var palettes;
  83546. if (use_pal) {
  83547. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83548. }
  83549. // Read LRE
  83550. if (use_rle) {
  83551. pixel_data = new Uint8Array(pixel_total);
  83552. var c, count, i;
  83553. var localOffset = 0;
  83554. var pixels = new Uint8Array(pixel_size);
  83555. while (offset < pixel_total && localOffset < pixel_total) {
  83556. c = data[offset++];
  83557. count = (c & 0x7f) + 1;
  83558. // RLE pixels
  83559. if (c & 0x80) {
  83560. // Bind pixel tmp array
  83561. for (i = 0; i < pixel_size; ++i) {
  83562. pixels[i] = data[offset++];
  83563. }
  83564. // Copy pixel array
  83565. for (i = 0; i < count; ++i) {
  83566. pixel_data.set(pixels, localOffset + i * pixel_size);
  83567. }
  83568. localOffset += pixel_size * count;
  83569. }
  83570. // Raw pixels
  83571. else {
  83572. count *= pixel_size;
  83573. for (i = 0; i < count; ++i) {
  83574. pixel_data[localOffset + i] = data[offset++];
  83575. }
  83576. localOffset += count;
  83577. }
  83578. }
  83579. }
  83580. // RAW Pixels
  83581. else {
  83582. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83583. }
  83584. // Load to texture
  83585. var x_start, y_start, x_step, y_step, y_end, x_end;
  83586. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83587. default:
  83588. case TGATools._ORIGIN_UL:
  83589. x_start = 0;
  83590. x_step = 1;
  83591. x_end = header.width;
  83592. y_start = 0;
  83593. y_step = 1;
  83594. y_end = header.height;
  83595. break;
  83596. case TGATools._ORIGIN_BL:
  83597. x_start = 0;
  83598. x_step = 1;
  83599. x_end = header.width;
  83600. y_start = header.height - 1;
  83601. y_step = -1;
  83602. y_end = -1;
  83603. break;
  83604. case TGATools._ORIGIN_UR:
  83605. x_start = header.width - 1;
  83606. x_step = -1;
  83607. x_end = -1;
  83608. y_start = 0;
  83609. y_step = 1;
  83610. y_end = header.height;
  83611. break;
  83612. case TGATools._ORIGIN_BR:
  83613. x_start = header.width - 1;
  83614. x_step = -1;
  83615. x_end = -1;
  83616. y_start = header.height - 1;
  83617. y_step = -1;
  83618. y_end = -1;
  83619. break;
  83620. }
  83621. // Load the specify method
  83622. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  83623. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  83624. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  83625. };
  83626. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83627. var image = pixel_data, colormap = palettes;
  83628. var width = header.width, height = header.height;
  83629. var color, i = 0, x, y;
  83630. var imageData = new Uint8Array(width * height * 4);
  83631. for (y = y_start; y !== y_end; y += y_step) {
  83632. for (x = x_start; x !== x_end; x += x_step, i++) {
  83633. color = image[i];
  83634. imageData[(x + width * y) * 4 + 3] = 255;
  83635. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  83636. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  83637. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  83638. }
  83639. }
  83640. return imageData;
  83641. };
  83642. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83643. var image = pixel_data;
  83644. var width = header.width, height = header.height;
  83645. var color, i = 0, x, y;
  83646. var imageData = new Uint8Array(width * height * 4);
  83647. for (y = y_start; y !== y_end; y += y_step) {
  83648. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83649. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  83650. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  83651. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  83652. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  83653. imageData[(x + width * y) * 4 + 0] = r;
  83654. imageData[(x + width * y) * 4 + 1] = g;
  83655. imageData[(x + width * y) * 4 + 2] = b;
  83656. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  83657. }
  83658. }
  83659. return imageData;
  83660. };
  83661. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83662. var image = pixel_data;
  83663. var width = header.width, height = header.height;
  83664. var i = 0, x, y;
  83665. var imageData = new Uint8Array(width * height * 4);
  83666. for (y = y_start; y !== y_end; y += y_step) {
  83667. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  83668. imageData[(x + width * y) * 4 + 3] = 255;
  83669. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83670. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83671. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83672. }
  83673. }
  83674. return imageData;
  83675. };
  83676. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83677. var image = pixel_data;
  83678. var width = header.width, height = header.height;
  83679. var i = 0, x, y;
  83680. var imageData = new Uint8Array(width * height * 4);
  83681. for (y = y_start; y !== y_end; y += y_step) {
  83682. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  83683. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83684. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83685. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83686. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  83687. }
  83688. }
  83689. return imageData;
  83690. };
  83691. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83692. var image = pixel_data;
  83693. var width = header.width, height = header.height;
  83694. var color, i = 0, x, y;
  83695. var imageData = new Uint8Array(width * height * 4);
  83696. for (y = y_start; y !== y_end; y += y_step) {
  83697. for (x = x_start; x !== x_end; x += x_step, i++) {
  83698. color = image[i];
  83699. imageData[(x + width * y) * 4 + 0] = color;
  83700. imageData[(x + width * y) * 4 + 1] = color;
  83701. imageData[(x + width * y) * 4 + 2] = color;
  83702. imageData[(x + width * y) * 4 + 3] = 255;
  83703. }
  83704. }
  83705. return imageData;
  83706. };
  83707. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83708. var image = pixel_data;
  83709. var width = header.width, height = header.height;
  83710. var i = 0, x, y;
  83711. var imageData = new Uint8Array(width * height * 4);
  83712. for (y = y_start; y !== y_end; y += y_step) {
  83713. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83714. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  83715. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  83716. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83717. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  83718. }
  83719. }
  83720. return imageData;
  83721. };
  83722. //private static _TYPE_NO_DATA = 0;
  83723. TGATools._TYPE_INDEXED = 1;
  83724. TGATools._TYPE_RGB = 2;
  83725. TGATools._TYPE_GREY = 3;
  83726. TGATools._TYPE_RLE_INDEXED = 9;
  83727. TGATools._TYPE_RLE_RGB = 10;
  83728. TGATools._TYPE_RLE_GREY = 11;
  83729. TGATools._ORIGIN_MASK = 0x30;
  83730. TGATools._ORIGIN_SHIFT = 0x04;
  83731. TGATools._ORIGIN_BL = 0x00;
  83732. TGATools._ORIGIN_BR = 0x01;
  83733. TGATools._ORIGIN_UL = 0x02;
  83734. TGATools._ORIGIN_UR = 0x03;
  83735. return TGATools;
  83736. }());
  83737. BABYLON.TGATools = TGATools;
  83738. })(BABYLON || (BABYLON = {}));
  83739. //# sourceMappingURL=babylon.tga.js.map
  83740. var BABYLON;
  83741. (function (BABYLON) {
  83742. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  83743. // All values and structures referenced from:
  83744. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  83745. var DDS_MAGIC = 0x20534444;
  83746. var
  83747. //DDSD_CAPS = 0x1,
  83748. //DDSD_HEIGHT = 0x2,
  83749. //DDSD_WIDTH = 0x4,
  83750. //DDSD_PITCH = 0x8,
  83751. //DDSD_PIXELFORMAT = 0x1000,
  83752. DDSD_MIPMAPCOUNT = 0x20000;
  83753. //DDSD_LINEARSIZE = 0x80000,
  83754. //DDSD_DEPTH = 0x800000;
  83755. // var DDSCAPS_COMPLEX = 0x8,
  83756. // DDSCAPS_MIPMAP = 0x400000,
  83757. // DDSCAPS_TEXTURE = 0x1000;
  83758. var DDSCAPS2_CUBEMAP = 0x200;
  83759. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  83760. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  83761. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  83762. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  83763. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  83764. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  83765. // DDSCAPS2_VOLUME = 0x200000;
  83766. var
  83767. //DDPF_ALPHAPIXELS = 0x1,
  83768. //DDPF_ALPHA = 0x2,
  83769. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  83770. //DDPF_YUV = 0x200,
  83771. DDPF_LUMINANCE = 0x20000;
  83772. function FourCCToInt32(value) {
  83773. return value.charCodeAt(0) +
  83774. (value.charCodeAt(1) << 8) +
  83775. (value.charCodeAt(2) << 16) +
  83776. (value.charCodeAt(3) << 24);
  83777. }
  83778. function Int32ToFourCC(value) {
  83779. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  83780. }
  83781. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  83782. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  83783. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  83784. var FOURCC_DX10 = FourCCToInt32("DX10");
  83785. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  83786. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  83787. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  83788. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  83789. var headerLengthInt = 31; // The header length in 32 bit ints
  83790. // Offsets into the header array
  83791. var off_magic = 0;
  83792. var off_size = 1;
  83793. var off_flags = 2;
  83794. var off_height = 3;
  83795. var off_width = 4;
  83796. var off_mipmapCount = 7;
  83797. var off_pfFlags = 20;
  83798. var off_pfFourCC = 21;
  83799. var off_RGBbpp = 22;
  83800. var off_RMask = 23;
  83801. var off_GMask = 24;
  83802. var off_BMask = 25;
  83803. var off_AMask = 26;
  83804. // var off_caps1 = 27;
  83805. var off_caps2 = 28;
  83806. // var off_caps3 = 29;
  83807. // var off_caps4 = 30;
  83808. var off_dxgiFormat = 32;
  83809. ;
  83810. var DDSTools = /** @class */ (function () {
  83811. function DDSTools() {
  83812. }
  83813. DDSTools.GetDDSInfo = function (arrayBuffer) {
  83814. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83815. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  83816. var mipmapCount = 1;
  83817. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  83818. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83819. }
  83820. var fourCC = header[off_pfFourCC];
  83821. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  83822. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83823. switch (fourCC) {
  83824. case FOURCC_D3DFMT_R16G16B16A16F:
  83825. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83826. break;
  83827. case FOURCC_D3DFMT_R32G32B32A32F:
  83828. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83829. break;
  83830. case FOURCC_DX10:
  83831. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  83832. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83833. break;
  83834. }
  83835. }
  83836. return {
  83837. width: header[off_width],
  83838. height: header[off_height],
  83839. mipmapCount: mipmapCount,
  83840. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  83841. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  83842. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  83843. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  83844. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  83845. dxgiFormat: dxgiFormat,
  83846. textureType: textureType
  83847. };
  83848. };
  83849. DDSTools._ToHalfFloat = function (value) {
  83850. if (!DDSTools._FloatView) {
  83851. DDSTools._FloatView = new Float32Array(1);
  83852. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  83853. }
  83854. DDSTools._FloatView[0] = value;
  83855. var x = DDSTools._Int32View[0];
  83856. var bits = (x >> 16) & 0x8000; /* Get the sign */
  83857. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  83858. var e = (x >> 23) & 0xff; /* Using int is faster here */
  83859. /* If zero, or denormal, or exponent underflows too much for a denormal
  83860. * half, return signed zero. */
  83861. if (e < 103) {
  83862. return bits;
  83863. }
  83864. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  83865. if (e > 142) {
  83866. bits |= 0x7c00;
  83867. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  83868. * not Inf, so make sure we set one mantissa bit too. */
  83869. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  83870. return bits;
  83871. }
  83872. /* If exponent underflows but not too much, return a denormal */
  83873. if (e < 113) {
  83874. m |= 0x0800;
  83875. /* Extra rounding may overflow and set mantissa to 0 and exponent
  83876. * to 1, which is OK. */
  83877. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  83878. return bits;
  83879. }
  83880. bits |= ((e - 112) << 10) | (m >> 1);
  83881. bits += m & 1;
  83882. return bits;
  83883. };
  83884. DDSTools._FromHalfFloat = function (value) {
  83885. var s = (value & 0x8000) >> 15;
  83886. var e = (value & 0x7C00) >> 10;
  83887. var f = value & 0x03FF;
  83888. if (e === 0) {
  83889. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  83890. }
  83891. else if (e == 0x1F) {
  83892. return f ? NaN : ((s ? -1 : 1) * Infinity);
  83893. }
  83894. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  83895. };
  83896. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83897. var destArray = new Float32Array(dataLength);
  83898. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83899. var index = 0;
  83900. for (var y = 0; y < height; y++) {
  83901. for (var x = 0; x < width; x++) {
  83902. var srcPos = (x + y * width) * 4;
  83903. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  83904. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  83905. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  83906. if (DDSTools.StoreLODInAlphaChannel) {
  83907. destArray[index + 3] = lod;
  83908. }
  83909. else {
  83910. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  83911. }
  83912. index += 4;
  83913. }
  83914. }
  83915. return destArray;
  83916. };
  83917. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83918. if (DDSTools.StoreLODInAlphaChannel) {
  83919. var destArray = new Uint16Array(dataLength);
  83920. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83921. var index = 0;
  83922. for (var y = 0; y < height; y++) {
  83923. for (var x = 0; x < width; x++) {
  83924. var srcPos = (x + y * width) * 4;
  83925. destArray[index] = srcData[srcPos];
  83926. destArray[index + 1] = srcData[srcPos + 1];
  83927. destArray[index + 2] = srcData[srcPos + 2];
  83928. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  83929. index += 4;
  83930. }
  83931. }
  83932. return destArray;
  83933. }
  83934. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  83935. };
  83936. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83937. if (DDSTools.StoreLODInAlphaChannel) {
  83938. var destArray = new Float32Array(dataLength);
  83939. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83940. var index = 0;
  83941. for (var y = 0; y < height; y++) {
  83942. for (var x = 0; x < width; x++) {
  83943. var srcPos = (x + y * width) * 4;
  83944. destArray[index] = srcData[srcPos];
  83945. destArray[index + 1] = srcData[srcPos + 1];
  83946. destArray[index + 2] = srcData[srcPos + 2];
  83947. destArray[index + 3] = lod;
  83948. index += 4;
  83949. }
  83950. }
  83951. return destArray;
  83952. }
  83953. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  83954. };
  83955. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83956. var destArray = new Uint8Array(dataLength);
  83957. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83958. var index = 0;
  83959. for (var y = 0; y < height; y++) {
  83960. for (var x = 0; x < width; x++) {
  83961. var srcPos = (x + y * width) * 4;
  83962. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  83963. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  83964. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  83965. if (DDSTools.StoreLODInAlphaChannel) {
  83966. destArray[index + 3] = lod;
  83967. }
  83968. else {
  83969. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  83970. }
  83971. index += 4;
  83972. }
  83973. }
  83974. return destArray;
  83975. };
  83976. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83977. var destArray = new Uint8Array(dataLength);
  83978. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83979. var index = 0;
  83980. for (var y = 0; y < height; y++) {
  83981. for (var x = 0; x < width; x++) {
  83982. var srcPos = (x + y * width) * 4;
  83983. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  83984. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  83985. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  83986. if (DDSTools.StoreLODInAlphaChannel) {
  83987. destArray[index + 3] = lod;
  83988. }
  83989. else {
  83990. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  83991. }
  83992. index += 4;
  83993. }
  83994. }
  83995. return destArray;
  83996. };
  83997. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  83998. var byteArray = new Uint8Array(dataLength);
  83999. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84000. var index = 0;
  84001. for (var y = 0; y < height; y++) {
  84002. for (var x = 0; x < width; x++) {
  84003. var srcPos = (x + y * width) * 4;
  84004. byteArray[index] = srcData[srcPos + rOffset];
  84005. byteArray[index + 1] = srcData[srcPos + gOffset];
  84006. byteArray[index + 2] = srcData[srcPos + bOffset];
  84007. byteArray[index + 3] = srcData[srcPos + aOffset];
  84008. index += 4;
  84009. }
  84010. }
  84011. return byteArray;
  84012. };
  84013. DDSTools._ExtractLongWordOrder = function (value) {
  84014. if (value === 0 || value === 255 || value === -16777216) {
  84015. return 0;
  84016. }
  84017. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84018. };
  84019. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84020. var byteArray = new Uint8Array(dataLength);
  84021. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84022. var index = 0;
  84023. for (var y = 0; y < height; y++) {
  84024. for (var x = 0; x < width; x++) {
  84025. var srcPos = (x + y * width) * 3;
  84026. byteArray[index] = srcData[srcPos + rOffset];
  84027. byteArray[index + 1] = srcData[srcPos + gOffset];
  84028. byteArray[index + 2] = srcData[srcPos + bOffset];
  84029. index += 3;
  84030. }
  84031. }
  84032. return byteArray;
  84033. };
  84034. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84035. var byteArray = new Uint8Array(dataLength);
  84036. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84037. var index = 0;
  84038. for (var y = 0; y < height; y++) {
  84039. for (var x = 0; x < width; x++) {
  84040. var srcPos = (x + y * width);
  84041. byteArray[index] = srcData[srcPos];
  84042. index++;
  84043. }
  84044. }
  84045. return byteArray;
  84046. };
  84047. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84048. if (lodIndex === void 0) { lodIndex = -1; }
  84049. var ext = engine.getCaps().s3tc;
  84050. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84051. var fourCC, width, height, dataLength = 0, dataOffset;
  84052. var byteArray, mipmapCount, mip;
  84053. var internalFormat = 0;
  84054. var format = 0;
  84055. var blockBytes = 1;
  84056. if (header[off_magic] !== DDS_MAGIC) {
  84057. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84058. return;
  84059. }
  84060. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84061. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84062. return;
  84063. }
  84064. if (info.isCompressed && !ext) {
  84065. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84066. return;
  84067. }
  84068. var bpp = header[off_RGBbpp];
  84069. dataOffset = header[off_size] + 4;
  84070. var computeFormats = false;
  84071. if (info.isFourCC) {
  84072. fourCC = header[off_pfFourCC];
  84073. switch (fourCC) {
  84074. case FOURCC_DXT1:
  84075. blockBytes = 8;
  84076. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84077. break;
  84078. case FOURCC_DXT3:
  84079. blockBytes = 16;
  84080. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84081. break;
  84082. case FOURCC_DXT5:
  84083. blockBytes = 16;
  84084. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84085. break;
  84086. case FOURCC_D3DFMT_R16G16B16A16F:
  84087. computeFormats = true;
  84088. break;
  84089. case FOURCC_D3DFMT_R32G32B32A32F:
  84090. computeFormats = true;
  84091. break;
  84092. case FOURCC_DX10:
  84093. // There is an additionnal header so dataOffset need to be changed
  84094. dataOffset += 5 * 4; // 5 uints
  84095. var supported = false;
  84096. switch (info.dxgiFormat) {
  84097. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84098. computeFormats = true;
  84099. supported = true;
  84100. break;
  84101. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84102. info.isRGB = true;
  84103. info.isFourCC = false;
  84104. bpp = 32;
  84105. supported = true;
  84106. break;
  84107. }
  84108. if (supported) {
  84109. break;
  84110. }
  84111. default:
  84112. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84113. return;
  84114. }
  84115. }
  84116. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84117. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84118. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84119. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84120. if (computeFormats) {
  84121. format = engine._getWebGLTextureType(info.textureType);
  84122. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84123. }
  84124. mipmapCount = 1;
  84125. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84126. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84127. }
  84128. for (var face = 0; face < faces; face++) {
  84129. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84130. width = header[off_width];
  84131. height = header[off_height];
  84132. for (mip = 0; mip < mipmapCount; ++mip) {
  84133. if (lodIndex === -1 || lodIndex === mip) {
  84134. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84135. var i = (lodIndex === -1) ? mip : 0;
  84136. if (!info.isCompressed && info.isFourCC) {
  84137. dataLength = width * height * 4;
  84138. var floatArray = null;
  84139. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84140. if (bpp === 128) {
  84141. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84142. }
  84143. else if (bpp === 64) {
  84144. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84145. }
  84146. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84147. format = engine._getWebGLTextureType(info.textureType);
  84148. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84149. }
  84150. else {
  84151. if (bpp === 128) {
  84152. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84153. }
  84154. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84155. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84156. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84157. format = engine._getWebGLTextureType(info.textureType);
  84158. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84159. }
  84160. else { // 64
  84161. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84162. }
  84163. }
  84164. if (floatArray) {
  84165. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84166. }
  84167. }
  84168. else if (info.isRGB) {
  84169. if (bpp === 24) {
  84170. dataLength = width * height * 3;
  84171. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84172. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84173. }
  84174. else { // 32
  84175. dataLength = width * height * 4;
  84176. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84177. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84178. }
  84179. }
  84180. else if (info.isLuminance) {
  84181. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84182. var unpaddedRowSize = width;
  84183. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84184. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84185. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84186. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84187. }
  84188. else {
  84189. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84190. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84191. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84192. }
  84193. }
  84194. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84195. width *= 0.5;
  84196. height *= 0.5;
  84197. width = Math.max(1.0, width);
  84198. height = Math.max(1.0, height);
  84199. }
  84200. if (currentFace !== undefined) {
  84201. // Loading a single face
  84202. break;
  84203. }
  84204. }
  84205. };
  84206. DDSTools.StoreLODInAlphaChannel = false;
  84207. return DDSTools;
  84208. }());
  84209. BABYLON.DDSTools = DDSTools;
  84210. })(BABYLON || (BABYLON = {}));
  84211. //# sourceMappingURL=babylon.dds.js.map
  84212. var BABYLON;
  84213. (function (BABYLON) {
  84214. /**
  84215. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84216. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84217. */
  84218. var KhronosTextureContainer = /** @class */ (function () {
  84219. /**
  84220. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84221. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84222. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84223. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84224. */
  84225. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84226. this.arrayBuffer = arrayBuffer;
  84227. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84228. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84229. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84230. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84231. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84232. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84233. BABYLON.Tools.Error("texture missing KTX identifier");
  84234. return;
  84235. }
  84236. // load the reset of the header in native 32 bit int
  84237. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84238. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84239. var oppositeEndianess = header[0] === 0x01020304;
  84240. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84241. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84242. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84243. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84244. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84245. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84246. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84247. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84248. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84249. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84250. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84251. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84252. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84253. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84254. if (this.glType !== 0) {
  84255. BABYLON.Tools.Error("only compressed formats currently supported");
  84256. return;
  84257. }
  84258. else {
  84259. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84260. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84261. }
  84262. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84263. BABYLON.Tools.Error("only 2D textures currently supported");
  84264. return;
  84265. }
  84266. if (this.numberOfArrayElements !== 0) {
  84267. BABYLON.Tools.Error("texture arrays not currently supported");
  84268. return;
  84269. }
  84270. if (this.numberOfFaces !== facesExpected) {
  84271. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84272. return;
  84273. }
  84274. // we now have a completely validated file, so could use existence of loadType as success
  84275. // would need to make this more elaborate & adjust checks above to support more than one load type
  84276. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84277. }
  84278. // not as fast hardware based, but will probably never need to use
  84279. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84280. return ((val & 0xFF) << 24)
  84281. | ((val & 0xFF00) << 8)
  84282. | ((val >> 8) & 0xFF00)
  84283. | ((val >> 24) & 0xFF);
  84284. };
  84285. /**
  84286. * It is assumed that the texture has already been created & is currently bound
  84287. */
  84288. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84289. switch (this.loadType) {
  84290. case KhronosTextureContainer.COMPRESSED_2D:
  84291. this._upload2DCompressedLevels(gl, loadMipmaps);
  84292. break;
  84293. case KhronosTextureContainer.TEX_2D:
  84294. case KhronosTextureContainer.COMPRESSED_3D:
  84295. case KhronosTextureContainer.TEX_3D:
  84296. }
  84297. };
  84298. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84299. // initialize width & height for level 1
  84300. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84301. var width = this.pixelWidth;
  84302. var height = this.pixelHeight;
  84303. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84304. for (var level = 0; level < mipmapCount; level++) {
  84305. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84306. for (var face = 0; face < this.numberOfFaces; face++) {
  84307. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84308. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84309. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84310. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84311. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84312. }
  84313. width = Math.max(1.0, width * 0.5);
  84314. height = Math.max(1.0, height * 0.5);
  84315. }
  84316. };
  84317. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84318. // load types
  84319. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84320. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84321. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84322. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84323. return KhronosTextureContainer;
  84324. }());
  84325. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84326. })(BABYLON || (BABYLON = {}));
  84327. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84328. var BABYLON;
  84329. (function (BABYLON) {
  84330. var Debug;
  84331. (function (Debug) {
  84332. /**
  84333. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84334. */
  84335. var SkeletonViewer = /** @class */ (function () {
  84336. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84337. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84338. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84339. this.skeleton = skeleton;
  84340. this.mesh = mesh;
  84341. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84342. this.renderingGroupId = renderingGroupId;
  84343. this.color = BABYLON.Color3.White();
  84344. this._debugLines = new Array();
  84345. this._isEnabled = false;
  84346. this._scene = scene;
  84347. this.update();
  84348. this._renderFunction = this.update.bind(this);
  84349. }
  84350. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84351. get: function () {
  84352. return this._isEnabled;
  84353. },
  84354. set: function (value) {
  84355. if (this._isEnabled === value) {
  84356. return;
  84357. }
  84358. this._isEnabled = value;
  84359. if (value) {
  84360. this._scene.registerBeforeRender(this._renderFunction);
  84361. }
  84362. else {
  84363. this._scene.unregisterBeforeRender(this._renderFunction);
  84364. }
  84365. },
  84366. enumerable: true,
  84367. configurable: true
  84368. });
  84369. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84370. if (x === void 0) { x = 0; }
  84371. if (y === void 0) { y = 0; }
  84372. if (z === void 0) { z = 0; }
  84373. var tmat = BABYLON.Tmp.Matrix[0];
  84374. var parentBone = bone.getParent();
  84375. tmat.copyFrom(bone.getLocalMatrix());
  84376. if (x !== 0 || y !== 0 || z !== 0) {
  84377. var tmat2 = BABYLON.Tmp.Matrix[1];
  84378. BABYLON.Matrix.IdentityToRef(tmat2);
  84379. tmat2.m[12] = x;
  84380. tmat2.m[13] = y;
  84381. tmat2.m[14] = z;
  84382. tmat2.multiplyToRef(tmat, tmat);
  84383. }
  84384. if (parentBone) {
  84385. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84386. }
  84387. tmat.multiplyToRef(meshMat, tmat);
  84388. position.x = tmat.m[12];
  84389. position.y = tmat.m[13];
  84390. position.z = tmat.m[14];
  84391. };
  84392. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84393. var len = bones.length;
  84394. var meshPos = this.mesh.position;
  84395. for (var i = 0; i < len; i++) {
  84396. var bone = bones[i];
  84397. var points = this._debugLines[i];
  84398. if (!points) {
  84399. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84400. this._debugLines[i] = points;
  84401. }
  84402. this._getBonePosition(points[0], bone, meshMat);
  84403. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84404. points[0].subtractInPlace(meshPos);
  84405. points[1].subtractInPlace(meshPos);
  84406. }
  84407. };
  84408. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84409. var len = bones.length;
  84410. var boneNum = 0;
  84411. var meshPos = this.mesh.position;
  84412. for (var i = len - 1; i >= 0; i--) {
  84413. var childBone = bones[i];
  84414. var parentBone = childBone.getParent();
  84415. if (!parentBone) {
  84416. continue;
  84417. }
  84418. var points = this._debugLines[boneNum];
  84419. if (!points) {
  84420. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84421. this._debugLines[boneNum] = points;
  84422. }
  84423. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84424. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84425. points[0].subtractInPlace(meshPos);
  84426. points[1].subtractInPlace(meshPos);
  84427. boneNum++;
  84428. }
  84429. };
  84430. SkeletonViewer.prototype.update = function () {
  84431. if (this.autoUpdateBonesMatrices) {
  84432. this.skeleton.computeAbsoluteTransforms();
  84433. }
  84434. if (this.skeleton.bones[0].length === undefined) {
  84435. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84436. }
  84437. else {
  84438. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84439. }
  84440. if (!this._debugMesh) {
  84441. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84442. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84443. }
  84444. else {
  84445. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84446. }
  84447. this._debugMesh.position.copyFrom(this.mesh.position);
  84448. this._debugMesh.color = this.color;
  84449. };
  84450. SkeletonViewer.prototype.dispose = function () {
  84451. if (this._debugMesh) {
  84452. this.isEnabled = false;
  84453. this._debugMesh.dispose();
  84454. this._debugMesh = null;
  84455. }
  84456. };
  84457. return SkeletonViewer;
  84458. }());
  84459. Debug.SkeletonViewer = SkeletonViewer;
  84460. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84461. })(BABYLON || (BABYLON = {}));
  84462. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84463. /**
  84464. * Module Debug contains the (visual) components to debug a scene correctly
  84465. */
  84466. var BABYLON;
  84467. (function (BABYLON) {
  84468. var Debug;
  84469. (function (Debug) {
  84470. /**
  84471. * The Axes viewer will show 3 axes in a specific point in space
  84472. */
  84473. var AxesViewer = /** @class */ (function () {
  84474. function AxesViewer(scene, scaleLines) {
  84475. if (scaleLines === void 0) { scaleLines = 1; }
  84476. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84477. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84478. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84479. this.scaleLines = 1;
  84480. this.scaleLines = scaleLines;
  84481. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84482. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84483. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84484. this._xmesh.renderingGroupId = 2;
  84485. this._ymesh.renderingGroupId = 2;
  84486. this._zmesh.renderingGroupId = 2;
  84487. this._xmesh.material.checkReadyOnlyOnce = true;
  84488. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84489. this._ymesh.material.checkReadyOnlyOnce = true;
  84490. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84491. this._zmesh.material.checkReadyOnlyOnce = true;
  84492. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84493. this.scene = scene;
  84494. }
  84495. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84496. var scaleLines = this.scaleLines;
  84497. if (this._xmesh) {
  84498. this._xmesh.position.copyFrom(position);
  84499. }
  84500. if (this._ymesh) {
  84501. this._ymesh.position.copyFrom(position);
  84502. }
  84503. if (this._zmesh) {
  84504. this._zmesh.position.copyFrom(position);
  84505. }
  84506. var point2 = this._xline[1];
  84507. point2.x = xaxis.x * scaleLines;
  84508. point2.y = xaxis.y * scaleLines;
  84509. point2.z = xaxis.z * scaleLines;
  84510. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84511. point2 = this._yline[1];
  84512. point2.x = yaxis.x * scaleLines;
  84513. point2.y = yaxis.y * scaleLines;
  84514. point2.z = yaxis.z * scaleLines;
  84515. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84516. point2 = this._zline[1];
  84517. point2.x = zaxis.x * scaleLines;
  84518. point2.y = zaxis.y * scaleLines;
  84519. point2.z = zaxis.z * scaleLines;
  84520. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84521. };
  84522. AxesViewer.prototype.dispose = function () {
  84523. if (this._xmesh) {
  84524. this._xmesh.dispose();
  84525. }
  84526. if (this._ymesh) {
  84527. this._ymesh.dispose();
  84528. }
  84529. if (this._zmesh) {
  84530. this._zmesh.dispose();
  84531. }
  84532. this._xmesh = null;
  84533. this._ymesh = null;
  84534. this._zmesh = null;
  84535. this.scene = null;
  84536. };
  84537. return AxesViewer;
  84538. }());
  84539. Debug.AxesViewer = AxesViewer;
  84540. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84541. })(BABYLON || (BABYLON = {}));
  84542. //# sourceMappingURL=babylon.axesViewer.js.map
  84543. var BABYLON;
  84544. (function (BABYLON) {
  84545. var Debug;
  84546. (function (Debug) {
  84547. /**
  84548. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84549. */
  84550. var BoneAxesViewer = /** @class */ (function (_super) {
  84551. __extends(BoneAxesViewer, _super);
  84552. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84553. if (scaleLines === void 0) { scaleLines = 1; }
  84554. var _this = _super.call(this, scene, scaleLines) || this;
  84555. _this.pos = BABYLON.Vector3.Zero();
  84556. _this.xaxis = BABYLON.Vector3.Zero();
  84557. _this.yaxis = BABYLON.Vector3.Zero();
  84558. _this.zaxis = BABYLON.Vector3.Zero();
  84559. _this.mesh = mesh;
  84560. _this.bone = bone;
  84561. return _this;
  84562. }
  84563. BoneAxesViewer.prototype.update = function () {
  84564. if (!this.mesh || !this.bone) {
  84565. return;
  84566. }
  84567. var bone = this.bone;
  84568. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  84569. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  84570. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  84571. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  84572. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  84573. };
  84574. BoneAxesViewer.prototype.dispose = function () {
  84575. if (this.mesh) {
  84576. this.mesh = null;
  84577. this.bone = null;
  84578. _super.prototype.dispose.call(this);
  84579. }
  84580. };
  84581. return BoneAxesViewer;
  84582. }(Debug.AxesViewer));
  84583. Debug.BoneAxesViewer = BoneAxesViewer;
  84584. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84585. })(BABYLON || (BABYLON = {}));
  84586. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  84587. var BABYLON;
  84588. (function (BABYLON) {
  84589. var RayHelper = /** @class */ (function () {
  84590. function RayHelper(ray) {
  84591. this.ray = ray;
  84592. }
  84593. RayHelper.CreateAndShow = function (ray, scene, color) {
  84594. var helper = new RayHelper(ray);
  84595. helper.show(scene, color);
  84596. return helper;
  84597. };
  84598. RayHelper.prototype.show = function (scene, color) {
  84599. if (!this._renderFunction && this.ray) {
  84600. var ray = this.ray;
  84601. this._renderFunction = this._render.bind(this);
  84602. this._scene = scene;
  84603. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  84604. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  84605. if (this._renderFunction) {
  84606. this._scene.registerBeforeRender(this._renderFunction);
  84607. }
  84608. }
  84609. if (color && this._renderLine) {
  84610. this._renderLine.color.copyFrom(color);
  84611. }
  84612. };
  84613. RayHelper.prototype.hide = function () {
  84614. if (this._renderFunction && this._scene) {
  84615. this._scene.unregisterBeforeRender(this._renderFunction);
  84616. this._scene = null;
  84617. this._renderFunction = null;
  84618. if (this._renderLine) {
  84619. this._renderLine.dispose();
  84620. this._renderLine = null;
  84621. }
  84622. this._renderPoints = [];
  84623. }
  84624. };
  84625. RayHelper.prototype._render = function () {
  84626. var ray = this.ray;
  84627. if (!ray) {
  84628. return;
  84629. }
  84630. var point = this._renderPoints[1];
  84631. var len = Math.min(ray.length, 1000000);
  84632. point.copyFrom(ray.direction);
  84633. point.scaleInPlace(len);
  84634. point.addInPlace(ray.origin);
  84635. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  84636. };
  84637. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  84638. this._attachedToMesh = mesh;
  84639. var ray = this.ray;
  84640. if (!ray) {
  84641. return;
  84642. }
  84643. if (!ray.direction) {
  84644. ray.direction = BABYLON.Vector3.Zero();
  84645. }
  84646. if (!ray.origin) {
  84647. ray.origin = BABYLON.Vector3.Zero();
  84648. }
  84649. if (length) {
  84650. ray.length = length;
  84651. }
  84652. if (!meshSpaceOrigin) {
  84653. meshSpaceOrigin = BABYLON.Vector3.Zero();
  84654. }
  84655. if (!meshSpaceDirection) {
  84656. // -1 so that this will work with Mesh.lookAt
  84657. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  84658. }
  84659. if (!this._meshSpaceDirection) {
  84660. this._meshSpaceDirection = meshSpaceDirection.clone();
  84661. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  84662. }
  84663. else {
  84664. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  84665. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  84666. }
  84667. if (!this._updateToMeshFunction) {
  84668. this._updateToMeshFunction = this._updateToMesh.bind(this);
  84669. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  84670. }
  84671. this._updateToMesh();
  84672. };
  84673. RayHelper.prototype.detachFromMesh = function () {
  84674. if (this._attachedToMesh) {
  84675. if (this._updateToMeshFunction) {
  84676. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  84677. }
  84678. this._attachedToMesh = null;
  84679. this._updateToMeshFunction = null;
  84680. }
  84681. };
  84682. RayHelper.prototype._updateToMesh = function () {
  84683. var ray = this.ray;
  84684. if (!this._attachedToMesh || !ray) {
  84685. return;
  84686. }
  84687. if (this._attachedToMesh._isDisposed) {
  84688. this.detachFromMesh();
  84689. return;
  84690. }
  84691. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  84692. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  84693. };
  84694. RayHelper.prototype.dispose = function () {
  84695. this.hide();
  84696. this.detachFromMesh();
  84697. this.ray = null;
  84698. };
  84699. return RayHelper;
  84700. }());
  84701. BABYLON.RayHelper = RayHelper;
  84702. })(BABYLON || (BABYLON = {}));
  84703. //# sourceMappingURL=babylon.rayHelper.js.map
  84704. var BABYLON;
  84705. (function (BABYLON) {
  84706. // load the inspector using require, if not present in the global namespace.
  84707. var DebugLayer = /** @class */ (function () {
  84708. function DebugLayer(scene) {
  84709. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84710. this._scene = scene;
  84711. // load inspector using require, if it doesn't exist on the global namespace.
  84712. }
  84713. /** Creates the inspector window. */
  84714. DebugLayer.prototype._createInspector = function (config) {
  84715. if (config === void 0) { config = {}; }
  84716. var popup = config.popup || false;
  84717. var initialTab = config.initialTab || 0;
  84718. var parentElement = config.parentElement || null;
  84719. if (!this._inspector) {
  84720. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84721. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  84722. } // else nothing to do,; instance is already existing
  84723. };
  84724. DebugLayer.prototype.isVisible = function () {
  84725. if (!this._inspector) {
  84726. return false;
  84727. }
  84728. return true;
  84729. };
  84730. DebugLayer.prototype.hide = function () {
  84731. if (this._inspector) {
  84732. try {
  84733. this._inspector.dispose();
  84734. }
  84735. catch (e) {
  84736. // If the inspector has been removed directly from the inspector tool
  84737. }
  84738. this._inspector = null;
  84739. }
  84740. };
  84741. DebugLayer.prototype.show = function (config) {
  84742. if (config === void 0) { config = {}; }
  84743. if (typeof this.BJSINSPECTOR == 'undefined') {
  84744. // Load inspector and add it to the DOM
  84745. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  84746. }
  84747. else {
  84748. // Otherwise creates the inspector
  84749. this._createInspector(config);
  84750. }
  84751. };
  84752. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  84753. return DebugLayer;
  84754. }());
  84755. BABYLON.DebugLayer = DebugLayer;
  84756. })(BABYLON || (BABYLON = {}));
  84757. //# sourceMappingURL=babylon.debugLayer.js.map
  84758. var BABYLON;
  84759. (function (BABYLON) {
  84760. var Debug;
  84761. (function (Debug) {
  84762. /**
  84763. * Used to show the physics impostor around the specific mesh.
  84764. */
  84765. var PhysicsViewer = /** @class */ (function () {
  84766. function PhysicsViewer(scene) {
  84767. this._impostors = [];
  84768. this._meshes = [];
  84769. this._numMeshes = 0;
  84770. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84771. var physicEngine = this._scene.getPhysicsEngine();
  84772. if (physicEngine) {
  84773. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  84774. }
  84775. }
  84776. PhysicsViewer.prototype._updateDebugMeshes = function () {
  84777. var plugin = this._physicsEnginePlugin;
  84778. for (var i = 0; i < this._numMeshes; i++) {
  84779. var impostor = this._impostors[i];
  84780. if (!impostor) {
  84781. continue;
  84782. }
  84783. if (impostor.isDisposed) {
  84784. this.hideImpostor(this._impostors[i--]);
  84785. }
  84786. else {
  84787. var mesh = this._meshes[i];
  84788. if (mesh && plugin) {
  84789. plugin.syncMeshWithImpostor(mesh, impostor);
  84790. }
  84791. }
  84792. }
  84793. };
  84794. PhysicsViewer.prototype.showImpostor = function (impostor) {
  84795. if (!this._scene) {
  84796. return;
  84797. }
  84798. for (var i = 0; i < this._numMeshes; i++) {
  84799. if (this._impostors[i] == impostor) {
  84800. return;
  84801. }
  84802. }
  84803. var debugMesh = this._getDebugMesh(impostor, this._scene);
  84804. if (debugMesh) {
  84805. this._impostors[this._numMeshes] = impostor;
  84806. this._meshes[this._numMeshes] = debugMesh;
  84807. if (this._numMeshes === 0) {
  84808. this._renderFunction = this._updateDebugMeshes.bind(this);
  84809. this._scene.registerBeforeRender(this._renderFunction);
  84810. }
  84811. this._numMeshes++;
  84812. }
  84813. };
  84814. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  84815. if (!impostor || !this._scene) {
  84816. return;
  84817. }
  84818. var removed = false;
  84819. for (var i = 0; i < this._numMeshes; i++) {
  84820. if (this._impostors[i] == impostor) {
  84821. var mesh = this._meshes[i];
  84822. if (!mesh) {
  84823. continue;
  84824. }
  84825. this._scene.removeMesh(mesh);
  84826. mesh.dispose();
  84827. this._numMeshes--;
  84828. if (this._numMeshes > 0) {
  84829. this._meshes[i] = this._meshes[this._numMeshes];
  84830. this._impostors[i] = this._impostors[this._numMeshes];
  84831. this._meshes[this._numMeshes] = null;
  84832. this._impostors[this._numMeshes] = null;
  84833. }
  84834. else {
  84835. this._meshes[0] = null;
  84836. this._impostors[0] = null;
  84837. }
  84838. removed = true;
  84839. break;
  84840. }
  84841. }
  84842. if (removed && this._numMeshes === 0) {
  84843. this._scene.unregisterBeforeRender(this._renderFunction);
  84844. }
  84845. };
  84846. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  84847. if (!this._debugMaterial) {
  84848. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  84849. this._debugMaterial.wireframe = true;
  84850. }
  84851. return this._debugMaterial;
  84852. };
  84853. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  84854. if (!this._debugBoxMesh) {
  84855. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  84856. this._debugBoxMesh.renderingGroupId = 1;
  84857. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84858. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  84859. scene.removeMesh(this._debugBoxMesh);
  84860. }
  84861. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  84862. };
  84863. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  84864. if (!this._debugSphereMesh) {
  84865. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  84866. this._debugSphereMesh.renderingGroupId = 1;
  84867. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84868. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  84869. scene.removeMesh(this._debugSphereMesh);
  84870. }
  84871. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  84872. };
  84873. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  84874. var mesh = null;
  84875. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  84876. mesh = this._getDebugBoxMesh(scene);
  84877. impostor.getBoxSizeToRef(mesh.scaling);
  84878. }
  84879. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  84880. mesh = this._getDebugSphereMesh(scene);
  84881. var radius = impostor.getRadius();
  84882. mesh.scaling.x = radius * 2;
  84883. mesh.scaling.y = radius * 2;
  84884. mesh.scaling.z = radius * 2;
  84885. }
  84886. return mesh;
  84887. };
  84888. PhysicsViewer.prototype.dispose = function () {
  84889. for (var i = 0; i < this._numMeshes; i++) {
  84890. this.hideImpostor(this._impostors[i]);
  84891. }
  84892. if (this._debugBoxMesh) {
  84893. this._debugBoxMesh.dispose();
  84894. }
  84895. if (this._debugSphereMesh) {
  84896. this._debugSphereMesh.dispose();
  84897. }
  84898. if (this._debugMaterial) {
  84899. this._debugMaterial.dispose();
  84900. }
  84901. this._impostors.length = 0;
  84902. this._scene = null;
  84903. this._physicsEnginePlugin = null;
  84904. };
  84905. return PhysicsViewer;
  84906. }());
  84907. Debug.PhysicsViewer = PhysicsViewer;
  84908. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84909. })(BABYLON || (BABYLON = {}));
  84910. //# sourceMappingURL=babylon.physicsViewer.js.map
  84911. var BABYLON;
  84912. (function (BABYLON) {
  84913. var BoundingBoxRenderer = /** @class */ (function () {
  84914. function BoundingBoxRenderer(scene) {
  84915. this.frontColor = new BABYLON.Color3(1, 1, 1);
  84916. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  84917. this.showBackLines = true;
  84918. this.renderList = new BABYLON.SmartArray(32);
  84919. this._vertexBuffers = {};
  84920. this._scene = scene;
  84921. }
  84922. BoundingBoxRenderer.prototype._prepareRessources = function () {
  84923. if (this._colorShader) {
  84924. return;
  84925. }
  84926. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  84927. attributes: [BABYLON.VertexBuffer.PositionKind],
  84928. uniforms: ["world", "viewProjection", "color"]
  84929. });
  84930. var engine = this._scene.getEngine();
  84931. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  84932. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  84933. this._createIndexBuffer();
  84934. };
  84935. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  84936. var engine = this._scene.getEngine();
  84937. 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]);
  84938. };
  84939. BoundingBoxRenderer.prototype._rebuild = function () {
  84940. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84941. if (vb) {
  84942. vb._rebuild();
  84943. }
  84944. this._createIndexBuffer();
  84945. };
  84946. BoundingBoxRenderer.prototype.reset = function () {
  84947. this.renderList.reset();
  84948. };
  84949. BoundingBoxRenderer.prototype.render = function () {
  84950. if (this.renderList.length === 0) {
  84951. return;
  84952. }
  84953. this._prepareRessources();
  84954. if (!this._colorShader.isReady()) {
  84955. return;
  84956. }
  84957. var engine = this._scene.getEngine();
  84958. engine.setDepthWrite(false);
  84959. this._colorShader._preBind();
  84960. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  84961. var boundingBox = this.renderList.data[boundingBoxIndex];
  84962. var min = boundingBox.minimum;
  84963. var max = boundingBox.maximum;
  84964. var diff = max.subtract(min);
  84965. var median = min.add(diff.scale(0.5));
  84966. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84967. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84968. .multiply(boundingBox.getWorldMatrix());
  84969. // VBOs
  84970. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84971. if (this.showBackLines) {
  84972. // Back
  84973. engine.setDepthFunctionToGreaterOrEqual();
  84974. this._scene.resetCachedMaterial();
  84975. this._colorShader.setColor4("color", this.backColor.toColor4());
  84976. this._colorShader.bind(worldMatrix);
  84977. // Draw order
  84978. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84979. }
  84980. // Front
  84981. engine.setDepthFunctionToLess();
  84982. this._scene.resetCachedMaterial();
  84983. this._colorShader.setColor4("color", this.frontColor.toColor4());
  84984. this._colorShader.bind(worldMatrix);
  84985. // Draw order
  84986. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84987. }
  84988. this._colorShader.unbind();
  84989. engine.setDepthFunctionToLessOrEqual();
  84990. engine.setDepthWrite(true);
  84991. };
  84992. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  84993. this._prepareRessources();
  84994. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  84995. return;
  84996. }
  84997. var engine = this._scene.getEngine();
  84998. engine.setDepthWrite(false);
  84999. engine.setColorWrite(false);
  85000. this._colorShader._preBind();
  85001. var boundingBox = mesh._boundingInfo.boundingBox;
  85002. var min = boundingBox.minimum;
  85003. var max = boundingBox.maximum;
  85004. var diff = max.subtract(min);
  85005. var median = min.add(diff.scale(0.5));
  85006. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85007. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85008. .multiply(boundingBox.getWorldMatrix());
  85009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85010. engine.setDepthFunctionToLess();
  85011. this._scene.resetCachedMaterial();
  85012. this._colorShader.bind(worldMatrix);
  85013. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85014. this._colorShader.unbind();
  85015. engine.setDepthFunctionToLessOrEqual();
  85016. engine.setDepthWrite(true);
  85017. engine.setColorWrite(true);
  85018. };
  85019. BoundingBoxRenderer.prototype.dispose = function () {
  85020. if (!this._colorShader) {
  85021. return;
  85022. }
  85023. this.renderList.dispose();
  85024. this._colorShader.dispose();
  85025. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85026. if (buffer) {
  85027. buffer.dispose();
  85028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85029. }
  85030. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85031. };
  85032. return BoundingBoxRenderer;
  85033. }());
  85034. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85035. })(BABYLON || (BABYLON = {}));
  85036. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85037. var BABYLON;
  85038. (function (BABYLON) {
  85039. /**
  85040. * Defines a target to use with MorphTargetManager
  85041. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85042. */
  85043. var MorphTarget = /** @class */ (function () {
  85044. /**
  85045. * Creates a new MorphTarget
  85046. * @param name defines the name of the target
  85047. * @param influence defines the influence to use
  85048. */
  85049. function MorphTarget(
  85050. /** defines the name of the target */
  85051. name, influence) {
  85052. if (influence === void 0) { influence = 0; }
  85053. this.name = name;
  85054. /**
  85055. * Gets or sets the list of animations
  85056. */
  85057. this.animations = new Array();
  85058. this._positions = null;
  85059. this._normals = null;
  85060. this._tangents = null;
  85061. /**
  85062. * Observable raised when the influence changes
  85063. */
  85064. this.onInfluenceChanged = new BABYLON.Observable();
  85065. this.influence = influence;
  85066. }
  85067. Object.defineProperty(MorphTarget.prototype, "influence", {
  85068. /**
  85069. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85070. */
  85071. get: function () {
  85072. return this._influence;
  85073. },
  85074. set: function (influence) {
  85075. if (this._influence === influence) {
  85076. return;
  85077. }
  85078. var previous = this._influence;
  85079. this._influence = influence;
  85080. if (this.onInfluenceChanged.hasObservers) {
  85081. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85082. }
  85083. },
  85084. enumerable: true,
  85085. configurable: true
  85086. });
  85087. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85088. /**
  85089. * Gets a boolean defining if the target contains position data
  85090. */
  85091. get: function () {
  85092. return !!this._positions;
  85093. },
  85094. enumerable: true,
  85095. configurable: true
  85096. });
  85097. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85098. /**
  85099. * Gets a boolean defining if the target contains normal data
  85100. */
  85101. get: function () {
  85102. return !!this._normals;
  85103. },
  85104. enumerable: true,
  85105. configurable: true
  85106. });
  85107. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85108. /**
  85109. * Gets a boolean defining if the target contains tangent data
  85110. */
  85111. get: function () {
  85112. return !!this._tangents;
  85113. },
  85114. enumerable: true,
  85115. configurable: true
  85116. });
  85117. /**
  85118. * Affects position data to this target
  85119. * @param data defines the position data to use
  85120. */
  85121. MorphTarget.prototype.setPositions = function (data) {
  85122. this._positions = data;
  85123. };
  85124. /**
  85125. * Gets the position data stored in this target
  85126. * @returns a FloatArray containing the position data (or null if not present)
  85127. */
  85128. MorphTarget.prototype.getPositions = function () {
  85129. return this._positions;
  85130. };
  85131. /**
  85132. * Affects normal data to this target
  85133. * @param data defines the normal data to use
  85134. */
  85135. MorphTarget.prototype.setNormals = function (data) {
  85136. this._normals = data;
  85137. };
  85138. /**
  85139. * Gets the normal data stored in this target
  85140. * @returns a FloatArray containing the normal data (or null if not present)
  85141. */
  85142. MorphTarget.prototype.getNormals = function () {
  85143. return this._normals;
  85144. };
  85145. /**
  85146. * Affects tangent data to this target
  85147. * @param data defines the tangent data to use
  85148. */
  85149. MorphTarget.prototype.setTangents = function (data) {
  85150. this._tangents = data;
  85151. };
  85152. /**
  85153. * Gets the tangent data stored in this target
  85154. * @returns a FloatArray containing the tangent data (or null if not present)
  85155. */
  85156. MorphTarget.prototype.getTangents = function () {
  85157. return this._tangents;
  85158. };
  85159. /**
  85160. * Serializes the current target into a Serialization object
  85161. * @returns the serialized object
  85162. */
  85163. MorphTarget.prototype.serialize = function () {
  85164. var serializationObject = {};
  85165. serializationObject.name = this.name;
  85166. serializationObject.influence = this.influence;
  85167. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85168. if (this.hasNormals) {
  85169. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85170. }
  85171. if (this.hasTangents) {
  85172. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85173. }
  85174. // Animations
  85175. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85176. return serializationObject;
  85177. };
  85178. // Statics
  85179. /**
  85180. * Creates a new target from serialized data
  85181. * @param serializationObject defines the serialized data to use
  85182. * @returns a new MorphTarget
  85183. */
  85184. MorphTarget.Parse = function (serializationObject) {
  85185. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85186. result.setPositions(serializationObject.positions);
  85187. if (serializationObject.normals) {
  85188. result.setNormals(serializationObject.normals);
  85189. }
  85190. if (serializationObject.tangents) {
  85191. result.setTangents(serializationObject.tangents);
  85192. }
  85193. // Animations
  85194. if (serializationObject.animations) {
  85195. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85196. var parsedAnimation = serializationObject.animations[animationIndex];
  85197. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85198. }
  85199. }
  85200. return result;
  85201. };
  85202. /**
  85203. * Creates a MorphTarget from mesh data
  85204. * @param mesh defines the source mesh
  85205. * @param name defines the name to use for the new target
  85206. * @param influence defines the influence to attach to the target
  85207. * @returns a new MorphTarget
  85208. */
  85209. MorphTarget.FromMesh = function (mesh, name, influence) {
  85210. if (!name) {
  85211. name = mesh.name;
  85212. }
  85213. var result = new MorphTarget(name, influence);
  85214. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85216. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85217. }
  85218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85219. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85220. }
  85221. return result;
  85222. };
  85223. return MorphTarget;
  85224. }());
  85225. BABYLON.MorphTarget = MorphTarget;
  85226. })(BABYLON || (BABYLON = {}));
  85227. //# sourceMappingURL=babylon.morphTarget.js.map
  85228. var BABYLON;
  85229. (function (BABYLON) {
  85230. /**
  85231. * This class is used to deform meshes using morphing between different targets
  85232. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85233. */
  85234. var MorphTargetManager = /** @class */ (function () {
  85235. /**
  85236. * Creates a new MorphTargetManager
  85237. * @param scene defines the current scene
  85238. */
  85239. function MorphTargetManager(scene) {
  85240. if (scene === void 0) { scene = null; }
  85241. this._targets = new Array();
  85242. this._targetObservable = new Array();
  85243. this._activeTargets = new BABYLON.SmartArray(16);
  85244. this._supportsNormals = false;
  85245. this._supportsTangents = false;
  85246. this._vertexCount = 0;
  85247. this._uniqueId = 0;
  85248. this._tempInfluences = new Array();
  85249. if (!scene) {
  85250. scene = BABYLON.Engine.LastCreatedScene;
  85251. }
  85252. this._scene = scene;
  85253. if (this._scene) {
  85254. this._scene.morphTargetManagers.push(this);
  85255. this._uniqueId = this._scene.getUniqueId();
  85256. }
  85257. }
  85258. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85259. /**
  85260. * Gets the unique ID of this manager
  85261. */
  85262. get: function () {
  85263. return this._uniqueId;
  85264. },
  85265. enumerable: true,
  85266. configurable: true
  85267. });
  85268. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85269. /**
  85270. * Gets the number of vertices handled by this manager
  85271. */
  85272. get: function () {
  85273. return this._vertexCount;
  85274. },
  85275. enumerable: true,
  85276. configurable: true
  85277. });
  85278. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85279. /**
  85280. * Gets a boolean indicating if this manager supports morphing of normals
  85281. */
  85282. get: function () {
  85283. return this._supportsNormals;
  85284. },
  85285. enumerable: true,
  85286. configurable: true
  85287. });
  85288. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85289. /**
  85290. * Gets a boolean indicating if this manager supports morphing of tangents
  85291. */
  85292. get: function () {
  85293. return this._supportsTangents;
  85294. },
  85295. enumerable: true,
  85296. configurable: true
  85297. });
  85298. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85299. /**
  85300. * Gets the number of targets stored in this manager
  85301. */
  85302. get: function () {
  85303. return this._targets.length;
  85304. },
  85305. enumerable: true,
  85306. configurable: true
  85307. });
  85308. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85309. /**
  85310. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85311. */
  85312. get: function () {
  85313. return this._activeTargets.length;
  85314. },
  85315. enumerable: true,
  85316. configurable: true
  85317. });
  85318. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85319. /**
  85320. * Gets the list of influences (one per target)
  85321. */
  85322. get: function () {
  85323. return this._influences;
  85324. },
  85325. enumerable: true,
  85326. configurable: true
  85327. });
  85328. /**
  85329. * Gets the active target at specified index. An active target is a target with an influence > 0
  85330. * @param index defines the index to check
  85331. * @returns the requested target
  85332. */
  85333. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85334. return this._activeTargets.data[index];
  85335. };
  85336. /**
  85337. * Gets the target at specified index
  85338. * @param index defines the index to check
  85339. * @returns the requested target
  85340. */
  85341. MorphTargetManager.prototype.getTarget = function (index) {
  85342. return this._targets[index];
  85343. };
  85344. /**
  85345. * Add a new target to this manager
  85346. * @param target defines the target to add
  85347. */
  85348. MorphTargetManager.prototype.addTarget = function (target) {
  85349. var _this = this;
  85350. this._targets.push(target);
  85351. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85352. _this._syncActiveTargets(needUpdate);
  85353. }));
  85354. this._syncActiveTargets(true);
  85355. };
  85356. /**
  85357. * Removes a target from the manager
  85358. * @param target defines the target to remove
  85359. */
  85360. MorphTargetManager.prototype.removeTarget = function (target) {
  85361. var index = this._targets.indexOf(target);
  85362. if (index >= 0) {
  85363. this._targets.splice(index, 1);
  85364. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85365. this._syncActiveTargets(true);
  85366. }
  85367. };
  85368. /**
  85369. * Serializes the current manager into a Serialization object
  85370. * @returns the serialized object
  85371. */
  85372. MorphTargetManager.prototype.serialize = function () {
  85373. var serializationObject = {};
  85374. serializationObject.id = this.uniqueId;
  85375. serializationObject.targets = [];
  85376. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85377. var target = _a[_i];
  85378. serializationObject.targets.push(target.serialize());
  85379. }
  85380. return serializationObject;
  85381. };
  85382. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85383. var influenceCount = 0;
  85384. this._activeTargets.reset();
  85385. this._supportsNormals = true;
  85386. this._supportsTangents = true;
  85387. this._vertexCount = 0;
  85388. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85389. var target = _a[_i];
  85390. this._activeTargets.push(target);
  85391. this._tempInfluences[influenceCount++] = target.influence;
  85392. var positions = target.getPositions();
  85393. if (positions) {
  85394. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85395. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85396. var vertexCount = positions.length / 3;
  85397. if (this._vertexCount === 0) {
  85398. this._vertexCount = vertexCount;
  85399. }
  85400. else if (this._vertexCount !== vertexCount) {
  85401. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85402. return;
  85403. }
  85404. }
  85405. }
  85406. if (!this._influences || this._influences.length !== influenceCount) {
  85407. this._influences = new Float32Array(influenceCount);
  85408. }
  85409. for (var index = 0; index < influenceCount; index++) {
  85410. this._influences[index] = this._tempInfluences[index];
  85411. }
  85412. if (needUpdate) {
  85413. this.synchronize();
  85414. }
  85415. };
  85416. /**
  85417. * Syncrhonize the targets with all the meshes using this morph target manager
  85418. */
  85419. MorphTargetManager.prototype.synchronize = function () {
  85420. if (!this._scene) {
  85421. return;
  85422. }
  85423. // Flag meshes as dirty to resync with the active targets
  85424. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85425. var mesh = _a[_i];
  85426. if (mesh.morphTargetManager === this) {
  85427. mesh._syncGeometryWithMorphTargetManager();
  85428. }
  85429. }
  85430. };
  85431. // Statics
  85432. /**
  85433. * Creates a new MorphTargetManager from serialized data
  85434. * @param serializationObject defines the serialized data
  85435. * @param scene defines the hosting scene
  85436. * @returns the new MorphTargetManager
  85437. */
  85438. MorphTargetManager.Parse = function (serializationObject, scene) {
  85439. var result = new MorphTargetManager(scene);
  85440. result._uniqueId = serializationObject.id;
  85441. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85442. var targetData = _a[_i];
  85443. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85444. }
  85445. return result;
  85446. };
  85447. return MorphTargetManager;
  85448. }());
  85449. BABYLON.MorphTargetManager = MorphTargetManager;
  85450. })(BABYLON || (BABYLON = {}));
  85451. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85452. var BABYLON;
  85453. (function (BABYLON) {
  85454. var Octree = /** @class */ (function () {
  85455. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85456. if (maxDepth === void 0) { maxDepth = 2; }
  85457. this.maxDepth = maxDepth;
  85458. this.dynamicContent = new Array();
  85459. this._maxBlockCapacity = maxBlockCapacity || 64;
  85460. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85461. this._creationFunc = creationFunc;
  85462. }
  85463. // Methods
  85464. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85465. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85466. };
  85467. Octree.prototype.addMesh = function (entry) {
  85468. for (var index = 0; index < this.blocks.length; index++) {
  85469. var block = this.blocks[index];
  85470. block.addEntry(entry);
  85471. }
  85472. };
  85473. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85474. this._selectionContent.reset();
  85475. for (var index = 0; index < this.blocks.length; index++) {
  85476. var block = this.blocks[index];
  85477. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85478. }
  85479. if (allowDuplicate) {
  85480. this._selectionContent.concat(this.dynamicContent);
  85481. }
  85482. else {
  85483. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85484. }
  85485. return this._selectionContent;
  85486. };
  85487. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85488. this._selectionContent.reset();
  85489. for (var index = 0; index < this.blocks.length; index++) {
  85490. var block = this.blocks[index];
  85491. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85492. }
  85493. if (allowDuplicate) {
  85494. this._selectionContent.concat(this.dynamicContent);
  85495. }
  85496. else {
  85497. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85498. }
  85499. return this._selectionContent;
  85500. };
  85501. Octree.prototype.intersectsRay = function (ray) {
  85502. this._selectionContent.reset();
  85503. for (var index = 0; index < this.blocks.length; index++) {
  85504. var block = this.blocks[index];
  85505. block.intersectsRay(ray, this._selectionContent);
  85506. }
  85507. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85508. return this._selectionContent;
  85509. };
  85510. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85511. target.blocks = new Array();
  85512. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85513. // Segmenting space
  85514. for (var x = 0; x < 2; x++) {
  85515. for (var y = 0; y < 2; y++) {
  85516. for (var z = 0; z < 2; z++) {
  85517. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85518. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85519. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85520. block.addEntries(entries);
  85521. target.blocks.push(block);
  85522. }
  85523. }
  85524. }
  85525. };
  85526. Octree.CreationFuncForMeshes = function (entry, block) {
  85527. var boundingInfo = entry.getBoundingInfo();
  85528. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85529. block.entries.push(entry);
  85530. }
  85531. };
  85532. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85533. var boundingInfo = entry.getBoundingInfo();
  85534. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85535. block.entries.push(entry);
  85536. }
  85537. };
  85538. return Octree;
  85539. }());
  85540. BABYLON.Octree = Octree;
  85541. })(BABYLON || (BABYLON = {}));
  85542. //# sourceMappingURL=babylon.octree.js.map
  85543. var BABYLON;
  85544. (function (BABYLON) {
  85545. var OctreeBlock = /** @class */ (function () {
  85546. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85547. this.entries = new Array();
  85548. this._boundingVectors = new Array();
  85549. this._capacity = capacity;
  85550. this._depth = depth;
  85551. this._maxDepth = maxDepth;
  85552. this._creationFunc = creationFunc;
  85553. this._minPoint = minPoint;
  85554. this._maxPoint = maxPoint;
  85555. this._boundingVectors.push(minPoint.clone());
  85556. this._boundingVectors.push(maxPoint.clone());
  85557. this._boundingVectors.push(minPoint.clone());
  85558. this._boundingVectors[2].x = maxPoint.x;
  85559. this._boundingVectors.push(minPoint.clone());
  85560. this._boundingVectors[3].y = maxPoint.y;
  85561. this._boundingVectors.push(minPoint.clone());
  85562. this._boundingVectors[4].z = maxPoint.z;
  85563. this._boundingVectors.push(maxPoint.clone());
  85564. this._boundingVectors[5].z = minPoint.z;
  85565. this._boundingVectors.push(maxPoint.clone());
  85566. this._boundingVectors[6].x = minPoint.x;
  85567. this._boundingVectors.push(maxPoint.clone());
  85568. this._boundingVectors[7].y = minPoint.y;
  85569. }
  85570. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  85571. // Property
  85572. get: function () {
  85573. return this._capacity;
  85574. },
  85575. enumerable: true,
  85576. configurable: true
  85577. });
  85578. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  85579. get: function () {
  85580. return this._minPoint;
  85581. },
  85582. enumerable: true,
  85583. configurable: true
  85584. });
  85585. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  85586. get: function () {
  85587. return this._maxPoint;
  85588. },
  85589. enumerable: true,
  85590. configurable: true
  85591. });
  85592. // Methods
  85593. OctreeBlock.prototype.addEntry = function (entry) {
  85594. if (this.blocks) {
  85595. for (var index = 0; index < this.blocks.length; index++) {
  85596. var block = this.blocks[index];
  85597. block.addEntry(entry);
  85598. }
  85599. return;
  85600. }
  85601. this._creationFunc(entry, this);
  85602. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  85603. this.createInnerBlocks();
  85604. }
  85605. };
  85606. OctreeBlock.prototype.addEntries = function (entries) {
  85607. for (var index = 0; index < entries.length; index++) {
  85608. var mesh = entries[index];
  85609. this.addEntry(mesh);
  85610. }
  85611. };
  85612. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  85613. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  85614. if (this.blocks) {
  85615. for (var index = 0; index < this.blocks.length; index++) {
  85616. var block = this.blocks[index];
  85617. block.select(frustumPlanes, selection, allowDuplicate);
  85618. }
  85619. return;
  85620. }
  85621. if (allowDuplicate) {
  85622. selection.concat(this.entries);
  85623. }
  85624. else {
  85625. selection.concatWithNoDuplicate(this.entries);
  85626. }
  85627. }
  85628. };
  85629. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  85630. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  85631. if (this.blocks) {
  85632. for (var index = 0; index < this.blocks.length; index++) {
  85633. var block = this.blocks[index];
  85634. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  85635. }
  85636. return;
  85637. }
  85638. if (allowDuplicate) {
  85639. selection.concat(this.entries);
  85640. }
  85641. else {
  85642. selection.concatWithNoDuplicate(this.entries);
  85643. }
  85644. }
  85645. };
  85646. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  85647. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  85648. if (this.blocks) {
  85649. for (var index = 0; index < this.blocks.length; index++) {
  85650. var block = this.blocks[index];
  85651. block.intersectsRay(ray, selection);
  85652. }
  85653. return;
  85654. }
  85655. selection.concatWithNoDuplicate(this.entries);
  85656. }
  85657. };
  85658. OctreeBlock.prototype.createInnerBlocks = function () {
  85659. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  85660. };
  85661. return OctreeBlock;
  85662. }());
  85663. BABYLON.OctreeBlock = OctreeBlock;
  85664. })(BABYLON || (BABYLON = {}));
  85665. //# sourceMappingURL=babylon.octreeBlock.js.map
  85666. var BABYLON;
  85667. (function (BABYLON) {
  85668. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  85669. __extends(VRDistortionCorrectionPostProcess, _super);
  85670. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  85671. var _this = _super.call(this, name, "vrDistortionCorrection", [
  85672. 'LensCenter',
  85673. 'Scale',
  85674. 'ScaleIn',
  85675. 'HmdWarpParam'
  85676. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  85677. _this._isRightEye = isRightEye;
  85678. _this._distortionFactors = vrMetrics.distortionK;
  85679. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  85680. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  85681. _this.adaptScaleToCurrentViewport = true;
  85682. _this.onSizeChangedObservable.add(function () {
  85683. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  85684. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  85685. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  85686. });
  85687. _this.onApplyObservable.add(function (effect) {
  85688. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  85689. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  85690. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  85691. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  85692. });
  85693. return _this;
  85694. }
  85695. return VRDistortionCorrectionPostProcess;
  85696. }(BABYLON.PostProcess));
  85697. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  85698. })(BABYLON || (BABYLON = {}));
  85699. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  85700. var BABYLON;
  85701. (function (BABYLON) {
  85702. var AnaglyphPostProcess = /** @class */ (function (_super) {
  85703. __extends(AnaglyphPostProcess, _super);
  85704. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  85705. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  85706. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85707. _this.onApplyObservable.add(function (effect) {
  85708. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  85709. });
  85710. return _this;
  85711. }
  85712. return AnaglyphPostProcess;
  85713. }(BABYLON.PostProcess));
  85714. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  85715. })(BABYLON || (BABYLON = {}));
  85716. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  85717. var BABYLON;
  85718. (function (BABYLON) {
  85719. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  85720. __extends(StereoscopicInterlacePostProcess, _super);
  85721. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  85722. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  85723. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85724. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85725. _this.onSizeChangedObservable.add(function () {
  85726. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85727. });
  85728. _this.onApplyObservable.add(function (effect) {
  85729. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  85730. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  85731. });
  85732. return _this;
  85733. }
  85734. return StereoscopicInterlacePostProcess;
  85735. }(BABYLON.PostProcess));
  85736. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  85737. })(BABYLON || (BABYLON = {}));
  85738. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  85739. var BABYLON;
  85740. (function (BABYLON) {
  85741. /**
  85742. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  85743. * Screen rotation is taken into account.
  85744. */
  85745. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  85746. function FreeCameraDeviceOrientationInput() {
  85747. var _this = this;
  85748. this._screenOrientationAngle = 0;
  85749. this._screenQuaternion = new BABYLON.Quaternion();
  85750. this._alpha = 0;
  85751. this._beta = 0;
  85752. this._gamma = 0;
  85753. this._orientationChanged = function () {
  85754. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  85755. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  85756. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  85757. };
  85758. this._deviceOrientation = function (evt) {
  85759. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  85760. _this._beta = evt.beta !== null ? evt.beta : 0;
  85761. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  85762. };
  85763. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  85764. this._orientationChanged();
  85765. }
  85766. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  85767. get: function () {
  85768. return this._camera;
  85769. },
  85770. set: function (camera) {
  85771. this._camera = camera;
  85772. if (this._camera != null && !this._camera.rotationQuaternion) {
  85773. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  85774. }
  85775. },
  85776. enumerable: true,
  85777. configurable: true
  85778. });
  85779. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85780. window.addEventListener("orientationchange", this._orientationChanged);
  85781. window.addEventListener("deviceorientation", this._deviceOrientation);
  85782. //In certain cases, the attach control is called AFTER orientation was changed,
  85783. //So this is needed.
  85784. this._orientationChanged();
  85785. };
  85786. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  85787. window.removeEventListener("orientationchange", this._orientationChanged);
  85788. window.removeEventListener("deviceorientation", this._deviceOrientation);
  85789. };
  85790. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  85791. //if no device orientation provided, don't update the rotation.
  85792. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  85793. if (!this._alpha)
  85794. return;
  85795. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  85796. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  85797. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  85798. //Mirror on XY Plane
  85799. this._camera.rotationQuaternion.z *= -1;
  85800. this._camera.rotationQuaternion.w *= -1;
  85801. };
  85802. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  85803. return "FreeCameraDeviceOrientationInput";
  85804. };
  85805. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  85806. return "deviceOrientation";
  85807. };
  85808. return FreeCameraDeviceOrientationInput;
  85809. }());
  85810. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  85811. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  85812. })(BABYLON || (BABYLON = {}));
  85813. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  85814. var BABYLON;
  85815. (function (BABYLON) {
  85816. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  85817. function ArcRotateCameraVRDeviceOrientationInput() {
  85818. this.alphaCorrection = 1;
  85819. this.betaCorrection = 1;
  85820. this.gammaCorrection = 1;
  85821. this._alpha = 0;
  85822. this._gamma = 0;
  85823. this._dirty = false;
  85824. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  85825. }
  85826. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85827. this.camera.attachControl(element, noPreventDefault);
  85828. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  85829. };
  85830. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  85831. if (evt.alpha !== null) {
  85832. this._alpha = +evt.alpha | 0;
  85833. }
  85834. if (evt.gamma !== null) {
  85835. this._gamma = +evt.gamma | 0;
  85836. }
  85837. this._dirty = true;
  85838. };
  85839. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  85840. if (this._dirty) {
  85841. this._dirty = false;
  85842. if (this._gamma < 0) {
  85843. this._gamma = 180 + this._gamma;
  85844. }
  85845. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  85846. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  85847. }
  85848. };
  85849. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  85850. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  85851. };
  85852. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  85853. return "ArcRotateCameraVRDeviceOrientationInput";
  85854. };
  85855. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  85856. return "VRDeviceOrientation";
  85857. };
  85858. return ArcRotateCameraVRDeviceOrientationInput;
  85859. }());
  85860. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  85861. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  85862. })(BABYLON || (BABYLON = {}));
  85863. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  85864. var BABYLON;
  85865. (function (BABYLON) {
  85866. var VRCameraMetrics = /** @class */ (function () {
  85867. function VRCameraMetrics() {
  85868. this.compensateDistortion = true;
  85869. }
  85870. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  85871. get: function () {
  85872. return this.hResolution / (2 * this.vResolution);
  85873. },
  85874. enumerable: true,
  85875. configurable: true
  85876. });
  85877. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  85878. get: function () {
  85879. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  85880. },
  85881. enumerable: true,
  85882. configurable: true
  85883. });
  85884. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  85885. get: function () {
  85886. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85887. var h = (4 * meters) / this.hScreenSize;
  85888. return BABYLON.Matrix.Translation(h, 0, 0);
  85889. },
  85890. enumerable: true,
  85891. configurable: true
  85892. });
  85893. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  85894. get: function () {
  85895. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85896. var h = (4 * meters) / this.hScreenSize;
  85897. return BABYLON.Matrix.Translation(-h, 0, 0);
  85898. },
  85899. enumerable: true,
  85900. configurable: true
  85901. });
  85902. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  85903. get: function () {
  85904. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  85905. },
  85906. enumerable: true,
  85907. configurable: true
  85908. });
  85909. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  85910. get: function () {
  85911. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  85912. },
  85913. enumerable: true,
  85914. configurable: true
  85915. });
  85916. VRCameraMetrics.GetDefault = function () {
  85917. var result = new VRCameraMetrics();
  85918. result.hResolution = 1280;
  85919. result.vResolution = 800;
  85920. result.hScreenSize = 0.149759993;
  85921. result.vScreenSize = 0.0935999975;
  85922. result.vScreenCenter = 0.0467999987;
  85923. result.eyeToScreenDistance = 0.0410000011;
  85924. result.lensSeparationDistance = 0.0635000020;
  85925. result.interpupillaryDistance = 0.0640000030;
  85926. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  85927. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  85928. result.postProcessScaleFactor = 1.714605507808412;
  85929. result.lensCenterOffset = 0.151976421;
  85930. return result;
  85931. };
  85932. return VRCameraMetrics;
  85933. }());
  85934. BABYLON.VRCameraMetrics = VRCameraMetrics;
  85935. })(BABYLON || (BABYLON = {}));
  85936. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  85937. var BABYLON;
  85938. (function (BABYLON) {
  85939. /**
  85940. * This represents a WebVR camera.
  85941. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  85942. * @example http://doc.babylonjs.com/how_to/webvr_camera
  85943. */
  85944. var WebVRFreeCamera = /** @class */ (function (_super) {
  85945. __extends(WebVRFreeCamera, _super);
  85946. /**
  85947. * Instantiates a WebVRFreeCamera.
  85948. * @param name The name of the WebVRFreeCamera
  85949. * @param position The starting anchor position for the camera
  85950. * @param scene The scene the camera belongs to
  85951. * @param webVROptions a set of customizable options for the webVRCamera
  85952. */
  85953. function WebVRFreeCamera(name, position, scene, webVROptions) {
  85954. if (webVROptions === void 0) { webVROptions = {}; }
  85955. var _this = _super.call(this, name, position, scene) || this;
  85956. _this.webVROptions = webVROptions;
  85957. /**
  85958. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  85959. */
  85960. _this._vrDevice = null;
  85961. /**
  85962. * The rawPose of the vrDevice.
  85963. */
  85964. _this.rawPose = null;
  85965. _this._specsVersion = "1.1";
  85966. _this._attached = false;
  85967. _this._descendants = [];
  85968. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  85969. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  85970. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  85971. _this._standingMatrix = null;
  85972. /**
  85973. * Represents device position in babylon space.
  85974. */
  85975. _this.devicePosition = BABYLON.Vector3.Zero();
  85976. /**
  85977. * Represents device rotation in babylon space.
  85978. */
  85979. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  85980. /**
  85981. * The scale of the device to be used when translating from device space to babylon space.
  85982. */
  85983. _this.deviceScaleFactor = 1;
  85984. _this._deviceToWorld = BABYLON.Matrix.Identity();
  85985. _this._worldToDevice = BABYLON.Matrix.Identity();
  85986. /**
  85987. * References to the webVR controllers for the vrDevice.
  85988. */
  85989. _this.controllers = [];
  85990. /**
  85991. * Emits an event when a controller is attached.
  85992. */
  85993. _this.onControllersAttachedObservable = new BABYLON.Observable();
  85994. /**
  85995. * Emits an event when a controller's mesh has been loaded;
  85996. */
  85997. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85998. /**
  85999. * If the rig cameras be used as parent instead of this camera.
  86000. */
  86001. _this.rigParenting = true;
  86002. _this._defaultHeight = undefined;
  86003. _this._workingVector = BABYLON.Vector3.Zero();
  86004. _this._oneVector = BABYLON.Vector3.One();
  86005. _this._workingMatrix = BABYLON.Matrix.Identity();
  86006. _this._cache.position = BABYLON.Vector3.Zero();
  86007. if (webVROptions.defaultHeight) {
  86008. _this._defaultHeight = webVROptions.defaultHeight;
  86009. _this.position.y = _this._defaultHeight;
  86010. }
  86011. _this.minZ = 0.1;
  86012. //legacy support - the compensation boolean was removed.
  86013. if (arguments.length === 5) {
  86014. _this.webVROptions = arguments[4];
  86015. }
  86016. // default webVR options
  86017. if (_this.webVROptions.trackPosition == undefined) {
  86018. _this.webVROptions.trackPosition = true;
  86019. }
  86020. if (_this.webVROptions.controllerMeshes == undefined) {
  86021. _this.webVROptions.controllerMeshes = true;
  86022. }
  86023. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86024. _this.webVROptions.defaultLightingOnControllers = true;
  86025. }
  86026. _this.rotationQuaternion = new BABYLON.Quaternion();
  86027. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86028. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86029. }
  86030. //enable VR
  86031. var engine = _this.getEngine();
  86032. _this._onVREnabled = function (success) { if (success) {
  86033. _this.initControllers();
  86034. } };
  86035. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86036. engine.initWebVR().add(function (event) {
  86037. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86038. return;
  86039. }
  86040. _this._vrDevice = event.vrDisplay;
  86041. //reset the rig parameters.
  86042. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86043. if (_this._attached) {
  86044. _this.getEngine().enableVR();
  86045. }
  86046. });
  86047. if (typeof (VRFrameData) !== "undefined")
  86048. _this._frameData = new VRFrameData();
  86049. /**
  86050. * The idea behind the following lines:
  86051. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86052. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86053. * the second will not show it correctly.
  86054. *
  86055. * To solve this - each object that has the camera as parent will be added to a protected array.
  86056. * When the rig camera renders, it will take this array and set all of those to be its children.
  86057. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86058. * Amazing!
  86059. */
  86060. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86061. if (camera.parent === _this && _this.rigParenting) {
  86062. _this._descendants = _this.getDescendants(true, function (n) {
  86063. // don't take the cameras or the controllers!
  86064. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86065. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86066. return !isController && !isRigCamera;
  86067. });
  86068. _this._descendants.forEach(function (node) {
  86069. node.parent = camera;
  86070. });
  86071. }
  86072. });
  86073. scene.onAfterCameraRenderObservable.add(function (camera) {
  86074. if (camera.parent === _this && _this.rigParenting) {
  86075. _this._descendants.forEach(function (node) {
  86076. node.parent = _this;
  86077. });
  86078. }
  86079. });
  86080. return _this;
  86081. }
  86082. /**
  86083. * Gets the device distance from the ground in meters.
  86084. * @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.
  86085. */
  86086. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86087. if (this._standingMatrix) {
  86088. // Add standing matrix offset to get real offset from ground in room
  86089. this._standingMatrix.getTranslationToRef(this._workingVector);
  86090. return this._deviceRoomPosition.y + this._workingVector.y;
  86091. }
  86092. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86093. return this._defaultHeight || 0;
  86094. };
  86095. /**
  86096. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86097. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86098. */
  86099. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86100. var _this = this;
  86101. if (callback === void 0) { callback = function (bool) { }; }
  86102. // Use standing matrix if available
  86103. this.getEngine().initWebVRAsync().then(function (result) {
  86104. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86105. callback(false);
  86106. }
  86107. else {
  86108. _this._standingMatrix = new BABYLON.Matrix();
  86109. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86110. if (!_this.getScene().useRightHandedSystem) {
  86111. [2, 6, 8, 9, 14].forEach(function (num) {
  86112. if (_this._standingMatrix) {
  86113. _this._standingMatrix.m[num] *= -1;
  86114. }
  86115. });
  86116. }
  86117. callback(true);
  86118. }
  86119. });
  86120. };
  86121. /**
  86122. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86123. * @returns A promise with a boolean set to if the standing matrix is supported.
  86124. */
  86125. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86126. var _this = this;
  86127. return new Promise(function (res, rej) {
  86128. _this.useStandingMatrix(function (supported) {
  86129. res(supported);
  86130. });
  86131. });
  86132. };
  86133. /**
  86134. * Disposes the camera
  86135. */
  86136. WebVRFreeCamera.prototype.dispose = function () {
  86137. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86138. _super.prototype.dispose.call(this);
  86139. };
  86140. /**
  86141. * Gets a vrController by name.
  86142. * @param name The name of the controller to retreive
  86143. * @returns the controller matching the name specified or null if not found
  86144. */
  86145. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86146. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86147. var gp = _a[_i];
  86148. if (gp.hand === name) {
  86149. return gp;
  86150. }
  86151. }
  86152. return null;
  86153. };
  86154. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86155. /**
  86156. * The controller corrisponding to the users left hand.
  86157. */
  86158. get: function () {
  86159. if (!this._leftController) {
  86160. this._leftController = this.getControllerByName("left");
  86161. }
  86162. return this._leftController;
  86163. },
  86164. enumerable: true,
  86165. configurable: true
  86166. });
  86167. ;
  86168. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86169. /**
  86170. * The controller corrisponding to the users right hand.
  86171. */
  86172. get: function () {
  86173. if (!this._rightController) {
  86174. this._rightController = this.getControllerByName("right");
  86175. }
  86176. return this._rightController;
  86177. },
  86178. enumerable: true,
  86179. configurable: true
  86180. });
  86181. ;
  86182. /**
  86183. * Casts a ray forward from the vrCamera's gaze.
  86184. * @param length Length of the ray (default: 100)
  86185. * @returns the ray corrisponding to the gaze
  86186. */
  86187. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86188. if (length === void 0) { length = 100; }
  86189. if (this.leftCamera) {
  86190. // Use left eye to avoid computation to compute center on every call
  86191. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86192. }
  86193. else {
  86194. return _super.prototype.getForwardRay.call(this, length);
  86195. }
  86196. };
  86197. /**
  86198. * Updates the camera based on device's frame data
  86199. */
  86200. WebVRFreeCamera.prototype._checkInputs = function () {
  86201. if (this._vrDevice && this._vrDevice.isPresenting) {
  86202. this._vrDevice.getFrameData(this._frameData);
  86203. this.updateFromDevice(this._frameData.pose);
  86204. }
  86205. _super.prototype._checkInputs.call(this);
  86206. };
  86207. /**
  86208. * Updates the poseControlled values based on the input device pose.
  86209. * @param poseData Pose coming from the device
  86210. */
  86211. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86212. if (poseData && poseData.orientation) {
  86213. this.rawPose = poseData;
  86214. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86215. if (this.getScene().useRightHandedSystem) {
  86216. this._deviceRoomRotationQuaternion.z *= -1;
  86217. this._deviceRoomRotationQuaternion.w *= -1;
  86218. }
  86219. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86220. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86221. if (this.getScene().useRightHandedSystem) {
  86222. this._deviceRoomPosition.z *= -1;
  86223. }
  86224. }
  86225. }
  86226. };
  86227. /**
  86228. * WebVR's attach control will start broadcasting frames to the device.
  86229. * Note that in certain browsers (chrome for example) this function must be called
  86230. * within a user-interaction callback. Example:
  86231. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86232. *
  86233. * @param element html element to attach the vrDevice to
  86234. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86235. */
  86236. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86237. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86238. this._attached = true;
  86239. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86240. if (this._vrDevice) {
  86241. this.getEngine().enableVR();
  86242. }
  86243. };
  86244. /**
  86245. * Detaches the camera from the html element and disables VR
  86246. *
  86247. * @param element html element to detach from
  86248. */
  86249. WebVRFreeCamera.prototype.detachControl = function (element) {
  86250. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86251. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86252. _super.prototype.detachControl.call(this, element);
  86253. this._attached = false;
  86254. this.getEngine().disableVR();
  86255. };
  86256. /**
  86257. * @returns the name of this class
  86258. */
  86259. WebVRFreeCamera.prototype.getClassName = function () {
  86260. return "WebVRFreeCamera";
  86261. };
  86262. /**
  86263. * Calls resetPose on the vrDisplay
  86264. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86265. */
  86266. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86267. //uses the vrDisplay's "resetPose()".
  86268. //pitch and roll won't be affected.
  86269. this._vrDevice.resetPose();
  86270. };
  86271. /**
  86272. * Updates the rig cameras (left and right eye)
  86273. */
  86274. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86275. var camLeft = this._rigCameras[0];
  86276. var camRight = this._rigCameras[1];
  86277. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86278. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86279. camLeft.position.copyFrom(this._deviceRoomPosition);
  86280. camRight.position.copyFrom(this._deviceRoomPosition);
  86281. };
  86282. /**
  86283. * Updates the cached values of the camera
  86284. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86285. */
  86286. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86287. var _this = this;
  86288. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86289. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86290. if (!this.updateCacheCalled) {
  86291. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86292. this.updateCacheCalled = true;
  86293. this.update();
  86294. }
  86295. // Set working vector to the device position in room space rotated by the new rotation
  86296. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86297. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86298. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86299. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86300. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86301. // Add translation from anchor position
  86302. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86303. this._workingVector.addInPlace(this.position);
  86304. this._workingVector.subtractInPlace(this._cache.position);
  86305. this._deviceToWorld.setTranslation(this._workingVector);
  86306. // Set an inverted matrix to be used when updating the camera
  86307. this._deviceToWorld.invertToRef(this._worldToDevice);
  86308. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86309. this.controllers.forEach(function (controller) {
  86310. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86311. controller.update();
  86312. });
  86313. }
  86314. if (!ignoreParentClass) {
  86315. _super.prototype._updateCache.call(this);
  86316. }
  86317. this.updateCacheCalled = false;
  86318. };
  86319. /**
  86320. * Updates the current device position and rotation in the babylon world
  86321. */
  86322. WebVRFreeCamera.prototype.update = function () {
  86323. // Get current device position in babylon world
  86324. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86325. // Get current device rotation in babylon world
  86326. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86327. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86328. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86329. _super.prototype.update.call(this);
  86330. };
  86331. /**
  86332. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86333. * @returns an identity matrix
  86334. */
  86335. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86336. return BABYLON.Matrix.Identity();
  86337. };
  86338. /**
  86339. * This function is called by the two RIG cameras.
  86340. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86341. */
  86342. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86343. var _this = this;
  86344. // Update the parent camera prior to using a child camera to avoid desynchronization
  86345. var parentCamera = this._cameraRigParams["parentCamera"];
  86346. parentCamera._updateCache();
  86347. //WebVR 1.1
  86348. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86349. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86350. if (!this.getScene().useRightHandedSystem) {
  86351. [2, 6, 8, 9, 14].forEach(function (num) {
  86352. _this._webvrViewMatrix.m[num] *= -1;
  86353. });
  86354. }
  86355. // update the camera rotation matrix
  86356. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86357. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86358. // Computing target and final matrix
  86359. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86360. // should the view matrix be updated with scale and position offset?
  86361. if (parentCamera.deviceScaleFactor !== 1) {
  86362. this._webvrViewMatrix.invert();
  86363. // scale the position, if set
  86364. if (parentCamera.deviceScaleFactor) {
  86365. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86366. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86367. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86368. }
  86369. this._webvrViewMatrix.invert();
  86370. }
  86371. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86372. return this._webvrViewMatrix;
  86373. };
  86374. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86375. var _this = this;
  86376. var parentCamera = this.parent;
  86377. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86378. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86379. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86380. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86381. //babylon compatible matrix
  86382. if (!this.getScene().useRightHandedSystem) {
  86383. [8, 9, 10, 11].forEach(function (num) {
  86384. _this._projectionMatrix.m[num] *= -1;
  86385. });
  86386. }
  86387. return this._projectionMatrix;
  86388. };
  86389. /**
  86390. * Initializes the controllers and their meshes
  86391. */
  86392. WebVRFreeCamera.prototype.initControllers = function () {
  86393. var _this = this;
  86394. this.controllers = [];
  86395. var manager = this.getScene().gamepadManager;
  86396. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86397. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86398. var webVrController = gamepad;
  86399. if (webVrController.defaultModel) {
  86400. webVrController.defaultModel.setEnabled(false);
  86401. }
  86402. if (webVrController.hand === "right") {
  86403. _this._rightController = null;
  86404. }
  86405. if (webVrController.hand === "left") {
  86406. _this._leftController = null;
  86407. }
  86408. var controllerIndex = _this.controllers.indexOf(webVrController);
  86409. if (controllerIndex !== -1) {
  86410. _this.controllers.splice(controllerIndex, 1);
  86411. }
  86412. }
  86413. });
  86414. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86415. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86416. var webVrController_1 = gamepad;
  86417. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86418. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86419. if (_this.webVROptions.controllerMeshes) {
  86420. if (webVrController_1.defaultModel) {
  86421. webVrController_1.defaultModel.setEnabled(true);
  86422. }
  86423. else {
  86424. // Load the meshes
  86425. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86426. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86427. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86428. if (_this.webVROptions.defaultLightingOnControllers) {
  86429. if (!_this._lightOnControllers) {
  86430. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86431. }
  86432. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86433. var children = mesh.getChildren();
  86434. if (children.length !== 0) {
  86435. children.forEach(function (mesh) {
  86436. light.includedOnlyMeshes.push(mesh);
  86437. activateLightOnSubMeshes_1(mesh, light);
  86438. });
  86439. }
  86440. };
  86441. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86442. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86443. }
  86444. });
  86445. }
  86446. }
  86447. webVrController_1.attachToPoseControlledCamera(_this);
  86448. // since this is async - sanity check. Is the controller already stored?
  86449. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86450. //add to the controllers array
  86451. _this.controllers.push(webVrController_1);
  86452. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86453. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86454. // So we're overriding setting left & right manually to be sure
  86455. var firstViveWandDetected = false;
  86456. for (var i = 0; i < _this.controllers.length; i++) {
  86457. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86458. if (!firstViveWandDetected) {
  86459. firstViveWandDetected = true;
  86460. _this.controllers[i].hand = "left";
  86461. }
  86462. else {
  86463. _this.controllers[i].hand = "right";
  86464. }
  86465. }
  86466. }
  86467. //did we find enough controllers? Great! let the developer know.
  86468. if (_this.controllers.length >= 2) {
  86469. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86470. }
  86471. }
  86472. }
  86473. });
  86474. };
  86475. return WebVRFreeCamera;
  86476. }(BABYLON.FreeCamera));
  86477. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86478. })(BABYLON || (BABYLON = {}));
  86479. //# sourceMappingURL=babylon.webVRCamera.js.map
  86480. var BABYLON;
  86481. (function (BABYLON) {
  86482. // We're mainly based on the logic defined into the FreeCamera code
  86483. /**
  86484. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86485. * being tilted forward or back and left or right.
  86486. */
  86487. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86488. __extends(DeviceOrientationCamera, _super);
  86489. /**
  86490. * Creates a new device orientation camera
  86491. * @param name The name of the camera
  86492. * @param position The start position camera
  86493. * @param scene The scene the camera belongs to
  86494. */
  86495. function DeviceOrientationCamera(name, position, scene) {
  86496. var _this = _super.call(this, name, position, scene) || this;
  86497. _this._quaternionCache = new BABYLON.Quaternion();
  86498. _this.inputs.addDeviceOrientation();
  86499. return _this;
  86500. }
  86501. /**
  86502. * Gets the current instance class name ("DeviceOrientationCamera").
  86503. * This helps avoiding instanceof at run time.
  86504. * @returns the class name
  86505. */
  86506. DeviceOrientationCamera.prototype.getClassName = function () {
  86507. return "DeviceOrientationCamera";
  86508. };
  86509. /**
  86510. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86511. */
  86512. DeviceOrientationCamera.prototype._checkInputs = function () {
  86513. _super.prototype._checkInputs.call(this);
  86514. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86515. if (this._initialQuaternion) {
  86516. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86517. }
  86518. };
  86519. /**
  86520. * Reset the camera to its default orientation on the specified axis only.
  86521. * @param axis The axis to reset
  86522. */
  86523. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86524. var _this = this;
  86525. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86526. //can only work if this camera has a rotation quaternion already.
  86527. if (!this.rotationQuaternion)
  86528. return;
  86529. if (!this._initialQuaternion) {
  86530. this._initialQuaternion = new BABYLON.Quaternion();
  86531. }
  86532. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86533. ['x', 'y', 'z'].forEach(function (axisName) {
  86534. if (!axis[axisName]) {
  86535. _this._initialQuaternion[axisName] = 0;
  86536. }
  86537. else {
  86538. _this._initialQuaternion[axisName] *= -1;
  86539. }
  86540. });
  86541. this._initialQuaternion.normalize();
  86542. //force rotation update
  86543. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86544. };
  86545. return DeviceOrientationCamera;
  86546. }(BABYLON.FreeCamera));
  86547. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  86548. })(BABYLON || (BABYLON = {}));
  86549. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  86550. var BABYLON;
  86551. (function (BABYLON) {
  86552. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  86553. __extends(VRDeviceOrientationFreeCamera, _super);
  86554. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86555. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86556. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86557. var _this = _super.call(this, name, position, scene) || this;
  86558. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86559. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86560. return _this;
  86561. }
  86562. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  86563. return "VRDeviceOrientationFreeCamera";
  86564. };
  86565. return VRDeviceOrientationFreeCamera;
  86566. }(BABYLON.DeviceOrientationCamera));
  86567. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  86568. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  86569. __extends(VRDeviceOrientationGamepadCamera, _super);
  86570. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86571. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86572. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86573. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  86574. _this.inputs.addGamepad();
  86575. return _this;
  86576. }
  86577. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  86578. return "VRDeviceOrientationGamepadCamera";
  86579. };
  86580. return VRDeviceOrientationGamepadCamera;
  86581. }(VRDeviceOrientationFreeCamera));
  86582. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  86583. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  86584. __extends(VRDeviceOrientationArcRotateCamera, _super);
  86585. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  86586. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86587. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86588. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86589. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86590. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86591. _this.inputs.addVRDeviceOrientation();
  86592. return _this;
  86593. }
  86594. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  86595. return "VRDeviceOrientationArcRotateCamera";
  86596. };
  86597. return VRDeviceOrientationArcRotateCamera;
  86598. }(BABYLON.ArcRotateCamera));
  86599. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  86600. })(BABYLON || (BABYLON = {}));
  86601. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  86602. var BABYLON;
  86603. (function (BABYLON) {
  86604. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  86605. __extends(AnaglyphFreeCamera, _super);
  86606. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  86607. var _this = _super.call(this, name, position, scene) || this;
  86608. _this.interaxialDistance = interaxialDistance;
  86609. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86610. return _this;
  86611. }
  86612. AnaglyphFreeCamera.prototype.getClassName = function () {
  86613. return "AnaglyphFreeCamera";
  86614. };
  86615. return AnaglyphFreeCamera;
  86616. }(BABYLON.FreeCamera));
  86617. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  86618. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  86619. __extends(AnaglyphArcRotateCamera, _super);
  86620. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  86621. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86622. _this.interaxialDistance = interaxialDistance;
  86623. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86624. return _this;
  86625. }
  86626. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  86627. return "AnaglyphArcRotateCamera";
  86628. };
  86629. return AnaglyphArcRotateCamera;
  86630. }(BABYLON.ArcRotateCamera));
  86631. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  86632. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  86633. __extends(AnaglyphGamepadCamera, _super);
  86634. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  86635. var _this = _super.call(this, name, position, scene) || this;
  86636. _this.interaxialDistance = interaxialDistance;
  86637. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86638. return _this;
  86639. }
  86640. AnaglyphGamepadCamera.prototype.getClassName = function () {
  86641. return "AnaglyphGamepadCamera";
  86642. };
  86643. return AnaglyphGamepadCamera;
  86644. }(BABYLON.GamepadCamera));
  86645. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  86646. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  86647. __extends(AnaglyphUniversalCamera, _super);
  86648. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  86649. var _this = _super.call(this, name, position, scene) || this;
  86650. _this.interaxialDistance = interaxialDistance;
  86651. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86652. return _this;
  86653. }
  86654. AnaglyphUniversalCamera.prototype.getClassName = function () {
  86655. return "AnaglyphUniversalCamera";
  86656. };
  86657. return AnaglyphUniversalCamera;
  86658. }(BABYLON.UniversalCamera));
  86659. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  86660. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  86661. __extends(StereoscopicFreeCamera, _super);
  86662. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86663. var _this = _super.call(this, name, position, scene) || this;
  86664. _this.interaxialDistance = interaxialDistance;
  86665. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86666. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86667. return _this;
  86668. }
  86669. StereoscopicFreeCamera.prototype.getClassName = function () {
  86670. return "StereoscopicFreeCamera";
  86671. };
  86672. return StereoscopicFreeCamera;
  86673. }(BABYLON.FreeCamera));
  86674. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  86675. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  86676. __extends(StereoscopicArcRotateCamera, _super);
  86677. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  86678. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86679. _this.interaxialDistance = interaxialDistance;
  86680. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86681. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86682. return _this;
  86683. }
  86684. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  86685. return "StereoscopicArcRotateCamera";
  86686. };
  86687. return StereoscopicArcRotateCamera;
  86688. }(BABYLON.ArcRotateCamera));
  86689. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  86690. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  86691. __extends(StereoscopicGamepadCamera, _super);
  86692. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86693. var _this = _super.call(this, name, position, scene) || this;
  86694. _this.interaxialDistance = interaxialDistance;
  86695. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86696. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86697. return _this;
  86698. }
  86699. StereoscopicGamepadCamera.prototype.getClassName = function () {
  86700. return "StereoscopicGamepadCamera";
  86701. };
  86702. return StereoscopicGamepadCamera;
  86703. }(BABYLON.GamepadCamera));
  86704. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  86705. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  86706. __extends(StereoscopicUniversalCamera, _super);
  86707. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86708. var _this = _super.call(this, name, position, scene) || this;
  86709. _this.interaxialDistance = interaxialDistance;
  86710. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86711. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86712. return _this;
  86713. }
  86714. StereoscopicUniversalCamera.prototype.getClassName = function () {
  86715. return "StereoscopicUniversalCamera";
  86716. };
  86717. return StereoscopicUniversalCamera;
  86718. }(BABYLON.UniversalCamera));
  86719. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  86720. })(BABYLON || (BABYLON = {}));
  86721. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  86722. var BABYLON;
  86723. (function (BABYLON) {
  86724. var VRExperienceHelperGazer = /** @class */ (function () {
  86725. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  86726. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  86727. this.scene = scene;
  86728. this._pointerDownOnMeshAsked = false;
  86729. this._isActionableMesh = false;
  86730. this._teleportationRequestInitiated = false;
  86731. this._teleportationBackRequestInitiated = false;
  86732. this._dpadPressed = true;
  86733. this._activePointer = false;
  86734. this._id = VRExperienceHelperGazer._idCounter++;
  86735. // Gaze tracker
  86736. if (!gazeTrackerToClone) {
  86737. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  86738. this._gazeTracker.bakeCurrentTransformIntoVertices();
  86739. this._gazeTracker.isPickable = false;
  86740. this._gazeTracker.isVisible = false;
  86741. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  86742. targetMat.specularColor = BABYLON.Color3.Black();
  86743. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86744. targetMat.backFaceCulling = false;
  86745. this._gazeTracker.material = targetMat;
  86746. }
  86747. else {
  86748. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  86749. }
  86750. }
  86751. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  86752. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  86753. };
  86754. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  86755. this._pointerDownOnMeshAsked = true;
  86756. if (this._currentMeshSelected && this._currentHit) {
  86757. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  86758. }
  86759. };
  86760. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  86761. if (this._currentMeshSelected && this._currentHit) {
  86762. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  86763. }
  86764. this._pointerDownOnMeshAsked = false;
  86765. };
  86766. VRExperienceHelperGazer.prototype._activatePointer = function () {
  86767. this._activePointer = true;
  86768. };
  86769. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  86770. this._activePointer = false;
  86771. };
  86772. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  86773. };
  86774. VRExperienceHelperGazer.prototype.dispose = function () {
  86775. this._interactionsEnabled = false;
  86776. this._teleportationEnabled = false;
  86777. };
  86778. VRExperienceHelperGazer._idCounter = 0;
  86779. return VRExperienceHelperGazer;
  86780. }());
  86781. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  86782. __extends(VRExperienceHelperControllerGazer, _super);
  86783. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  86784. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  86785. _this.webVRController = webVRController;
  86786. // Laser pointer
  86787. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  86788. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  86789. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86790. laserPointerMaterial.alpha = 0.6;
  86791. _this._laserPointer.material = laserPointerMaterial;
  86792. _this._laserPointer.rotation.x = Math.PI / 2;
  86793. _this._laserPointer.position.z = -0.5;
  86794. _this._laserPointer.isVisible = false;
  86795. if (!webVRController.mesh) {
  86796. // Create an empty mesh that is used prior to loading the high quality model
  86797. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  86798. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  86799. preloadPointerPose.rotation.x = -0.7;
  86800. preloadMesh.addChild(preloadPointerPose);
  86801. webVRController.attachToMesh(preloadMesh);
  86802. }
  86803. _this._setLaserPointerParent(webVRController.mesh);
  86804. return _this;
  86805. }
  86806. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  86807. return this.webVRController.getForwardRay(length);
  86808. };
  86809. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  86810. _super.prototype._activatePointer.call(this);
  86811. this._laserPointer.isVisible = true;
  86812. };
  86813. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  86814. _super.prototype._deactivatePointer.call(this);
  86815. this._laserPointer.isVisible = false;
  86816. };
  86817. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  86818. this._laserPointer.material.emissiveColor = color;
  86819. };
  86820. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  86821. var makeNotPick = function (root) {
  86822. root.name += " laserPointer";
  86823. root.getChildMeshes().forEach(function (c) {
  86824. makeNotPick(c);
  86825. });
  86826. };
  86827. makeNotPick(mesh);
  86828. var childMeshes = mesh.getChildMeshes();
  86829. this.webVRController._pointingPoseNode = null;
  86830. for (var i = 0; i < childMeshes.length; i++) {
  86831. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  86832. mesh = childMeshes[i];
  86833. this.webVRController._pointingPoseNode = mesh;
  86834. break;
  86835. }
  86836. }
  86837. this._laserPointer.parent = mesh;
  86838. };
  86839. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  86840. this._laserPointer.scaling.y = distance;
  86841. this._laserPointer.position.z = -distance / 2;
  86842. };
  86843. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  86844. _super.prototype.dispose.call(this);
  86845. this._laserPointer.dispose();
  86846. };
  86847. return VRExperienceHelperControllerGazer;
  86848. }(VRExperienceHelperGazer));
  86849. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  86850. __extends(VRExperienceHelperCameraGazer, _super);
  86851. function VRExperienceHelperCameraGazer(getCamera, scene) {
  86852. var _this = _super.call(this, scene) || this;
  86853. _this.getCamera = getCamera;
  86854. return _this;
  86855. }
  86856. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  86857. var camera = this.getCamera();
  86858. if (camera) {
  86859. return camera.getForwardRay(length);
  86860. }
  86861. else {
  86862. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  86863. }
  86864. };
  86865. return VRExperienceHelperCameraGazer;
  86866. }(VRExperienceHelperGazer));
  86867. /**
  86868. * Helps to quickly add VR support to an existing scene.
  86869. * See http://doc.babylonjs.com/how_to/webvr_helper
  86870. */
  86871. var VRExperienceHelper = /** @class */ (function () {
  86872. /**
  86873. * Instantiates a VRExperienceHelper.
  86874. * Helps to quickly add VR support to an existing scene.
  86875. * @param scene The scene the VRExperienceHelper belongs to.
  86876. * @param webVROptions Options to modify the vr experience helper's behavior.
  86877. */
  86878. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  86879. if (webVROptions === void 0) { webVROptions = {}; }
  86880. var _this = this;
  86881. this.webVROptions = webVROptions;
  86882. // Can the system support WebVR, even if a headset isn't plugged in?
  86883. this._webVRsupported = false;
  86884. // If WebVR is supported, is a headset plugged in and are we ready to present?
  86885. this._webVRready = false;
  86886. // Are we waiting for the requestPresent callback to complete?
  86887. this._webVRrequesting = false;
  86888. // Are we presenting to the headset right now?
  86889. this._webVRpresenting = false;
  86890. // Are we presenting in the fullscreen fallback?
  86891. this._fullscreenVRpresenting = false;
  86892. /**
  86893. * Observable raised when entering VR.
  86894. */
  86895. this.onEnteringVRObservable = new BABYLON.Observable();
  86896. /**
  86897. * Observable raised when exiting VR.
  86898. */
  86899. this.onExitingVRObservable = new BABYLON.Observable();
  86900. /**
  86901. * Observable raised when controller mesh is loaded.
  86902. */
  86903. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86904. this._useCustomVRButton = false;
  86905. this._teleportationRequested = false;
  86906. this._teleportActive = false;
  86907. this._floorMeshesCollection = [];
  86908. this._rotationAllowed = true;
  86909. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  86910. this._rotationRightAsked = false;
  86911. this._rotationLeftAsked = false;
  86912. this._isDefaultTeleportationTarget = true;
  86913. this._teleportationFillColor = "#444444";
  86914. this._teleportationBorderColor = "#FFFFFF";
  86915. this._rotationAngle = 0;
  86916. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  86917. this._padSensibilityUp = 0.65;
  86918. this._padSensibilityDown = 0.35;
  86919. this.leftController = null;
  86920. this.rightController = null;
  86921. /**
  86922. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  86923. */
  86924. this.onNewMeshSelected = new BABYLON.Observable();
  86925. /**
  86926. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  86927. */
  86928. this.onNewMeshPicked = new BABYLON.Observable();
  86929. /**
  86930. * Observable raised before camera teleportation
  86931. */
  86932. this.onBeforeCameraTeleport = new BABYLON.Observable();
  86933. /**
  86934. * Observable raised after camera teleportation
  86935. */
  86936. this.onAfterCameraTeleport = new BABYLON.Observable();
  86937. /**
  86938. * Observable raised when current selected mesh gets unselected
  86939. */
  86940. this.onSelectedMeshUnselected = new BABYLON.Observable();
  86941. /**
  86942. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  86943. */
  86944. this.teleportationEnabled = true;
  86945. this._teleportationInitialized = false;
  86946. this._interactionsEnabled = false;
  86947. this._interactionsRequested = false;
  86948. this._displayGaze = true;
  86949. this._displayLaserPointer = true;
  86950. this._onResize = function () {
  86951. _this.moveButtonToBottomRight();
  86952. if (_this._fullscreenVRpresenting && _this._webVRready) {
  86953. _this.exitVR();
  86954. }
  86955. };
  86956. this._onFullscreenChange = function () {
  86957. if (document.fullscreen !== undefined) {
  86958. _this._fullscreenVRpresenting = document.fullscreen;
  86959. }
  86960. else if (document.mozFullScreen !== undefined) {
  86961. _this._fullscreenVRpresenting = document.mozFullScreen;
  86962. }
  86963. else if (document.webkitIsFullScreen !== undefined) {
  86964. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  86965. }
  86966. else if (document.msIsFullScreen !== undefined) {
  86967. _this._fullscreenVRpresenting = document.msIsFullScreen;
  86968. }
  86969. if (!_this._fullscreenVRpresenting && _this._canvas) {
  86970. _this.exitVR();
  86971. if (!_this._useCustomVRButton) {
  86972. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  86973. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  86974. }
  86975. }
  86976. };
  86977. this.beforeRender = function () {
  86978. if (_this.leftController && _this.leftController._activePointer) {
  86979. _this._castRayAndSelectObject(_this.leftController);
  86980. }
  86981. if (_this.rightController && _this.rightController._activePointer) {
  86982. _this._castRayAndSelectObject(_this.rightController);
  86983. }
  86984. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  86985. _this._castRayAndSelectObject(_this._cameraGazer);
  86986. }
  86987. else {
  86988. _this._cameraGazer._gazeTracker.isVisible = false;
  86989. }
  86990. };
  86991. this._onNewGamepadConnected = function (gamepad) {
  86992. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  86993. if (gamepad.leftStick) {
  86994. gamepad.onleftstickchanged(function (stickValues) {
  86995. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  86996. // Listening to classic/xbox gamepad only if no VR controller is active
  86997. if ((!_this.leftController && !_this.rightController) ||
  86998. ((_this.leftController && !_this.leftController._activePointer) &&
  86999. (_this.rightController && !_this.rightController._activePointer))) {
  87000. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87001. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87002. }
  87003. }
  87004. });
  87005. }
  87006. if (gamepad.rightStick) {
  87007. gamepad.onrightstickchanged(function (stickValues) {
  87008. if (_this._teleportationInitialized) {
  87009. _this._checkRotate(stickValues, _this._cameraGazer);
  87010. }
  87011. });
  87012. }
  87013. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87014. gamepad.onbuttondown(function (buttonPressed) {
  87015. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87016. _this._cameraGazer._selectionPointerDown();
  87017. }
  87018. });
  87019. gamepad.onbuttonup(function (buttonPressed) {
  87020. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87021. _this._cameraGazer._selectionPointerUp();
  87022. }
  87023. });
  87024. }
  87025. }
  87026. else {
  87027. var webVRController = gamepad;
  87028. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87029. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87030. _this.rightController = controller;
  87031. }
  87032. else {
  87033. _this.leftController = controller;
  87034. }
  87035. _this._tryEnableInteractionOnController(controller);
  87036. }
  87037. };
  87038. // 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
  87039. this._tryEnableInteractionOnController = function (controller) {
  87040. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87041. _this._enableInteractionOnController(controller);
  87042. }
  87043. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87044. _this._enableTeleportationOnController(controller);
  87045. }
  87046. };
  87047. this._onNewGamepadDisconnected = function (gamepad) {
  87048. if (gamepad instanceof BABYLON.WebVRController) {
  87049. if (gamepad.hand === "left" && _this.leftController != null) {
  87050. _this.leftController.dispose();
  87051. _this.leftController = null;
  87052. }
  87053. if (gamepad.hand === "right" && _this.rightController != null) {
  87054. _this.rightController.dispose();
  87055. _this.rightController = null;
  87056. }
  87057. }
  87058. };
  87059. this._workingVector = BABYLON.Vector3.Zero();
  87060. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87061. this._workingMatrix = BABYLON.Matrix.Identity();
  87062. this._scene = scene;
  87063. this._canvas = scene.getEngine().getRenderingCanvas();
  87064. // Parse options
  87065. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87066. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87067. }
  87068. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87069. webVROptions.createDeviceOrientationCamera = true;
  87070. }
  87071. if (webVROptions.defaultHeight === undefined) {
  87072. webVROptions.defaultHeight = 1.7;
  87073. }
  87074. if (webVROptions.useCustomVRButton) {
  87075. this._useCustomVRButton = true;
  87076. if (webVROptions.customVRButton) {
  87077. this._btnVR = webVROptions.customVRButton;
  87078. }
  87079. }
  87080. if (webVROptions.rayLength) {
  87081. this._rayLength = webVROptions.rayLength;
  87082. }
  87083. this._defaultHeight = webVROptions.defaultHeight;
  87084. if (webVROptions.positionScale) {
  87085. this._rayLength *= webVROptions.positionScale;
  87086. this._defaultHeight *= webVROptions.positionScale;
  87087. }
  87088. // Set position
  87089. if (this._scene.activeCamera) {
  87090. this._position = this._scene.activeCamera.position.clone();
  87091. }
  87092. else {
  87093. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87094. }
  87095. // Set non-vr camera
  87096. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87097. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87098. // Copy data from existing camera
  87099. if (this._scene.activeCamera) {
  87100. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87101. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87102. // Set rotation from previous camera
  87103. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87104. var targetCamera = this._scene.activeCamera;
  87105. if (targetCamera.rotationQuaternion) {
  87106. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87107. }
  87108. else {
  87109. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87110. }
  87111. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87112. }
  87113. }
  87114. this._scene.activeCamera = this._deviceOrientationCamera;
  87115. if (this._canvas) {
  87116. this._scene.activeCamera.attachControl(this._canvas);
  87117. }
  87118. }
  87119. else {
  87120. this._existingCamera = this._scene.activeCamera;
  87121. }
  87122. // Create VR cameras
  87123. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87124. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87125. }
  87126. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87127. this._webVRCamera.useStandingMatrix();
  87128. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87129. // Create default button
  87130. if (!this._useCustomVRButton) {
  87131. this._btnVR = document.createElement("BUTTON");
  87132. this._btnVR.className = "babylonVRicon";
  87133. this._btnVR.id = "babylonVRiconbtn";
  87134. this._btnVR.title = "Click to switch to VR";
  87135. 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) }";
  87136. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87137. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87138. // css += ".babylonVRicon.vrdisplaysupported { }";
  87139. // css += ".babylonVRicon.vrdisplayready { }";
  87140. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87141. var style = document.createElement('style');
  87142. style.appendChild(document.createTextNode(css));
  87143. document.getElementsByTagName('head')[0].appendChild(style);
  87144. this.moveButtonToBottomRight();
  87145. }
  87146. // VR button click event
  87147. if (this._btnVR) {
  87148. this._btnVR.addEventListener("click", function () {
  87149. if (!_this.isInVRMode) {
  87150. _this.enterVR();
  87151. }
  87152. else {
  87153. _this.exitVR();
  87154. }
  87155. });
  87156. }
  87157. // Window events
  87158. window.addEventListener("resize", this._onResize);
  87159. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87160. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87161. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87162. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87163. // Display vr button when headset is connected
  87164. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87165. this.displayVRButton();
  87166. }
  87167. else {
  87168. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87169. if (e.vrDisplay) {
  87170. _this.displayVRButton();
  87171. }
  87172. });
  87173. }
  87174. // Exiting VR mode using 'ESC' key on desktop
  87175. this._onKeyDown = function (event) {
  87176. if (event.keyCode === 27 && _this.isInVRMode) {
  87177. _this.exitVR();
  87178. }
  87179. };
  87180. document.addEventListener("keydown", this._onKeyDown);
  87181. // Exiting VR mode double tapping the touch screen
  87182. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87183. if (_this.isInVRMode) {
  87184. _this.exitVR();
  87185. if (_this._fullscreenVRpresenting) {
  87186. _this._scene.getEngine().switchFullscreen(true);
  87187. }
  87188. }
  87189. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87190. // Listen for WebVR display changes
  87191. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87192. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87193. this._onVRRequestPresentStart = function () {
  87194. _this._webVRrequesting = true;
  87195. _this.updateButtonVisibility();
  87196. };
  87197. this._onVRRequestPresentComplete = function (success) {
  87198. _this._webVRrequesting = false;
  87199. _this.updateButtonVisibility();
  87200. };
  87201. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87202. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87203. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87204. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87205. scene.onDisposeObservable.add(function () {
  87206. _this.dispose();
  87207. });
  87208. // Gamepad connection events
  87209. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87210. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87211. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87212. this.updateButtonVisibility();
  87213. //create easing functions
  87214. this._circleEase = new BABYLON.CircleEase();
  87215. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87216. }
  87217. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87218. /** Return this.onEnteringVRObservable
  87219. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87220. */
  87221. get: function () {
  87222. return this.onEnteringVRObservable;
  87223. },
  87224. enumerable: true,
  87225. configurable: true
  87226. });
  87227. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87228. /** Return this.onExitingVRObservable
  87229. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87230. */
  87231. get: function () {
  87232. return this.onExitingVRObservable;
  87233. },
  87234. enumerable: true,
  87235. configurable: true
  87236. });
  87237. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87238. /** Return this.onControllerMeshLoadedObservable
  87239. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87240. */
  87241. get: function () {
  87242. return this.onControllerMeshLoadedObservable;
  87243. },
  87244. enumerable: true,
  87245. configurable: true
  87246. });
  87247. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87248. /**
  87249. * The mesh used to display where the user is going to teleport.
  87250. */
  87251. get: function () {
  87252. return this._teleportationTarget;
  87253. },
  87254. /**
  87255. * Sets the mesh to be used to display where the user is going to teleport.
  87256. */
  87257. set: function (value) {
  87258. if (value) {
  87259. value.name = "teleportationTarget";
  87260. this._isDefaultTeleportationTarget = false;
  87261. this._teleportationTarget = value;
  87262. }
  87263. },
  87264. enumerable: true,
  87265. configurable: true
  87266. });
  87267. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87268. /**
  87269. * The mesh used to display where the user is selecting,
  87270. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87271. * See http://doc.babylonjs.com/resources/baking_transformations
  87272. */
  87273. get: function () {
  87274. return this._cameraGazer._gazeTracker;
  87275. },
  87276. set: function (value) {
  87277. if (value) {
  87278. this._cameraGazer._gazeTracker = value;
  87279. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87280. this._cameraGazer._gazeTracker.isPickable = false;
  87281. this._cameraGazer._gazeTracker.isVisible = false;
  87282. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87283. if (this.leftController) {
  87284. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87285. }
  87286. if (this.rightController) {
  87287. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87288. }
  87289. }
  87290. },
  87291. enumerable: true,
  87292. configurable: true
  87293. });
  87294. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87295. /**
  87296. * If the ray of the gaze should be displayed.
  87297. */
  87298. get: function () {
  87299. return this._displayGaze;
  87300. },
  87301. /**
  87302. * Sets if the ray of the gaze should be displayed.
  87303. */
  87304. set: function (value) {
  87305. this._displayGaze = value;
  87306. if (!value) {
  87307. this._cameraGazer._gazeTracker.isVisible = false;
  87308. if (this.leftController) {
  87309. this.leftController._gazeTracker.isVisible = false;
  87310. }
  87311. if (this.rightController) {
  87312. this.rightController._gazeTracker.isVisible = false;
  87313. }
  87314. }
  87315. },
  87316. enumerable: true,
  87317. configurable: true
  87318. });
  87319. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87320. /**
  87321. * If the ray of the LaserPointer should be displayed.
  87322. */
  87323. get: function () {
  87324. return this._displayLaserPointer;
  87325. },
  87326. /**
  87327. * Sets if the ray of the LaserPointer should be displayed.
  87328. */
  87329. set: function (value) {
  87330. this._displayLaserPointer = value;
  87331. if (!value) {
  87332. if (this.rightController) {
  87333. this.rightController._deactivatePointer();
  87334. this.rightController._gazeTracker.isVisible = false;
  87335. }
  87336. if (this.leftController) {
  87337. this.leftController._deactivatePointer();
  87338. this.leftController._gazeTracker.isVisible = false;
  87339. }
  87340. }
  87341. else {
  87342. if (this.rightController) {
  87343. this.rightController._activatePointer();
  87344. }
  87345. else if (this.leftController) {
  87346. this.leftController._activatePointer();
  87347. }
  87348. }
  87349. },
  87350. enumerable: true,
  87351. configurable: true
  87352. });
  87353. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87354. /**
  87355. * The deviceOrientationCamera used as the camera when not in VR.
  87356. */
  87357. get: function () {
  87358. return this._deviceOrientationCamera;
  87359. },
  87360. enumerable: true,
  87361. configurable: true
  87362. });
  87363. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87364. /**
  87365. * Based on the current WebVR support, returns the current VR camera used.
  87366. */
  87367. get: function () {
  87368. if (this._webVRready) {
  87369. return this._webVRCamera;
  87370. }
  87371. else {
  87372. return this._scene.activeCamera;
  87373. }
  87374. },
  87375. enumerable: true,
  87376. configurable: true
  87377. });
  87378. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87379. /**
  87380. * The webVRCamera which is used when in VR.
  87381. */
  87382. get: function () {
  87383. return this._webVRCamera;
  87384. },
  87385. enumerable: true,
  87386. configurable: true
  87387. });
  87388. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87389. /**
  87390. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87391. */
  87392. get: function () {
  87393. return this._vrDeviceOrientationCamera;
  87394. },
  87395. enumerable: true,
  87396. configurable: true
  87397. });
  87398. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87399. get: function () {
  87400. var result = this._cameraGazer._teleportationRequestInitiated
  87401. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87402. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87403. return result;
  87404. },
  87405. enumerable: true,
  87406. configurable: true
  87407. });
  87408. // Raised when one of the controller has loaded successfully its associated default mesh
  87409. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87410. if (this.leftController && this.leftController.webVRController == webVRController) {
  87411. if (webVRController.mesh) {
  87412. this.leftController._setLaserPointerParent(webVRController.mesh);
  87413. }
  87414. }
  87415. if (this.rightController && this.rightController.webVRController == webVRController) {
  87416. if (webVRController.mesh) {
  87417. this.rightController._setLaserPointerParent(webVRController.mesh);
  87418. }
  87419. }
  87420. try {
  87421. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  87422. }
  87423. catch (err) {
  87424. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  87425. }
  87426. };
  87427. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  87428. /**
  87429. * Gets a value indicating if we are currently in VR mode.
  87430. */
  87431. get: function () {
  87432. return this._webVRpresenting || this._fullscreenVRpresenting;
  87433. },
  87434. enumerable: true,
  87435. configurable: true
  87436. });
  87437. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  87438. var vrDisplay = this._scene.getEngine().getVRDevice();
  87439. if (vrDisplay) {
  87440. var wasPresenting = this._webVRpresenting;
  87441. // A VR display is connected
  87442. this._webVRpresenting = vrDisplay.isPresenting;
  87443. if (wasPresenting && !this._webVRpresenting)
  87444. this.exitVR();
  87445. }
  87446. else {
  87447. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  87448. }
  87449. this.updateButtonVisibility();
  87450. };
  87451. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  87452. this._webVRsupported = eventArgs.vrSupported;
  87453. this._webVRready = !!eventArgs.vrDisplay;
  87454. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  87455. this.updateButtonVisibility();
  87456. };
  87457. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  87458. if (this._canvas && !this._useCustomVRButton) {
  87459. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  87460. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  87461. }
  87462. };
  87463. VRExperienceHelper.prototype.displayVRButton = function () {
  87464. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  87465. document.body.appendChild(this._btnVR);
  87466. this._btnVRDisplayed = true;
  87467. }
  87468. };
  87469. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  87470. if (!this._btnVR || this._useCustomVRButton) {
  87471. return;
  87472. }
  87473. this._btnVR.className = "babylonVRicon";
  87474. if (this.isInVRMode) {
  87475. this._btnVR.className += " vrdisplaypresenting";
  87476. }
  87477. else {
  87478. if (this._webVRready)
  87479. this._btnVR.className += " vrdisplayready";
  87480. if (this._webVRsupported)
  87481. this._btnVR.className += " vrdisplaysupported";
  87482. if (this._webVRrequesting)
  87483. this._btnVR.className += " vrdisplayrequesting";
  87484. }
  87485. };
  87486. /**
  87487. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  87488. * Otherwise, will use the fullscreen API.
  87489. */
  87490. VRExperienceHelper.prototype.enterVR = function () {
  87491. if (this.onEnteringVRObservable) {
  87492. try {
  87493. this.onEnteringVRObservable.notifyObservers(this);
  87494. }
  87495. catch (err) {
  87496. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  87497. }
  87498. }
  87499. if (this._scene.activeCamera) {
  87500. this._position = this._scene.activeCamera.position.clone();
  87501. // make sure that we return to the last active camera
  87502. this._existingCamera = this._scene.activeCamera;
  87503. }
  87504. if (this._webVRrequesting)
  87505. return;
  87506. // If WebVR is supported and a headset is connected
  87507. if (this._webVRready) {
  87508. if (!this._webVRpresenting) {
  87509. this._webVRCamera.position = this._position;
  87510. this._scene.activeCamera = this._webVRCamera;
  87511. }
  87512. }
  87513. else if (this._vrDeviceOrientationCamera) {
  87514. this._vrDeviceOrientationCamera.position = this._position;
  87515. if (this._scene.activeCamera) {
  87516. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87517. }
  87518. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  87519. this._scene.getEngine().switchFullscreen(true);
  87520. this.updateButtonVisibility();
  87521. }
  87522. if (this._scene.activeCamera && this._canvas) {
  87523. this._scene.activeCamera.attachControl(this._canvas);
  87524. }
  87525. if (this._interactionsEnabled) {
  87526. this._scene.registerBeforeRender(this.beforeRender);
  87527. }
  87528. };
  87529. /**
  87530. * Attempt to exit VR, or fullscreen.
  87531. */
  87532. VRExperienceHelper.prototype.exitVR = function () {
  87533. if (this.onExitingVRObservable) {
  87534. try {
  87535. this.onExitingVRObservable.notifyObservers(this);
  87536. }
  87537. catch (err) {
  87538. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  87539. }
  87540. }
  87541. if (this._webVRpresenting) {
  87542. this._scene.getEngine().disableVR();
  87543. }
  87544. if (this._scene.activeCamera) {
  87545. this._position = this._scene.activeCamera.position.clone();
  87546. }
  87547. if (this._deviceOrientationCamera) {
  87548. this._deviceOrientationCamera.position = this._position;
  87549. this._scene.activeCamera = this._deviceOrientationCamera;
  87550. if (this._canvas) {
  87551. this._scene.activeCamera.attachControl(this._canvas);
  87552. }
  87553. }
  87554. else if (this._existingCamera) {
  87555. this._existingCamera.position = this._position;
  87556. this._scene.activeCamera = this._existingCamera;
  87557. }
  87558. this.updateButtonVisibility();
  87559. if (this._interactionsEnabled) {
  87560. this._scene.unregisterBeforeRender(this.beforeRender);
  87561. }
  87562. // resize to update width and height when exiting vr exits fullscreen
  87563. this._scene.getEngine().resize();
  87564. };
  87565. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  87566. /**
  87567. * The position of the vr experience helper.
  87568. */
  87569. get: function () {
  87570. return this._position;
  87571. },
  87572. /**
  87573. * Sets the position of the vr experience helper.
  87574. */
  87575. set: function (value) {
  87576. this._position = value;
  87577. if (this._scene.activeCamera) {
  87578. this._scene.activeCamera.position = value;
  87579. }
  87580. },
  87581. enumerable: true,
  87582. configurable: true
  87583. });
  87584. /**
  87585. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  87586. */
  87587. VRExperienceHelper.prototype.enableInteractions = function () {
  87588. var _this = this;
  87589. if (!this._interactionsEnabled) {
  87590. this._interactionsRequested = true;
  87591. if (this.leftController) {
  87592. this._enableInteractionOnController(this.leftController);
  87593. }
  87594. if (this.rightController) {
  87595. this._enableInteractionOnController(this.rightController);
  87596. }
  87597. this.raySelectionPredicate = function (mesh) {
  87598. return mesh.isVisible;
  87599. };
  87600. this.meshSelectionPredicate = function (mesh) {
  87601. return true;
  87602. };
  87603. this._raySelectionPredicate = function (mesh) {
  87604. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  87605. && mesh.name.indexOf("teleportationTarget") === -1
  87606. && mesh.name.indexOf("torusTeleportation") === -1
  87607. && mesh.name.indexOf("laserPointer") === -1)) {
  87608. return _this.raySelectionPredicate(mesh);
  87609. }
  87610. return false;
  87611. };
  87612. this._interactionsEnabled = true;
  87613. }
  87614. };
  87615. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  87616. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  87617. if (this._floorMeshesCollection[i].id === mesh.id) {
  87618. return true;
  87619. }
  87620. }
  87621. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  87622. return true;
  87623. }
  87624. return false;
  87625. };
  87626. /**
  87627. * Adds a floor mesh to be used for teleportation.
  87628. * @param floorMesh the mesh to be used for teleportation.
  87629. */
  87630. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  87631. if (!this._floorMeshesCollection) {
  87632. return;
  87633. }
  87634. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  87635. return;
  87636. }
  87637. this._floorMeshesCollection.push(floorMesh);
  87638. };
  87639. /**
  87640. * Removes a floor mesh from being used for teleportation.
  87641. * @param floorMesh the mesh to be removed.
  87642. */
  87643. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  87644. if (!this._floorMeshesCollection) {
  87645. return;
  87646. }
  87647. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  87648. if (meshIndex !== -1) {
  87649. this._floorMeshesCollection.splice(meshIndex, 1);
  87650. }
  87651. };
  87652. /**
  87653. * Enables interactions and teleportation using the VR controllers and gaze.
  87654. * @param vrTeleportationOptions options to modify teleportation behavior.
  87655. */
  87656. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  87657. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  87658. if (!this._teleportationInitialized) {
  87659. this._teleportationRequested = true;
  87660. this.enableInteractions();
  87661. if (vrTeleportationOptions.floorMeshName) {
  87662. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  87663. }
  87664. if (vrTeleportationOptions.floorMeshes) {
  87665. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  87666. }
  87667. if (this.leftController != null) {
  87668. this._enableTeleportationOnController(this.leftController);
  87669. }
  87670. if (this.rightController != null) {
  87671. this._enableTeleportationOnController(this.rightController);
  87672. }
  87673. // Creates an image processing post process for the vignette not relying
  87674. // on the main scene configuration for image processing to reduce setup and spaces
  87675. // (gamma/linear) conflicts.
  87676. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  87677. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87678. imageProcessingConfiguration.vignetteEnabled = true;
  87679. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  87680. this._webVRCamera.detachPostProcess(this._postProcessMove);
  87681. this._teleportationInitialized = true;
  87682. if (this._isDefaultTeleportationTarget) {
  87683. this._createTeleportationCircles();
  87684. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  87685. }
  87686. }
  87687. };
  87688. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  87689. var _this = this;
  87690. var controllerMesh = controller.webVRController.mesh;
  87691. if (controllerMesh) {
  87692. controller._interactionsEnabled = true;
  87693. controller._activatePointer();
  87694. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  87695. // Enabling / disabling laserPointer
  87696. if (_this._displayLaserPointer && stateObject.value === 1) {
  87697. if (controller._activePointer) {
  87698. controller._deactivatePointer();
  87699. }
  87700. else {
  87701. controller._activatePointer();
  87702. }
  87703. if (_this.displayGaze) {
  87704. controller._gazeTracker.isVisible = controller._activePointer;
  87705. }
  87706. }
  87707. });
  87708. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  87709. if (!controller._pointerDownOnMeshAsked) {
  87710. if (stateObject.value > _this._padSensibilityUp) {
  87711. controller._selectionPointerDown();
  87712. }
  87713. }
  87714. else if (stateObject.value < _this._padSensibilityDown) {
  87715. controller._selectionPointerUp();
  87716. }
  87717. });
  87718. }
  87719. };
  87720. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  87721. // Dont teleport if another gaze already requested teleportation
  87722. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  87723. return;
  87724. }
  87725. if (!gazer._teleportationRequestInitiated) {
  87726. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  87727. gazer._activatePointer();
  87728. gazer._teleportationRequestInitiated = true;
  87729. }
  87730. }
  87731. else {
  87732. // Listening to the proper controller values changes to confirm teleportation
  87733. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  87734. if (this._teleportActive) {
  87735. this._teleportCamera(this._haloCenter);
  87736. }
  87737. gazer._teleportationRequestInitiated = false;
  87738. }
  87739. }
  87740. };
  87741. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  87742. // Only rotate when user is not currently selecting a teleportation location
  87743. if (gazer._teleportationRequestInitiated) {
  87744. return;
  87745. }
  87746. if (!this._rotationLeftAsked) {
  87747. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  87748. this._rotationLeftAsked = true;
  87749. if (this._rotationAllowed) {
  87750. this._rotateCamera(false);
  87751. }
  87752. }
  87753. }
  87754. else {
  87755. if (stateObject.x > -this._padSensibilityDown) {
  87756. this._rotationLeftAsked = false;
  87757. }
  87758. }
  87759. if (!this._rotationRightAsked) {
  87760. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  87761. this._rotationRightAsked = true;
  87762. if (this._rotationAllowed) {
  87763. this._rotateCamera(true);
  87764. }
  87765. }
  87766. }
  87767. else {
  87768. if (stateObject.x < this._padSensibilityDown) {
  87769. this._rotationRightAsked = false;
  87770. }
  87771. }
  87772. };
  87773. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  87774. // Only teleport backwards when user is not currently selecting a teleportation location
  87775. if (gazer._teleportationRequestInitiated) {
  87776. return;
  87777. }
  87778. // Teleport backwards
  87779. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  87780. if (!gazer._teleportationBackRequestInitiated) {
  87781. if (!this.currentVRCamera) {
  87782. return;
  87783. }
  87784. // Get rotation and position of the current camera
  87785. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  87786. var position = this.currentVRCamera.position;
  87787. // If the camera has device position, use that instead
  87788. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  87789. rotation = this.currentVRCamera.deviceRotationQuaternion;
  87790. position = this.currentVRCamera.devicePosition;
  87791. }
  87792. // Get matrix with only the y rotation of the device rotation
  87793. rotation.toEulerAnglesToRef(this._workingVector);
  87794. this._workingVector.z = 0;
  87795. this._workingVector.x = 0;
  87796. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  87797. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  87798. // Rotate backwards ray by device rotation to cast at the ground behind the user
  87799. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  87800. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  87801. var ray = new BABYLON.Ray(position, this._workingVector);
  87802. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  87803. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  87804. this._teleportCamera(hit.pickedPoint);
  87805. }
  87806. gazer._teleportationBackRequestInitiated = true;
  87807. }
  87808. }
  87809. else {
  87810. gazer._teleportationBackRequestInitiated = false;
  87811. }
  87812. };
  87813. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  87814. var _this = this;
  87815. var controllerMesh = controller.webVRController.mesh;
  87816. if (controllerMesh) {
  87817. if (!controller._interactionsEnabled) {
  87818. this._enableInteractionOnController(controller);
  87819. }
  87820. controller._interactionsEnabled = true;
  87821. controller._teleportationEnabled = true;
  87822. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87823. controller._dpadPressed = false;
  87824. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  87825. controller._dpadPressed = stateObject.pressed;
  87826. if (!controller._dpadPressed) {
  87827. _this._rotationLeftAsked = false;
  87828. _this._rotationRightAsked = false;
  87829. controller._teleportationBackRequestInitiated = false;
  87830. }
  87831. });
  87832. }
  87833. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  87834. if (_this.teleportationEnabled) {
  87835. _this._checkTeleportBackwards(stateObject, controller);
  87836. _this._checkTeleportWithRay(stateObject, controller);
  87837. }
  87838. _this._checkRotate(stateObject, controller);
  87839. });
  87840. }
  87841. };
  87842. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  87843. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  87844. this._teleportationTarget.isPickable = false;
  87845. var length = 512;
  87846. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  87847. dynamicTexture.hasAlpha = true;
  87848. var context = dynamicTexture.getContext();
  87849. var centerX = length / 2;
  87850. var centerY = length / 2;
  87851. var radius = 200;
  87852. context.beginPath();
  87853. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  87854. context.fillStyle = this._teleportationFillColor;
  87855. context.fill();
  87856. context.lineWidth = 10;
  87857. context.strokeStyle = this._teleportationBorderColor;
  87858. context.stroke();
  87859. context.closePath();
  87860. dynamicTexture.update();
  87861. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  87862. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  87863. this._teleportationTarget.material = teleportationCircleMaterial;
  87864. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  87865. torus.isPickable = false;
  87866. torus.parent = this._teleportationTarget;
  87867. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  87868. var keys = [];
  87869. keys.push({
  87870. frame: 0,
  87871. value: 0
  87872. });
  87873. keys.push({
  87874. frame: 30,
  87875. value: 0.4
  87876. });
  87877. keys.push({
  87878. frame: 60,
  87879. value: 0
  87880. });
  87881. animationInnerCircle.setKeys(keys);
  87882. var easingFunction = new BABYLON.SineEase();
  87883. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87884. animationInnerCircle.setEasingFunction(easingFunction);
  87885. torus.animations = [];
  87886. torus.animations.push(animationInnerCircle);
  87887. this._scene.beginAnimation(torus, 0, 60, true);
  87888. this._hideTeleportationTarget();
  87889. };
  87890. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  87891. this._teleportActive = true;
  87892. if (this._teleportationInitialized) {
  87893. this._teleportationTarget.isVisible = true;
  87894. if (this._isDefaultTeleportationTarget) {
  87895. this._teleportationTarget.getChildren()[0].isVisible = true;
  87896. }
  87897. }
  87898. };
  87899. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  87900. this._teleportActive = false;
  87901. if (this._teleportationInitialized) {
  87902. this._teleportationTarget.isVisible = false;
  87903. if (this._isDefaultTeleportationTarget) {
  87904. this._teleportationTarget.getChildren()[0].isVisible = false;
  87905. }
  87906. }
  87907. };
  87908. VRExperienceHelper.prototype._rotateCamera = function (right) {
  87909. var _this = this;
  87910. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87911. return;
  87912. }
  87913. if (right) {
  87914. this._rotationAngle++;
  87915. }
  87916. else {
  87917. this._rotationAngle--;
  87918. }
  87919. this.currentVRCamera.animations = [];
  87920. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  87921. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87922. var animationRotationKeys = [];
  87923. animationRotationKeys.push({
  87924. frame: 0,
  87925. value: this.currentVRCamera.rotationQuaternion
  87926. });
  87927. animationRotationKeys.push({
  87928. frame: 6,
  87929. value: target
  87930. });
  87931. animationRotation.setKeys(animationRotationKeys);
  87932. animationRotation.setEasingFunction(this._circleEase);
  87933. this.currentVRCamera.animations.push(animationRotation);
  87934. this._postProcessMove.animations = [];
  87935. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87936. var vignetteWeightKeys = [];
  87937. vignetteWeightKeys.push({
  87938. frame: 0,
  87939. value: 0
  87940. });
  87941. vignetteWeightKeys.push({
  87942. frame: 3,
  87943. value: 4
  87944. });
  87945. vignetteWeightKeys.push({
  87946. frame: 6,
  87947. value: 0
  87948. });
  87949. animationPP.setKeys(vignetteWeightKeys);
  87950. animationPP.setEasingFunction(this._circleEase);
  87951. this._postProcessMove.animations.push(animationPP);
  87952. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87953. var vignetteStretchKeys = [];
  87954. vignetteStretchKeys.push({
  87955. frame: 0,
  87956. value: 0
  87957. });
  87958. vignetteStretchKeys.push({
  87959. frame: 3,
  87960. value: 10
  87961. });
  87962. vignetteStretchKeys.push({
  87963. frame: 6,
  87964. value: 0
  87965. });
  87966. animationPP2.setKeys(vignetteStretchKeys);
  87967. animationPP2.setEasingFunction(this._circleEase);
  87968. this._postProcessMove.animations.push(animationPP2);
  87969. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87970. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87971. this._postProcessMove.samples = 4;
  87972. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87973. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  87974. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87975. });
  87976. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  87977. };
  87978. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  87979. if (hit.pickedPoint) {
  87980. if (gazer._teleportationRequestInitiated) {
  87981. this._displayTeleportationTarget();
  87982. this._haloCenter.copyFrom(hit.pickedPoint);
  87983. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  87984. }
  87985. var pickNormal = hit.getNormal(true, false);
  87986. if (pickNormal) {
  87987. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87988. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87989. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  87990. }
  87991. this._teleportationTarget.position.y += 0.1;
  87992. }
  87993. };
  87994. VRExperienceHelper.prototype._teleportCamera = function (location) {
  87995. var _this = this;
  87996. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87997. return;
  87998. }
  87999. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88000. // offset of the headset from the anchor.
  88001. if (this.webVRCamera.leftCamera) {
  88002. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88003. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88004. location.subtractToRef(this._workingVector, this._workingVector);
  88005. }
  88006. else {
  88007. this._workingVector.copyFrom(location);
  88008. }
  88009. // Add height to account for user's height offset
  88010. if (this.isInVRMode) {
  88011. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88012. }
  88013. else {
  88014. this._workingVector.y += this._defaultHeight;
  88015. }
  88016. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88017. // Create animation from the camera's position to the new location
  88018. this.currentVRCamera.animations = [];
  88019. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88020. var animationCameraTeleportationKeys = [{
  88021. frame: 0,
  88022. value: this.currentVRCamera.position
  88023. },
  88024. {
  88025. frame: 11,
  88026. value: this._workingVector
  88027. }
  88028. ];
  88029. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88030. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88031. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88032. this._postProcessMove.animations = [];
  88033. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88034. var vignetteWeightKeys = [];
  88035. vignetteWeightKeys.push({
  88036. frame: 0,
  88037. value: 0
  88038. });
  88039. vignetteWeightKeys.push({
  88040. frame: 5,
  88041. value: 8
  88042. });
  88043. vignetteWeightKeys.push({
  88044. frame: 11,
  88045. value: 0
  88046. });
  88047. animationPP.setKeys(vignetteWeightKeys);
  88048. this._postProcessMove.animations.push(animationPP);
  88049. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88050. var vignetteStretchKeys = [];
  88051. vignetteStretchKeys.push({
  88052. frame: 0,
  88053. value: 0
  88054. });
  88055. vignetteStretchKeys.push({
  88056. frame: 5,
  88057. value: 10
  88058. });
  88059. vignetteStretchKeys.push({
  88060. frame: 11,
  88061. value: 0
  88062. });
  88063. animationPP2.setKeys(vignetteStretchKeys);
  88064. this._postProcessMove.animations.push(animationPP2);
  88065. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88066. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88067. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88068. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88069. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88070. });
  88071. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88072. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88073. });
  88074. this._hideTeleportationTarget();
  88075. };
  88076. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88077. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88078. return;
  88079. }
  88080. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  88081. // Moving the gazeTracker on the mesh face targetted
  88082. if (hit && hit.pickedPoint) {
  88083. if (this._displayGaze) {
  88084. var multiplier = 1;
  88085. gazer._gazeTracker.isVisible = true;
  88086. if (gazer._isActionableMesh) {
  88087. multiplier = 3;
  88088. }
  88089. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88090. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88091. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88092. var pickNormal = hit.getNormal();
  88093. // To avoid z-fighting
  88094. var deltaFighting = 0.002;
  88095. if (pickNormal) {
  88096. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88097. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88098. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88099. }
  88100. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88101. if (gazer._gazeTracker.position.x < 0) {
  88102. gazer._gazeTracker.position.x += deltaFighting;
  88103. }
  88104. else {
  88105. gazer._gazeTracker.position.x -= deltaFighting;
  88106. }
  88107. if (gazer._gazeTracker.position.y < 0) {
  88108. gazer._gazeTracker.position.y += deltaFighting;
  88109. }
  88110. else {
  88111. gazer._gazeTracker.position.y -= deltaFighting;
  88112. }
  88113. if (gazer._gazeTracker.position.z < 0) {
  88114. gazer._gazeTracker.position.z += deltaFighting;
  88115. }
  88116. else {
  88117. gazer._gazeTracker.position.z -= deltaFighting;
  88118. }
  88119. }
  88120. // Changing the size of the laser pointer based on the distance from the targetted point
  88121. gazer._updatePointerDistance(hit.distance);
  88122. }
  88123. else {
  88124. gazer._gazeTracker.isVisible = false;
  88125. }
  88126. if (hit && hit.pickedMesh) {
  88127. gazer._currentHit = hit;
  88128. if (gazer._pointerDownOnMeshAsked) {
  88129. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88130. }
  88131. // The object selected is the floor, we're in a teleportation scenario
  88132. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88133. // Moving the teleportation area to this targetted point
  88134. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88135. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88136. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88137. }
  88138. gazer._currentMeshSelected = null;
  88139. if (gazer._teleportationRequestInitiated) {
  88140. this._moveTeleportationSelectorTo(hit, gazer);
  88141. }
  88142. return;
  88143. }
  88144. // If not, we're in a selection scenario
  88145. //this._teleportationAllowed = false;
  88146. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88147. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88148. this.onNewMeshPicked.notifyObservers(hit);
  88149. gazer._currentMeshSelected = hit.pickedMesh;
  88150. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88151. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88152. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88153. gazer._isActionableMesh = true;
  88154. }
  88155. else {
  88156. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88157. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88158. gazer._isActionableMesh = false;
  88159. }
  88160. try {
  88161. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88162. }
  88163. catch (err) {
  88164. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88165. }
  88166. }
  88167. else {
  88168. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88169. gazer._currentMeshSelected = null;
  88170. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88171. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88172. }
  88173. }
  88174. }
  88175. else {
  88176. gazer._currentHit = null;
  88177. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88178. gazer._currentMeshSelected = null;
  88179. //this._teleportationAllowed = false;
  88180. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88181. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88182. }
  88183. };
  88184. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88185. if (mesh) {
  88186. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88187. }
  88188. };
  88189. /**
  88190. * Sets the color of the laser ray from the vr controllers.
  88191. * @param color new color for the ray.
  88192. */
  88193. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88194. if (this.leftController) {
  88195. this.leftController._setLaserPointerColor(color);
  88196. }
  88197. if (this.rightController) {
  88198. this.rightController._setLaserPointerColor(color);
  88199. }
  88200. };
  88201. /**
  88202. * Sets the color of the ray from the vr headsets gaze.
  88203. * @param color new color for the ray.
  88204. */
  88205. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88206. if (!this._cameraGazer._gazeTracker.material) {
  88207. return;
  88208. }
  88209. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88210. if (this.leftController) {
  88211. this.leftController._gazeTracker.material.emissiveColor = color;
  88212. }
  88213. if (this.rightController) {
  88214. this.rightController._gazeTracker.material.emissiveColor = color;
  88215. }
  88216. };
  88217. /**
  88218. * Exits VR and disposes of the vr experience helper
  88219. */
  88220. VRExperienceHelper.prototype.dispose = function () {
  88221. if (this.isInVRMode) {
  88222. this.exitVR();
  88223. }
  88224. if (this._postProcessMove) {
  88225. this._postProcessMove.dispose();
  88226. }
  88227. if (this._webVRCamera) {
  88228. this._webVRCamera.dispose();
  88229. }
  88230. if (this._vrDeviceOrientationCamera) {
  88231. this._vrDeviceOrientationCamera.dispose();
  88232. }
  88233. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88234. document.body.removeChild(this._btnVR);
  88235. }
  88236. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88237. this._deviceOrientationCamera.dispose();
  88238. }
  88239. if (this._cameraGazer) {
  88240. this._cameraGazer.dispose();
  88241. }
  88242. if (this.leftController) {
  88243. this.leftController.dispose();
  88244. }
  88245. if (this.rightController) {
  88246. this.rightController.dispose();
  88247. }
  88248. if (this._teleportationTarget) {
  88249. this._teleportationTarget.dispose();
  88250. }
  88251. this._floorMeshesCollection = [];
  88252. document.removeEventListener("keydown", this._onKeyDown);
  88253. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88254. window.removeEventListener("resize", this._onResize);
  88255. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88256. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88257. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88258. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88259. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88260. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88261. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88262. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88263. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88264. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88265. this._scene.unregisterBeforeRender(this.beforeRender);
  88266. };
  88267. /**
  88268. * Gets the name of the VRExperienceHelper class
  88269. * @returns "VRExperienceHelper"
  88270. */
  88271. VRExperienceHelper.prototype.getClassName = function () {
  88272. return "VRExperienceHelper";
  88273. };
  88274. return VRExperienceHelper;
  88275. }());
  88276. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88277. })(BABYLON || (BABYLON = {}));
  88278. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88279. // Mainly based on these 2 articles :
  88280. // 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
  88281. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88282. var BABYLON;
  88283. (function (BABYLON) {
  88284. /**
  88285. * Defines the potential axis of a Joystick
  88286. */
  88287. var JoystickAxis;
  88288. (function (JoystickAxis) {
  88289. /** X axis */
  88290. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88291. /** Y axis */
  88292. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88293. /** Z axis */
  88294. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88295. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88296. /**
  88297. * Class used to define virtual joystick (used in touch mode)
  88298. */
  88299. var VirtualJoystick = /** @class */ (function () {
  88300. /**
  88301. * Creates a new virtual joystick
  88302. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88303. */
  88304. function VirtualJoystick(leftJoystick) {
  88305. var _this = this;
  88306. if (leftJoystick) {
  88307. this._leftJoystick = true;
  88308. }
  88309. else {
  88310. this._leftJoystick = false;
  88311. }
  88312. VirtualJoystick._globalJoystickIndex++;
  88313. // By default left & right arrow keys are moving the X
  88314. // and up & down keys are moving the Y
  88315. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88316. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88317. this.reverseLeftRight = false;
  88318. this.reverseUpDown = false;
  88319. // collections of pointers
  88320. this._touches = new BABYLON.StringDictionary();
  88321. this.deltaPosition = BABYLON.Vector3.Zero();
  88322. this._joystickSensibility = 25;
  88323. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88324. this._onResize = function (evt) {
  88325. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88326. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88327. if (VirtualJoystick.vjCanvas) {
  88328. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88329. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88330. }
  88331. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88332. };
  88333. // injecting a canvas element on top of the canvas 3D game
  88334. if (!VirtualJoystick.vjCanvas) {
  88335. window.addEventListener("resize", this._onResize, false);
  88336. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88337. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88338. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88339. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88340. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88341. VirtualJoystick.vjCanvas.style.width = "100%";
  88342. VirtualJoystick.vjCanvas.style.height = "100%";
  88343. VirtualJoystick.vjCanvas.style.position = "absolute";
  88344. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88345. VirtualJoystick.vjCanvas.style.top = "0px";
  88346. VirtualJoystick.vjCanvas.style.left = "0px";
  88347. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88348. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88349. // Support for jQuery PEP polyfill
  88350. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88351. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88352. if (!context) {
  88353. throw new Error("Unable to create canvas for virtual joystick");
  88354. }
  88355. VirtualJoystick.vjCanvasContext = context;
  88356. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88357. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88358. document.body.appendChild(VirtualJoystick.vjCanvas);
  88359. }
  88360. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88361. this.pressed = false;
  88362. // default joystick color
  88363. this._joystickColor = "cyan";
  88364. this._joystickPointerID = -1;
  88365. // current joystick position
  88366. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88367. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88368. // origin joystick position
  88369. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88370. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88371. this._onPointerDownHandlerRef = function (evt) {
  88372. _this._onPointerDown(evt);
  88373. };
  88374. this._onPointerMoveHandlerRef = function (evt) {
  88375. _this._onPointerMove(evt);
  88376. };
  88377. this._onPointerUpHandlerRef = function (evt) {
  88378. _this._onPointerUp(evt);
  88379. };
  88380. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88381. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88382. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88383. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88384. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88385. evt.preventDefault(); // Disables system menu
  88386. }, false);
  88387. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88388. }
  88389. /**
  88390. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  88391. * @param newJoystickSensibility defines the new sensibility
  88392. */
  88393. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88394. this._joystickSensibility = newJoystickSensibility;
  88395. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88396. };
  88397. VirtualJoystick.prototype._onPointerDown = function (e) {
  88398. var positionOnScreenCondition;
  88399. e.preventDefault();
  88400. if (this._leftJoystick === true) {
  88401. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88402. }
  88403. else {
  88404. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88405. }
  88406. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88407. // First contact will be dedicated to the virtual joystick
  88408. this._joystickPointerID = e.pointerId;
  88409. this._joystickPointerStartPos.x = e.clientX;
  88410. this._joystickPointerStartPos.y = e.clientY;
  88411. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  88412. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  88413. this._deltaJoystickVector.x = 0;
  88414. this._deltaJoystickVector.y = 0;
  88415. this.pressed = true;
  88416. this._touches.add(e.pointerId.toString(), e);
  88417. }
  88418. else {
  88419. // You can only trigger the action buttons with a joystick declared
  88420. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  88421. this._action();
  88422. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  88423. }
  88424. }
  88425. };
  88426. VirtualJoystick.prototype._onPointerMove = function (e) {
  88427. // If the current pointer is the one associated to the joystick (first touch contact)
  88428. if (this._joystickPointerID == e.pointerId) {
  88429. this._joystickPointerPos.x = e.clientX;
  88430. this._joystickPointerPos.y = e.clientY;
  88431. this._deltaJoystickVector = this._joystickPointerPos.clone();
  88432. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  88433. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  88434. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  88435. switch (this._axisTargetedByLeftAndRight) {
  88436. case JoystickAxis.X:
  88437. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  88438. break;
  88439. case JoystickAxis.Y:
  88440. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  88441. break;
  88442. case JoystickAxis.Z:
  88443. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  88444. break;
  88445. }
  88446. var directionUpDown = this.reverseUpDown ? 1 : -1;
  88447. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  88448. switch (this._axisTargetedByUpAndDown) {
  88449. case JoystickAxis.X:
  88450. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  88451. break;
  88452. case JoystickAxis.Y:
  88453. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  88454. break;
  88455. case JoystickAxis.Z:
  88456. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  88457. break;
  88458. }
  88459. }
  88460. else {
  88461. var data = this._touches.get(e.pointerId.toString());
  88462. if (data) {
  88463. data.x = e.clientX;
  88464. data.y = e.clientY;
  88465. }
  88466. }
  88467. };
  88468. VirtualJoystick.prototype._onPointerUp = function (e) {
  88469. if (this._joystickPointerID == e.pointerId) {
  88470. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  88471. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  88472. this._joystickPointerID = -1;
  88473. this.pressed = false;
  88474. }
  88475. else {
  88476. var touch = this._touches.get(e.pointerId.toString());
  88477. if (touch) {
  88478. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88479. }
  88480. }
  88481. this._deltaJoystickVector.x = 0;
  88482. this._deltaJoystickVector.y = 0;
  88483. this._touches.remove(e.pointerId.toString());
  88484. };
  88485. /**
  88486. * Change the color of the virtual joystick
  88487. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  88488. */
  88489. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  88490. this._joystickColor = newColor;
  88491. };
  88492. /**
  88493. * Defines a callback to call when the joystick is touched
  88494. * @param action defines the callback
  88495. */
  88496. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  88497. this._action = action;
  88498. };
  88499. /**
  88500. * Defines which axis you'd like to control for left & right
  88501. * @param axis defines the axis to use
  88502. */
  88503. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  88504. switch (axis) {
  88505. case JoystickAxis.X:
  88506. case JoystickAxis.Y:
  88507. case JoystickAxis.Z:
  88508. this._axisTargetedByLeftAndRight = axis;
  88509. break;
  88510. default:
  88511. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88512. break;
  88513. }
  88514. };
  88515. /**
  88516. * Defines which axis you'd like to control for up & down
  88517. * @param axis defines the axis to use
  88518. */
  88519. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  88520. switch (axis) {
  88521. case JoystickAxis.X:
  88522. case JoystickAxis.Y:
  88523. case JoystickAxis.Z:
  88524. this._axisTargetedByUpAndDown = axis;
  88525. break;
  88526. default:
  88527. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88528. break;
  88529. }
  88530. };
  88531. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  88532. var _this = this;
  88533. if (this.pressed) {
  88534. this._touches.forEach(function (key, touch) {
  88535. if (touch.pointerId === _this._joystickPointerID) {
  88536. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  88537. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  88538. VirtualJoystick.vjCanvasContext.beginPath();
  88539. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88540. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88541. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  88542. VirtualJoystick.vjCanvasContext.stroke();
  88543. VirtualJoystick.vjCanvasContext.closePath();
  88544. VirtualJoystick.vjCanvasContext.beginPath();
  88545. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88546. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88547. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  88548. VirtualJoystick.vjCanvasContext.stroke();
  88549. VirtualJoystick.vjCanvasContext.closePath();
  88550. VirtualJoystick.vjCanvasContext.beginPath();
  88551. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88552. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  88553. VirtualJoystick.vjCanvasContext.stroke();
  88554. VirtualJoystick.vjCanvasContext.closePath();
  88555. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  88556. }
  88557. else {
  88558. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88559. VirtualJoystick.vjCanvasContext.beginPath();
  88560. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  88561. VirtualJoystick.vjCanvasContext.beginPath();
  88562. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  88563. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88564. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  88565. VirtualJoystick.vjCanvasContext.stroke();
  88566. VirtualJoystick.vjCanvasContext.closePath();
  88567. touch.prevX = touch.x;
  88568. touch.prevY = touch.y;
  88569. }
  88570. ;
  88571. });
  88572. }
  88573. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88574. };
  88575. /**
  88576. * Release internal HTML canvas
  88577. */
  88578. VirtualJoystick.prototype.releaseCanvas = function () {
  88579. if (VirtualJoystick.vjCanvas) {
  88580. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  88581. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  88582. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  88583. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  88584. window.removeEventListener("resize", this._onResize);
  88585. document.body.removeChild(VirtualJoystick.vjCanvas);
  88586. VirtualJoystick.vjCanvas = null;
  88587. }
  88588. };
  88589. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  88590. VirtualJoystick._globalJoystickIndex = 0;
  88591. return VirtualJoystick;
  88592. }());
  88593. BABYLON.VirtualJoystick = VirtualJoystick;
  88594. })(BABYLON || (BABYLON = {}));
  88595. //# sourceMappingURL=babylon.virtualJoystick.js.map
  88596. var BABYLON;
  88597. (function (BABYLON) {
  88598. // We're mainly based on the logic defined into the FreeCamera code
  88599. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  88600. __extends(VirtualJoysticksCamera, _super);
  88601. function VirtualJoysticksCamera(name, position, scene) {
  88602. var _this = _super.call(this, name, position, scene) || this;
  88603. _this.inputs.addVirtualJoystick();
  88604. return _this;
  88605. }
  88606. VirtualJoysticksCamera.prototype.getClassName = function () {
  88607. return "VirtualJoysticksCamera";
  88608. };
  88609. return VirtualJoysticksCamera;
  88610. }(BABYLON.FreeCamera));
  88611. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  88612. })(BABYLON || (BABYLON = {}));
  88613. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  88614. var BABYLON;
  88615. (function (BABYLON) {
  88616. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  88617. function FreeCameraVirtualJoystickInput() {
  88618. }
  88619. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  88620. return this._leftjoystick;
  88621. };
  88622. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  88623. return this._rightjoystick;
  88624. };
  88625. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  88626. if (this._leftjoystick) {
  88627. var camera = this.camera;
  88628. var speed = camera._computeLocalCameraSpeed() * 50;
  88629. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  88630. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  88631. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  88632. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  88633. if (!this._leftjoystick.pressed) {
  88634. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  88635. }
  88636. if (!this._rightjoystick.pressed) {
  88637. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  88638. }
  88639. }
  88640. };
  88641. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  88642. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  88643. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  88644. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  88645. this._leftjoystick.setJoystickSensibility(0.15);
  88646. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  88647. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  88648. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  88649. this._rightjoystick.reverseUpDown = true;
  88650. this._rightjoystick.setJoystickSensibility(0.05);
  88651. this._rightjoystick.setJoystickColor("yellow");
  88652. };
  88653. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  88654. this._leftjoystick.releaseCanvas();
  88655. this._rightjoystick.releaseCanvas();
  88656. };
  88657. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  88658. return "FreeCameraVirtualJoystickInput";
  88659. };
  88660. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  88661. return "virtualJoystick";
  88662. };
  88663. return FreeCameraVirtualJoystickInput;
  88664. }());
  88665. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  88666. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  88667. })(BABYLON || (BABYLON = {}));
  88668. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  88669. var BABYLON;
  88670. (function (BABYLON) {
  88671. var SimplificationSettings = /** @class */ (function () {
  88672. function SimplificationSettings(quality, distance, optimizeMesh) {
  88673. this.quality = quality;
  88674. this.distance = distance;
  88675. this.optimizeMesh = optimizeMesh;
  88676. }
  88677. return SimplificationSettings;
  88678. }());
  88679. BABYLON.SimplificationSettings = SimplificationSettings;
  88680. var SimplificationQueue = /** @class */ (function () {
  88681. function SimplificationQueue() {
  88682. this.running = false;
  88683. this._simplificationArray = [];
  88684. }
  88685. SimplificationQueue.prototype.addTask = function (task) {
  88686. this._simplificationArray.push(task);
  88687. };
  88688. SimplificationQueue.prototype.executeNext = function () {
  88689. var task = this._simplificationArray.pop();
  88690. if (task) {
  88691. this.running = true;
  88692. this.runSimplification(task);
  88693. }
  88694. else {
  88695. this.running = false;
  88696. }
  88697. };
  88698. SimplificationQueue.prototype.runSimplification = function (task) {
  88699. var _this = this;
  88700. if (task.parallelProcessing) {
  88701. //parallel simplifier
  88702. task.settings.forEach(function (setting) {
  88703. var simplifier = _this.getSimplifier(task);
  88704. simplifier.simplify(setting, function (newMesh) {
  88705. task.mesh.addLODLevel(setting.distance, newMesh);
  88706. newMesh.isVisible = true;
  88707. //check if it is the last
  88708. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  88709. //all done, run the success callback.
  88710. task.successCallback();
  88711. }
  88712. _this.executeNext();
  88713. });
  88714. });
  88715. }
  88716. else {
  88717. //single simplifier.
  88718. var simplifier = this.getSimplifier(task);
  88719. var runDecimation = function (setting, callback) {
  88720. simplifier.simplify(setting, function (newMesh) {
  88721. task.mesh.addLODLevel(setting.distance, newMesh);
  88722. newMesh.isVisible = true;
  88723. //run the next quality level
  88724. callback();
  88725. });
  88726. };
  88727. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  88728. runDecimation(task.settings[loop.index], function () {
  88729. loop.executeNext();
  88730. });
  88731. }, function () {
  88732. //execution ended, run the success callback.
  88733. if (task.successCallback) {
  88734. task.successCallback();
  88735. }
  88736. _this.executeNext();
  88737. });
  88738. }
  88739. };
  88740. SimplificationQueue.prototype.getSimplifier = function (task) {
  88741. switch (task.simplificationType) {
  88742. case SimplificationType.QUADRATIC:
  88743. default:
  88744. return new QuadraticErrorSimplification(task.mesh);
  88745. }
  88746. };
  88747. return SimplificationQueue;
  88748. }());
  88749. BABYLON.SimplificationQueue = SimplificationQueue;
  88750. /**
  88751. * The implemented types of simplification
  88752. * At the moment only Quadratic Error Decimation is implemented
  88753. */
  88754. var SimplificationType;
  88755. (function (SimplificationType) {
  88756. /** Quadratic error decimation */
  88757. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  88758. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  88759. var DecimationTriangle = /** @class */ (function () {
  88760. function DecimationTriangle(vertices) {
  88761. this.vertices = vertices;
  88762. this.error = new Array(4);
  88763. this.deleted = false;
  88764. this.isDirty = false;
  88765. this.deletePending = false;
  88766. this.borderFactor = 0;
  88767. }
  88768. return DecimationTriangle;
  88769. }());
  88770. BABYLON.DecimationTriangle = DecimationTriangle;
  88771. var DecimationVertex = /** @class */ (function () {
  88772. function DecimationVertex(position, id) {
  88773. this.position = position;
  88774. this.id = id;
  88775. this.isBorder = true;
  88776. this.q = new QuadraticMatrix();
  88777. this.triangleCount = 0;
  88778. this.triangleStart = 0;
  88779. this.originalOffsets = [];
  88780. }
  88781. DecimationVertex.prototype.updatePosition = function (newPosition) {
  88782. this.position.copyFrom(newPosition);
  88783. };
  88784. return DecimationVertex;
  88785. }());
  88786. BABYLON.DecimationVertex = DecimationVertex;
  88787. var QuadraticMatrix = /** @class */ (function () {
  88788. function QuadraticMatrix(data) {
  88789. this.data = new Array(10);
  88790. for (var i = 0; i < 10; ++i) {
  88791. if (data && data[i]) {
  88792. this.data[i] = data[i];
  88793. }
  88794. else {
  88795. this.data[i] = 0;
  88796. }
  88797. }
  88798. }
  88799. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  88800. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  88801. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  88802. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  88803. return det;
  88804. };
  88805. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  88806. for (var i = 0; i < 10; ++i) {
  88807. this.data[i] += matrix.data[i];
  88808. }
  88809. };
  88810. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  88811. for (var i = 0; i < 10; ++i) {
  88812. this.data[i] += data[i];
  88813. }
  88814. };
  88815. QuadraticMatrix.prototype.add = function (matrix) {
  88816. var m = new QuadraticMatrix();
  88817. for (var i = 0; i < 10; ++i) {
  88818. m.data[i] = this.data[i] + matrix.data[i];
  88819. }
  88820. return m;
  88821. };
  88822. QuadraticMatrix.FromData = function (a, b, c, d) {
  88823. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  88824. };
  88825. //returning an array to avoid garbage collection
  88826. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  88827. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  88828. };
  88829. return QuadraticMatrix;
  88830. }());
  88831. BABYLON.QuadraticMatrix = QuadraticMatrix;
  88832. var Reference = /** @class */ (function () {
  88833. function Reference(vertexId, triangleId) {
  88834. this.vertexId = vertexId;
  88835. this.triangleId = triangleId;
  88836. }
  88837. return Reference;
  88838. }());
  88839. BABYLON.Reference = Reference;
  88840. /**
  88841. * An implementation of the Quadratic Error simplification algorithm.
  88842. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  88843. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  88844. * @author RaananW
  88845. */
  88846. var QuadraticErrorSimplification = /** @class */ (function () {
  88847. function QuadraticErrorSimplification(_mesh) {
  88848. this._mesh = _mesh;
  88849. this.syncIterations = 5000;
  88850. this.aggressiveness = 7;
  88851. this.decimationIterations = 100;
  88852. this.boundingBoxEpsilon = BABYLON.Epsilon;
  88853. }
  88854. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  88855. var _this = this;
  88856. this.initDecimatedMesh();
  88857. //iterating through the submeshes array, one after the other.
  88858. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  88859. _this.initWithMesh(loop.index, function () {
  88860. _this.runDecimation(settings, loop.index, function () {
  88861. loop.executeNext();
  88862. });
  88863. }, settings.optimizeMesh);
  88864. }, function () {
  88865. setTimeout(function () {
  88866. successCallback(_this._reconstructedMesh);
  88867. }, 0);
  88868. });
  88869. };
  88870. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  88871. var _this = this;
  88872. var targetCount = ~~(this.triangles.length * settings.quality);
  88873. var deletedTriangles = 0;
  88874. var triangleCount = this.triangles.length;
  88875. var iterationFunction = function (iteration, callback) {
  88876. setTimeout(function () {
  88877. if (iteration % 5 === 0) {
  88878. _this.updateMesh(iteration === 0);
  88879. }
  88880. for (var i = 0; i < _this.triangles.length; ++i) {
  88881. _this.triangles[i].isDirty = false;
  88882. }
  88883. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  88884. var trianglesIterator = function (i) {
  88885. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  88886. var t = _this.triangles[tIdx];
  88887. if (!t)
  88888. return;
  88889. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  88890. return;
  88891. }
  88892. for (var j = 0; j < 3; ++j) {
  88893. if (t.error[j] < threshold) {
  88894. var deleted0 = [];
  88895. var deleted1 = [];
  88896. var v0 = t.vertices[j];
  88897. var v1 = t.vertices[(j + 1) % 3];
  88898. if (v0.isBorder || v1.isBorder)
  88899. continue;
  88900. var p = BABYLON.Vector3.Zero();
  88901. var n = BABYLON.Vector3.Zero();
  88902. var uv = BABYLON.Vector2.Zero();
  88903. var color = new BABYLON.Color4(0, 0, 0, 1);
  88904. _this.calculateError(v0, v1, p, n, uv, color);
  88905. var delTr = new Array();
  88906. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  88907. continue;
  88908. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  88909. continue;
  88910. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  88911. continue;
  88912. var uniqueArray = new Array();
  88913. delTr.forEach(function (deletedT) {
  88914. if (uniqueArray.indexOf(deletedT) === -1) {
  88915. deletedT.deletePending = true;
  88916. uniqueArray.push(deletedT);
  88917. }
  88918. });
  88919. if (uniqueArray.length % 2 !== 0) {
  88920. continue;
  88921. }
  88922. v0.q = v1.q.add(v0.q);
  88923. v0.updatePosition(p);
  88924. var tStart = _this.references.length;
  88925. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  88926. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  88927. var tCount = _this.references.length - tStart;
  88928. if (tCount <= v0.triangleCount) {
  88929. if (tCount) {
  88930. for (var c = 0; c < tCount; c++) {
  88931. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  88932. }
  88933. }
  88934. }
  88935. else {
  88936. v0.triangleStart = tStart;
  88937. }
  88938. v0.triangleCount = tCount;
  88939. break;
  88940. }
  88941. }
  88942. };
  88943. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  88944. }, 0);
  88945. };
  88946. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  88947. if (triangleCount - deletedTriangles <= targetCount)
  88948. loop.breakLoop();
  88949. else {
  88950. iterationFunction(loop.index, function () {
  88951. loop.executeNext();
  88952. });
  88953. }
  88954. }, function () {
  88955. setTimeout(function () {
  88956. //reconstruct this part of the mesh
  88957. _this.reconstructMesh(submeshIndex);
  88958. successCallback();
  88959. }, 0);
  88960. });
  88961. };
  88962. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  88963. var _this = this;
  88964. this.vertices = [];
  88965. this.triangles = [];
  88966. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88967. var indices = this._mesh.getIndices();
  88968. var submesh = this._mesh.subMeshes[submeshIndex];
  88969. var findInVertices = function (positionToSearch) {
  88970. if (optimizeMesh) {
  88971. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  88972. if (_this.vertices[ii].position.equals(positionToSearch)) {
  88973. return _this.vertices[ii];
  88974. }
  88975. }
  88976. }
  88977. return null;
  88978. };
  88979. var vertexReferences = [];
  88980. var vertexInit = function (i) {
  88981. if (!positionData) {
  88982. return;
  88983. }
  88984. var offset = i + submesh.verticesStart;
  88985. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  88986. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  88987. vertex.originalOffsets.push(offset);
  88988. if (vertex.id === _this.vertices.length) {
  88989. _this.vertices.push(vertex);
  88990. }
  88991. vertexReferences.push(vertex.id);
  88992. };
  88993. //var totalVertices = mesh.getTotalVertices();
  88994. var totalVertices = submesh.verticesCount;
  88995. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  88996. var indicesInit = function (i) {
  88997. if (!indices) {
  88998. return;
  88999. }
  89000. var offset = (submesh.indexStart / 3) + i;
  89001. var pos = (offset * 3);
  89002. var i0 = indices[pos + 0];
  89003. var i1 = indices[pos + 1];
  89004. var i2 = indices[pos + 2];
  89005. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89006. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89007. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89008. var triangle = new DecimationTriangle([v0, v1, v2]);
  89009. triangle.originalOffset = pos;
  89010. _this.triangles.push(triangle);
  89011. };
  89012. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89013. _this.init(callback);
  89014. });
  89015. });
  89016. };
  89017. QuadraticErrorSimplification.prototype.init = function (callback) {
  89018. var _this = this;
  89019. var triangleInit1 = function (i) {
  89020. var t = _this.triangles[i];
  89021. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89022. for (var j = 0; j < 3; j++) {
  89023. 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))));
  89024. }
  89025. };
  89026. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89027. var triangleInit2 = function (i) {
  89028. var t = _this.triangles[i];
  89029. for (var j = 0; j < 3; ++j) {
  89030. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89031. }
  89032. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89033. };
  89034. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89035. callback();
  89036. });
  89037. });
  89038. };
  89039. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89040. var newTriangles = [];
  89041. var i;
  89042. for (i = 0; i < this.vertices.length; ++i) {
  89043. this.vertices[i].triangleCount = 0;
  89044. }
  89045. var t;
  89046. var j;
  89047. for (i = 0; i < this.triangles.length; ++i) {
  89048. if (!this.triangles[i].deleted) {
  89049. t = this.triangles[i];
  89050. for (j = 0; j < 3; ++j) {
  89051. t.vertices[j].triangleCount = 1;
  89052. }
  89053. newTriangles.push(t);
  89054. }
  89055. }
  89056. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89057. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89058. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89059. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89060. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89061. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89062. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89063. var vertexCount = 0;
  89064. for (i = 0; i < this.vertices.length; ++i) {
  89065. var vertex = this.vertices[i];
  89066. vertex.id = vertexCount;
  89067. if (vertex.triangleCount) {
  89068. vertex.originalOffsets.forEach(function (originalOffset) {
  89069. if (!normalData) {
  89070. return;
  89071. }
  89072. newPositionData.push(vertex.position.x);
  89073. newPositionData.push(vertex.position.y);
  89074. newPositionData.push(vertex.position.z);
  89075. newNormalData.push(normalData[originalOffset * 3]);
  89076. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89077. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89078. if (uvs && uvs.length) {
  89079. newUVsData.push(uvs[(originalOffset * 2)]);
  89080. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89081. }
  89082. else if (colorsData && colorsData.length) {
  89083. newColorsData.push(colorsData[(originalOffset * 4)]);
  89084. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89085. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89086. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89087. }
  89088. ++vertexCount;
  89089. });
  89090. }
  89091. }
  89092. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89093. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89094. var submeshesArray = this._reconstructedMesh.subMeshes;
  89095. this._reconstructedMesh.subMeshes = [];
  89096. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89097. var originalIndices = this._mesh.getIndices();
  89098. for (i = 0; i < newTriangles.length; ++i) {
  89099. t = newTriangles[i]; //now get the new referencing point for each vertex
  89100. [0, 1, 2].forEach(function (idx) {
  89101. var id = originalIndices[t.originalOffset + idx];
  89102. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89103. if (offset < 0)
  89104. offset = 0;
  89105. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89106. });
  89107. }
  89108. //overwriting the old vertex buffers and indices.
  89109. this._reconstructedMesh.setIndices(newIndicesArray);
  89110. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89111. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89112. if (newUVsData.length > 0)
  89113. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89114. if (newColorsData.length > 0)
  89115. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89116. //create submesh
  89117. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89118. if (submeshIndex > 0) {
  89119. this._reconstructedMesh.subMeshes = [];
  89120. submeshesArray.forEach(function (submesh) {
  89121. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89122. });
  89123. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89124. }
  89125. };
  89126. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89127. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89128. this._reconstructedMesh.material = this._mesh.material;
  89129. this._reconstructedMesh.parent = this._mesh.parent;
  89130. this._reconstructedMesh.isVisible = false;
  89131. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89132. };
  89133. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89134. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89135. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89136. if (t.deleted)
  89137. continue;
  89138. var s = this.references[vertex1.triangleStart + i].vertexId;
  89139. var v1 = t.vertices[(s + 1) % 3];
  89140. var v2 = t.vertices[(s + 2) % 3];
  89141. if ((v1 === vertex2 || v2 === vertex2)) {
  89142. deletedArray[i] = true;
  89143. delTr.push(t);
  89144. continue;
  89145. }
  89146. var d1 = v1.position.subtract(point);
  89147. d1 = d1.normalize();
  89148. var d2 = v2.position.subtract(point);
  89149. d2 = d2.normalize();
  89150. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89151. return true;
  89152. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89153. deletedArray[i] = false;
  89154. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89155. return true;
  89156. }
  89157. return false;
  89158. };
  89159. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89160. var newDeleted = deletedTriangles;
  89161. for (var i = 0; i < vertex.triangleCount; ++i) {
  89162. var ref = this.references[vertex.triangleStart + i];
  89163. var t = this.triangles[ref.triangleId];
  89164. if (t.deleted)
  89165. continue;
  89166. if (deletedArray[i] && t.deletePending) {
  89167. t.deleted = true;
  89168. newDeleted++;
  89169. continue;
  89170. }
  89171. t.vertices[ref.vertexId] = origVertex;
  89172. t.isDirty = true;
  89173. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89174. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89175. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89176. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89177. this.references.push(ref);
  89178. }
  89179. return newDeleted;
  89180. };
  89181. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89182. for (var i = 0; i < this.vertices.length; ++i) {
  89183. var vCount = [];
  89184. var vId = [];
  89185. var v = this.vertices[i];
  89186. var j;
  89187. for (j = 0; j < v.triangleCount; ++j) {
  89188. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89189. for (var ii = 0; ii < 3; ii++) {
  89190. var ofs = 0;
  89191. var vv = triangle.vertices[ii];
  89192. while (ofs < vCount.length) {
  89193. if (vId[ofs] === vv.id)
  89194. break;
  89195. ++ofs;
  89196. }
  89197. if (ofs === vCount.length) {
  89198. vCount.push(1);
  89199. vId.push(vv.id);
  89200. }
  89201. else {
  89202. vCount[ofs]++;
  89203. }
  89204. }
  89205. }
  89206. for (j = 0; j < vCount.length; ++j) {
  89207. if (vCount[j] === 1) {
  89208. this.vertices[vId[j]].isBorder = true;
  89209. }
  89210. else {
  89211. this.vertices[vId[j]].isBorder = false;
  89212. }
  89213. }
  89214. }
  89215. };
  89216. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89217. if (identifyBorders === void 0) { identifyBorders = false; }
  89218. var i;
  89219. if (!identifyBorders) {
  89220. var newTrianglesVector = [];
  89221. for (i = 0; i < this.triangles.length; ++i) {
  89222. if (!this.triangles[i].deleted) {
  89223. newTrianglesVector.push(this.triangles[i]);
  89224. }
  89225. }
  89226. this.triangles = newTrianglesVector;
  89227. }
  89228. for (i = 0; i < this.vertices.length; ++i) {
  89229. this.vertices[i].triangleCount = 0;
  89230. this.vertices[i].triangleStart = 0;
  89231. }
  89232. var t;
  89233. var j;
  89234. var v;
  89235. for (i = 0; i < this.triangles.length; ++i) {
  89236. t = this.triangles[i];
  89237. for (j = 0; j < 3; ++j) {
  89238. v = t.vertices[j];
  89239. v.triangleCount++;
  89240. }
  89241. }
  89242. var tStart = 0;
  89243. for (i = 0; i < this.vertices.length; ++i) {
  89244. this.vertices[i].triangleStart = tStart;
  89245. tStart += this.vertices[i].triangleCount;
  89246. this.vertices[i].triangleCount = 0;
  89247. }
  89248. var newReferences = new Array(this.triangles.length * 3);
  89249. for (i = 0; i < this.triangles.length; ++i) {
  89250. t = this.triangles[i];
  89251. for (j = 0; j < 3; ++j) {
  89252. v = t.vertices[j];
  89253. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89254. v.triangleCount++;
  89255. }
  89256. }
  89257. this.references = newReferences;
  89258. if (identifyBorders) {
  89259. this.identifyBorder();
  89260. }
  89261. };
  89262. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89263. var x = point.x;
  89264. var y = point.y;
  89265. var z = point.z;
  89266. 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
  89267. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89268. };
  89269. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89270. var q = vertex1.q.add(vertex2.q);
  89271. var border = vertex1.isBorder && vertex2.isBorder;
  89272. var error = 0;
  89273. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89274. if (qDet !== 0 && !border) {
  89275. if (!pointResult) {
  89276. pointResult = BABYLON.Vector3.Zero();
  89277. }
  89278. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89279. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89280. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89281. error = this.vertexError(q, pointResult);
  89282. }
  89283. else {
  89284. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89285. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89286. var error1 = this.vertexError(q, vertex1.position);
  89287. var error2 = this.vertexError(q, vertex2.position);
  89288. var error3 = this.vertexError(q, p3);
  89289. error = Math.min(error1, error2, error3);
  89290. if (error === error1) {
  89291. if (pointResult) {
  89292. pointResult.copyFrom(vertex1.position);
  89293. }
  89294. }
  89295. else if (error === error2) {
  89296. if (pointResult) {
  89297. pointResult.copyFrom(vertex2.position);
  89298. }
  89299. }
  89300. else {
  89301. if (pointResult) {
  89302. pointResult.copyFrom(p3);
  89303. }
  89304. }
  89305. }
  89306. return error;
  89307. };
  89308. return QuadraticErrorSimplification;
  89309. }());
  89310. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89311. })(BABYLON || (BABYLON = {}));
  89312. //# sourceMappingURL=babylon.meshSimplification.js.map
  89313. var BABYLON;
  89314. (function (BABYLON) {
  89315. var MeshLODLevel = /** @class */ (function () {
  89316. function MeshLODLevel(distance, mesh) {
  89317. this.distance = distance;
  89318. this.mesh = mesh;
  89319. }
  89320. return MeshLODLevel;
  89321. }());
  89322. BABYLON.MeshLODLevel = MeshLODLevel;
  89323. })(BABYLON || (BABYLON = {}));
  89324. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89325. var BABYLON;
  89326. (function (BABYLON) {
  89327. /**
  89328. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89329. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89330. */
  89331. var SceneOptimization = /** @class */ (function () {
  89332. /**
  89333. * Creates the SceneOptimization object
  89334. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89335. * @param desc defines the description associated with the optimization
  89336. */
  89337. function SceneOptimization(
  89338. /**
  89339. * Defines the priority of this optimization (0 by default which means first in the list)
  89340. */
  89341. priority) {
  89342. if (priority === void 0) { priority = 0; }
  89343. this.priority = priority;
  89344. }
  89345. /**
  89346. * Gets a string describing the action executed by the current optimization
  89347. * @returns description string
  89348. */
  89349. SceneOptimization.prototype.getDescription = function () {
  89350. return "";
  89351. };
  89352. /**
  89353. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89354. * @param scene defines the current scene where to apply this optimization
  89355. * @param optimizer defines the current optimizer
  89356. * @returns true if everything that can be done was applied
  89357. */
  89358. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89359. return true;
  89360. };
  89361. ;
  89362. return SceneOptimization;
  89363. }());
  89364. BABYLON.SceneOptimization = SceneOptimization;
  89365. /**
  89366. * Defines an optimization used to reduce the size of render target textures
  89367. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89368. */
  89369. var TextureOptimization = /** @class */ (function (_super) {
  89370. __extends(TextureOptimization, _super);
  89371. /**
  89372. * Creates the TextureOptimization object
  89373. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89374. * @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
  89375. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89376. */
  89377. function TextureOptimization(
  89378. /**
  89379. * Defines the priority of this optimization (0 by default which means first in the list)
  89380. */
  89381. priority,
  89382. /**
  89383. * 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
  89384. */
  89385. maximumSize,
  89386. /**
  89387. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89388. */
  89389. step) {
  89390. if (priority === void 0) { priority = 0; }
  89391. if (maximumSize === void 0) { maximumSize = 1024; }
  89392. if (step === void 0) { step = 0.5; }
  89393. var _this = _super.call(this, priority) || this;
  89394. _this.priority = priority;
  89395. _this.maximumSize = maximumSize;
  89396. _this.step = step;
  89397. return _this;
  89398. }
  89399. /**
  89400. * Gets a string describing the action executed by the current optimization
  89401. * @returns description string
  89402. */
  89403. TextureOptimization.prototype.getDescription = function () {
  89404. return "Reducing render target texture size to " + this.maximumSize;
  89405. };
  89406. /**
  89407. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89408. * @param scene defines the current scene where to apply this optimization
  89409. * @param optimizer defines the current optimizer
  89410. * @returns true if everything that can be done was applied
  89411. */
  89412. TextureOptimization.prototype.apply = function (scene, optimizer) {
  89413. var allDone = true;
  89414. for (var index = 0; index < scene.textures.length; index++) {
  89415. var texture = scene.textures[index];
  89416. if (!texture.canRescale || texture.getContext) {
  89417. continue;
  89418. }
  89419. var currentSize = texture.getSize();
  89420. var maxDimension = Math.max(currentSize.width, currentSize.height);
  89421. if (maxDimension > this.maximumSize) {
  89422. texture.scale(this.step);
  89423. allDone = false;
  89424. }
  89425. }
  89426. return allDone;
  89427. };
  89428. return TextureOptimization;
  89429. }(SceneOptimization));
  89430. BABYLON.TextureOptimization = TextureOptimization;
  89431. /**
  89432. * Defines an optimization used to increase or decrease the rendering resolution
  89433. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89434. */
  89435. var HardwareScalingOptimization = /** @class */ (function (_super) {
  89436. __extends(HardwareScalingOptimization, _super);
  89437. /**
  89438. * Creates the HardwareScalingOptimization object
  89439. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89440. * @param maximumScale defines the maximum scale to use (2 by default)
  89441. * @param step defines the step to use between two passes (0.5 by default)
  89442. */
  89443. function HardwareScalingOptimization(
  89444. /**
  89445. * Defines the priority of this optimization (0 by default which means first in the list)
  89446. */
  89447. priority,
  89448. /**
  89449. * Defines the maximum scale to use (2 by default)
  89450. */
  89451. maximumScale,
  89452. /**
  89453. * Defines the step to use between two passes (0.5 by default)
  89454. */
  89455. step) {
  89456. if (priority === void 0) { priority = 0; }
  89457. if (maximumScale === void 0) { maximumScale = 2; }
  89458. if (step === void 0) { step = 0.25; }
  89459. var _this = _super.call(this, priority) || this;
  89460. _this.priority = priority;
  89461. _this.maximumScale = maximumScale;
  89462. _this.step = step;
  89463. _this._currentScale = -1;
  89464. _this._directionOffset = 1;
  89465. return _this;
  89466. }
  89467. /**
  89468. * Gets a string describing the action executed by the current optimization
  89469. * @return description string
  89470. */
  89471. HardwareScalingOptimization.prototype.getDescription = function () {
  89472. return "Setting hardware scaling level to " + this._currentScale;
  89473. };
  89474. /**
  89475. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89476. * @param scene defines the current scene where to apply this optimization
  89477. * @param optimizer defines the current optimizer
  89478. * @returns true if everything that can be done was applied
  89479. */
  89480. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  89481. if (this._currentScale === -1) {
  89482. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  89483. if (this._currentScale > this.maximumScale) {
  89484. this._directionOffset = -1;
  89485. }
  89486. }
  89487. this._currentScale += this._directionOffset * this.step;
  89488. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  89489. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  89490. };
  89491. ;
  89492. return HardwareScalingOptimization;
  89493. }(SceneOptimization));
  89494. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  89495. /**
  89496. * Defines an optimization used to remove shadows
  89497. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89498. */
  89499. var ShadowsOptimization = /** @class */ (function (_super) {
  89500. __extends(ShadowsOptimization, _super);
  89501. function ShadowsOptimization() {
  89502. return _super !== null && _super.apply(this, arguments) || this;
  89503. }
  89504. /**
  89505. * Gets a string describing the action executed by the current optimization
  89506. * @return description string
  89507. */
  89508. ShadowsOptimization.prototype.getDescription = function () {
  89509. return "Turning shadows on/off";
  89510. };
  89511. /**
  89512. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89513. * @param scene defines the current scene where to apply this optimization
  89514. * @param optimizer defines the current optimizer
  89515. * @returns true if everything that can be done was applied
  89516. */
  89517. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  89518. scene.shadowsEnabled = optimizer.isInImprovementMode;
  89519. return true;
  89520. };
  89521. ;
  89522. return ShadowsOptimization;
  89523. }(SceneOptimization));
  89524. BABYLON.ShadowsOptimization = ShadowsOptimization;
  89525. /**
  89526. * Defines an optimization used to turn post-processes off
  89527. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89528. */
  89529. var PostProcessesOptimization = /** @class */ (function (_super) {
  89530. __extends(PostProcessesOptimization, _super);
  89531. function PostProcessesOptimization() {
  89532. return _super !== null && _super.apply(this, arguments) || this;
  89533. }
  89534. /**
  89535. * Gets a string describing the action executed by the current optimization
  89536. * @return description string
  89537. */
  89538. PostProcessesOptimization.prototype.getDescription = function () {
  89539. return "Turning post-processes on/off";
  89540. };
  89541. /**
  89542. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89543. * @param scene defines the current scene where to apply this optimization
  89544. * @param optimizer defines the current optimizer
  89545. * @returns true if everything that can be done was applied
  89546. */
  89547. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  89548. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  89549. return true;
  89550. };
  89551. ;
  89552. return PostProcessesOptimization;
  89553. }(SceneOptimization));
  89554. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  89555. /**
  89556. * Defines an optimization used to turn lens flares off
  89557. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89558. */
  89559. var LensFlaresOptimization = /** @class */ (function (_super) {
  89560. __extends(LensFlaresOptimization, _super);
  89561. function LensFlaresOptimization() {
  89562. return _super !== null && _super.apply(this, arguments) || this;
  89563. }
  89564. /**
  89565. * Gets a string describing the action executed by the current optimization
  89566. * @return description string
  89567. */
  89568. LensFlaresOptimization.prototype.getDescription = function () {
  89569. return "Turning lens flares on/off";
  89570. };
  89571. /**
  89572. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89573. * @param scene defines the current scene where to apply this optimization
  89574. * @param optimizer defines the current optimizer
  89575. * @returns true if everything that can be done was applied
  89576. */
  89577. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  89578. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  89579. return true;
  89580. };
  89581. ;
  89582. return LensFlaresOptimization;
  89583. }(SceneOptimization));
  89584. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  89585. /**
  89586. * Defines an optimization based on user defined callback.
  89587. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89588. */
  89589. var CustomOptimization = /** @class */ (function (_super) {
  89590. __extends(CustomOptimization, _super);
  89591. function CustomOptimization() {
  89592. return _super !== null && _super.apply(this, arguments) || this;
  89593. }
  89594. /**
  89595. * Gets a string describing the action executed by the current optimization
  89596. * @returns description string
  89597. */
  89598. CustomOptimization.prototype.getDescription = function () {
  89599. if (this.onGetDescription) {
  89600. return this.onGetDescription();
  89601. }
  89602. return "Running user defined callback";
  89603. };
  89604. /**
  89605. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89606. * @param scene defines the current scene where to apply this optimization
  89607. * @param optimizer defines the current optimizer
  89608. * @returns true if everything that can be done was applied
  89609. */
  89610. CustomOptimization.prototype.apply = function (scene, optimizer) {
  89611. if (this.onApply) {
  89612. return this.onApply(scene, optimizer);
  89613. }
  89614. return true;
  89615. };
  89616. ;
  89617. return CustomOptimization;
  89618. }(SceneOptimization));
  89619. BABYLON.CustomOptimization = CustomOptimization;
  89620. /**
  89621. * Defines an optimization used to turn particles off
  89622. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89623. */
  89624. var ParticlesOptimization = /** @class */ (function (_super) {
  89625. __extends(ParticlesOptimization, _super);
  89626. function ParticlesOptimization() {
  89627. return _super !== null && _super.apply(this, arguments) || this;
  89628. }
  89629. /**
  89630. * Gets a string describing the action executed by the current optimization
  89631. * @return description string
  89632. */
  89633. ParticlesOptimization.prototype.getDescription = function () {
  89634. return "Turning particles on/off";
  89635. };
  89636. /**
  89637. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89638. * @param scene defines the current scene where to apply this optimization
  89639. * @param optimizer defines the current optimizer
  89640. * @returns true if everything that can be done was applied
  89641. */
  89642. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  89643. scene.particlesEnabled = optimizer.isInImprovementMode;
  89644. return true;
  89645. };
  89646. ;
  89647. return ParticlesOptimization;
  89648. }(SceneOptimization));
  89649. BABYLON.ParticlesOptimization = ParticlesOptimization;
  89650. /**
  89651. * Defines an optimization used to turn render targets off
  89652. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89653. */
  89654. var RenderTargetsOptimization = /** @class */ (function (_super) {
  89655. __extends(RenderTargetsOptimization, _super);
  89656. function RenderTargetsOptimization() {
  89657. return _super !== null && _super.apply(this, arguments) || this;
  89658. }
  89659. /**
  89660. * Gets a string describing the action executed by the current optimization
  89661. * @return description string
  89662. */
  89663. RenderTargetsOptimization.prototype.getDescription = function () {
  89664. return "Turning render targets off";
  89665. };
  89666. /**
  89667. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89668. * @param scene defines the current scene where to apply this optimization
  89669. * @param optimizer defines the current optimizer
  89670. * @returns true if everything that can be done was applied
  89671. */
  89672. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  89673. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  89674. return true;
  89675. };
  89676. ;
  89677. return RenderTargetsOptimization;
  89678. }(SceneOptimization));
  89679. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  89680. /**
  89681. * Defines an optimization used to merge meshes with compatible materials
  89682. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89683. */
  89684. var MergeMeshesOptimization = /** @class */ (function (_super) {
  89685. __extends(MergeMeshesOptimization, _super);
  89686. function MergeMeshesOptimization() {
  89687. var _this = _super !== null && _super.apply(this, arguments) || this;
  89688. _this._canBeMerged = function (abstractMesh) {
  89689. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  89690. return false;
  89691. }
  89692. var mesh = abstractMesh;
  89693. if (!mesh.isVisible || !mesh.isEnabled()) {
  89694. return false;
  89695. }
  89696. if (mesh.instances.length > 0) {
  89697. return false;
  89698. }
  89699. if (mesh.skeleton || mesh.hasLODLevels) {
  89700. return false;
  89701. }
  89702. if (mesh.parent) {
  89703. return false;
  89704. }
  89705. return true;
  89706. };
  89707. return _this;
  89708. }
  89709. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  89710. /**
  89711. * Gets or sets a boolean which defines if optimization octree has to be updated
  89712. */
  89713. get: function () {
  89714. return MergeMeshesOptimization._UpdateSelectionTree;
  89715. },
  89716. /**
  89717. * Gets or sets a boolean which defines if optimization octree has to be updated
  89718. */
  89719. set: function (value) {
  89720. MergeMeshesOptimization._UpdateSelectionTree = value;
  89721. },
  89722. enumerable: true,
  89723. configurable: true
  89724. });
  89725. /**
  89726. * Gets a string describing the action executed by the current optimization
  89727. * @return description string
  89728. */
  89729. MergeMeshesOptimization.prototype.getDescription = function () {
  89730. return "Merging similar meshes together";
  89731. };
  89732. /**
  89733. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89734. * @param scene defines the current scene where to apply this optimization
  89735. * @param optimizer defines the current optimizer
  89736. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  89737. * @returns true if everything that can be done was applied
  89738. */
  89739. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  89740. var globalPool = scene.meshes.slice(0);
  89741. var globalLength = globalPool.length;
  89742. for (var index = 0; index < globalLength; index++) {
  89743. var currentPool = new Array();
  89744. var current = globalPool[index];
  89745. // Checks
  89746. if (!this._canBeMerged(current)) {
  89747. continue;
  89748. }
  89749. currentPool.push(current);
  89750. // Find compatible meshes
  89751. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  89752. var otherMesh = globalPool[subIndex];
  89753. if (!this._canBeMerged(otherMesh)) {
  89754. continue;
  89755. }
  89756. if (otherMesh.material !== current.material) {
  89757. continue;
  89758. }
  89759. if (otherMesh.checkCollisions !== current.checkCollisions) {
  89760. continue;
  89761. }
  89762. currentPool.push(otherMesh);
  89763. globalLength--;
  89764. globalPool.splice(subIndex, 1);
  89765. subIndex--;
  89766. }
  89767. if (currentPool.length < 2) {
  89768. continue;
  89769. }
  89770. // Merge meshes
  89771. BABYLON.Mesh.MergeMeshes(currentPool);
  89772. }
  89773. if (updateSelectionTree != undefined) {
  89774. if (updateSelectionTree) {
  89775. scene.createOrUpdateSelectionOctree();
  89776. }
  89777. }
  89778. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  89779. scene.createOrUpdateSelectionOctree();
  89780. }
  89781. return true;
  89782. };
  89783. ;
  89784. MergeMeshesOptimization._UpdateSelectionTree = false;
  89785. return MergeMeshesOptimization;
  89786. }(SceneOptimization));
  89787. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  89788. /**
  89789. * Defines a list of options used by SceneOptimizer
  89790. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89791. */
  89792. var SceneOptimizerOptions = /** @class */ (function () {
  89793. /**
  89794. * Creates a new list of options used by SceneOptimizer
  89795. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  89796. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  89797. */
  89798. function SceneOptimizerOptions(
  89799. /**
  89800. * Defines the target frame rate to reach (60 by default)
  89801. */
  89802. targetFrameRate,
  89803. /**
  89804. * Defines the interval between two checkes (2000ms by default)
  89805. */
  89806. trackerDuration) {
  89807. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  89808. if (trackerDuration === void 0) { trackerDuration = 2000; }
  89809. this.targetFrameRate = targetFrameRate;
  89810. this.trackerDuration = trackerDuration;
  89811. /**
  89812. * Gets the list of optimizations to apply
  89813. */
  89814. this.optimizations = new Array();
  89815. }
  89816. /**
  89817. * Add a new optimization
  89818. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  89819. * @returns the current SceneOptimizerOptions
  89820. */
  89821. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  89822. this.optimizations.push(optimization);
  89823. return this;
  89824. };
  89825. /**
  89826. * Add a new custom optimization
  89827. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  89828. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  89829. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89830. * @returns the current SceneOptimizerOptions
  89831. */
  89832. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  89833. if (priority === void 0) { priority = 0; }
  89834. var optimization = new CustomOptimization(priority);
  89835. optimization.onApply = onApply;
  89836. optimization.onGetDescription = onGetDescription;
  89837. this.optimizations.push(optimization);
  89838. return this;
  89839. };
  89840. /**
  89841. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  89842. * @param targetFrameRate defines the target frame rate (60 by default)
  89843. * @returns a SceneOptimizerOptions object
  89844. */
  89845. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  89846. var result = new SceneOptimizerOptions(targetFrameRate);
  89847. var priority = 0;
  89848. result.addOptimization(new MergeMeshesOptimization(priority));
  89849. result.addOptimization(new ShadowsOptimization(priority));
  89850. result.addOptimization(new LensFlaresOptimization(priority));
  89851. // Next priority
  89852. priority++;
  89853. result.addOptimization(new PostProcessesOptimization(priority));
  89854. result.addOptimization(new ParticlesOptimization(priority));
  89855. // Next priority
  89856. priority++;
  89857. result.addOptimization(new TextureOptimization(priority, 1024));
  89858. return result;
  89859. };
  89860. /**
  89861. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  89862. * @param targetFrameRate defines the target frame rate (60 by default)
  89863. * @returns a SceneOptimizerOptions object
  89864. */
  89865. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  89866. var result = new SceneOptimizerOptions(targetFrameRate);
  89867. var priority = 0;
  89868. result.addOptimization(new MergeMeshesOptimization(priority));
  89869. result.addOptimization(new ShadowsOptimization(priority));
  89870. result.addOptimization(new LensFlaresOptimization(priority));
  89871. // Next priority
  89872. priority++;
  89873. result.addOptimization(new PostProcessesOptimization(priority));
  89874. result.addOptimization(new ParticlesOptimization(priority));
  89875. // Next priority
  89876. priority++;
  89877. result.addOptimization(new TextureOptimization(priority, 512));
  89878. // Next priority
  89879. priority++;
  89880. result.addOptimization(new RenderTargetsOptimization(priority));
  89881. // Next priority
  89882. priority++;
  89883. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  89884. return result;
  89885. };
  89886. /**
  89887. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  89888. * @param targetFrameRate defines the target frame rate (60 by default)
  89889. * @returns a SceneOptimizerOptions object
  89890. */
  89891. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  89892. var result = new SceneOptimizerOptions(targetFrameRate);
  89893. var priority = 0;
  89894. result.addOptimization(new MergeMeshesOptimization(priority));
  89895. result.addOptimization(new ShadowsOptimization(priority));
  89896. result.addOptimization(new LensFlaresOptimization(priority));
  89897. // Next priority
  89898. priority++;
  89899. result.addOptimization(new PostProcessesOptimization(priority));
  89900. result.addOptimization(new ParticlesOptimization(priority));
  89901. // Next priority
  89902. priority++;
  89903. result.addOptimization(new TextureOptimization(priority, 256));
  89904. // Next priority
  89905. priority++;
  89906. result.addOptimization(new RenderTargetsOptimization(priority));
  89907. // Next priority
  89908. priority++;
  89909. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  89910. return result;
  89911. };
  89912. return SceneOptimizerOptions;
  89913. }());
  89914. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  89915. /**
  89916. * Class used to run optimizations in order to reach a target frame rate
  89917. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89918. */
  89919. var SceneOptimizer = /** @class */ (function () {
  89920. /**
  89921. * Creates a new SceneOptimizer
  89922. * @param scene defines the scene to work on
  89923. * @param options defines the options to use with the SceneOptimizer
  89924. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  89925. * @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)
  89926. */
  89927. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  89928. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  89929. if (improvementMode === void 0) { improvementMode = false; }
  89930. var _this = this;
  89931. this._isRunning = false;
  89932. this._currentPriorityLevel = 0;
  89933. this._targetFrameRate = 60;
  89934. this._trackerDuration = 2000;
  89935. this._currentFrameRate = 0;
  89936. this._improvementMode = false;
  89937. /**
  89938. * Defines an observable called when the optimizer reaches the target frame rate
  89939. */
  89940. this.onSuccessObservable = new BABYLON.Observable();
  89941. /**
  89942. * Defines an observable called when the optimizer enables an optimization
  89943. */
  89944. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  89945. /**
  89946. * Defines an observable called when the optimizer is not able to reach the target frame rate
  89947. */
  89948. this.onFailureObservable = new BABYLON.Observable();
  89949. if (!options) {
  89950. this._options = new SceneOptimizerOptions();
  89951. }
  89952. else {
  89953. this._options = options;
  89954. }
  89955. if (this._options.targetFrameRate) {
  89956. this._targetFrameRate = this._options.targetFrameRate;
  89957. }
  89958. if (this._options.trackerDuration) {
  89959. this._trackerDuration = this._options.trackerDuration;
  89960. }
  89961. if (autoGeneratePriorities) {
  89962. var priority = 0;
  89963. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  89964. var optim = _a[_i];
  89965. optim.priority = priority++;
  89966. }
  89967. }
  89968. this._improvementMode = improvementMode;
  89969. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89970. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  89971. _this._sceneDisposeObserver = null;
  89972. _this.dispose();
  89973. });
  89974. }
  89975. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  89976. /**
  89977. * Gets a boolean indicating if the optimizer is in improvement mode
  89978. */
  89979. get: function () {
  89980. return this._improvementMode;
  89981. },
  89982. enumerable: true,
  89983. configurable: true
  89984. });
  89985. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  89986. /**
  89987. * Gets the current priority level (0 at start)
  89988. */
  89989. get: function () {
  89990. return this._currentPriorityLevel;
  89991. },
  89992. enumerable: true,
  89993. configurable: true
  89994. });
  89995. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  89996. /**
  89997. * Gets the current frame rate checked by the SceneOptimizer
  89998. */
  89999. get: function () {
  90000. return this._currentFrameRate;
  90001. },
  90002. enumerable: true,
  90003. configurable: true
  90004. });
  90005. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90006. /**
  90007. * Gets or sets the current target frame rate (60 by default)
  90008. */
  90009. get: function () {
  90010. return this._targetFrameRate;
  90011. },
  90012. /**
  90013. * Gets or sets the current target frame rate (60 by default)
  90014. */
  90015. set: function (value) {
  90016. this._targetFrameRate = value;
  90017. },
  90018. enumerable: true,
  90019. configurable: true
  90020. });
  90021. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90022. /**
  90023. * Gets or sets the current interval between two checks (every 2000ms by default)
  90024. */
  90025. get: function () {
  90026. return this._trackerDuration;
  90027. },
  90028. /**
  90029. * Gets or sets the current interval between two checks (every 2000ms by default)
  90030. */
  90031. set: function (value) {
  90032. this._trackerDuration = value;
  90033. },
  90034. enumerable: true,
  90035. configurable: true
  90036. });
  90037. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90038. /**
  90039. * Gets the list of active optimizations
  90040. */
  90041. get: function () {
  90042. return this._options.optimizations;
  90043. },
  90044. enumerable: true,
  90045. configurable: true
  90046. });
  90047. /**
  90048. * Stops the current optimizer
  90049. */
  90050. SceneOptimizer.prototype.stop = function () {
  90051. this._isRunning = false;
  90052. };
  90053. /**
  90054. * Reset the optimizer to initial step (current priority level = 0)
  90055. */
  90056. SceneOptimizer.prototype.reset = function () {
  90057. this._currentPriorityLevel = 0;
  90058. };
  90059. /**
  90060. * Start the optimizer. By default it will try to reach a specific framerate
  90061. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90062. */
  90063. SceneOptimizer.prototype.start = function () {
  90064. var _this = this;
  90065. if (this._isRunning) {
  90066. return;
  90067. }
  90068. this._isRunning = true;
  90069. // Let's wait for the scene to be ready before running our check
  90070. this._scene.executeWhenReady(function () {
  90071. setTimeout(function () {
  90072. _this._checkCurrentState();
  90073. }, _this._trackerDuration);
  90074. });
  90075. };
  90076. SceneOptimizer.prototype._checkCurrentState = function () {
  90077. var _this = this;
  90078. if (!this._isRunning) {
  90079. return;
  90080. }
  90081. var scene = this._scene;
  90082. var options = this._options;
  90083. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90084. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90085. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90086. this._isRunning = false;
  90087. this.onSuccessObservable.notifyObservers(this);
  90088. return;
  90089. }
  90090. // Apply current level of optimizations
  90091. var allDone = true;
  90092. var noOptimizationApplied = true;
  90093. for (var index = 0; index < options.optimizations.length; index++) {
  90094. var optimization = options.optimizations[index];
  90095. if (optimization.priority === this._currentPriorityLevel) {
  90096. noOptimizationApplied = false;
  90097. allDone = allDone && optimization.apply(scene, this);
  90098. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90099. }
  90100. }
  90101. // If no optimization was applied, this is a failure :(
  90102. if (noOptimizationApplied) {
  90103. this._isRunning = false;
  90104. this.onFailureObservable.notifyObservers(this);
  90105. return;
  90106. }
  90107. // If all optimizations were done, move to next level
  90108. if (allDone) {
  90109. this._currentPriorityLevel++;
  90110. }
  90111. // Let's the system running for a specific amount of time before checking FPS
  90112. scene.executeWhenReady(function () {
  90113. setTimeout(function () {
  90114. _this._checkCurrentState();
  90115. }, _this._trackerDuration);
  90116. });
  90117. };
  90118. /**
  90119. * Release all resources
  90120. */
  90121. SceneOptimizer.prototype.dispose = function () {
  90122. this.stop();
  90123. this.onSuccessObservable.clear();
  90124. this.onFailureObservable.clear();
  90125. this.onNewOptimizationAppliedObservable.clear();
  90126. if (this._sceneDisposeObserver) {
  90127. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90128. }
  90129. };
  90130. /**
  90131. * Helper function to create a SceneOptimizer with one single line of code
  90132. * @param scene defines the scene to work on
  90133. * @param options defines the options to use with the SceneOptimizer
  90134. * @param onSuccess defines a callback to call on success
  90135. * @param onFailure defines a callback to call on failure
  90136. * @returns the new SceneOptimizer object
  90137. */
  90138. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90139. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90140. if (onSuccess) {
  90141. optimizer.onSuccessObservable.add(function () {
  90142. onSuccess();
  90143. });
  90144. }
  90145. if (onFailure) {
  90146. optimizer.onFailureObservable.add(function () {
  90147. onFailure();
  90148. });
  90149. }
  90150. optimizer.start();
  90151. return optimizer;
  90152. };
  90153. return SceneOptimizer;
  90154. }());
  90155. BABYLON.SceneOptimizer = SceneOptimizer;
  90156. })(BABYLON || (BABYLON = {}));
  90157. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90158. var BABYLON;
  90159. (function (BABYLON) {
  90160. var OutlineRenderer = /** @class */ (function () {
  90161. function OutlineRenderer(scene) {
  90162. this.zOffset = 1;
  90163. this._scene = scene;
  90164. }
  90165. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90166. var _this = this;
  90167. if (useOverlay === void 0) { useOverlay = false; }
  90168. var scene = this._scene;
  90169. var engine = this._scene.getEngine();
  90170. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90171. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90172. return;
  90173. }
  90174. var mesh = subMesh.getRenderingMesh();
  90175. var material = subMesh.getMaterial();
  90176. if (!material || !scene.activeCamera) {
  90177. return;
  90178. }
  90179. engine.enableEffect(this._effect);
  90180. // Logarithmic depth
  90181. if (material.useLogarithmicDepth) {
  90182. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90183. }
  90184. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90185. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90186. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90187. // Bones
  90188. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90189. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90190. }
  90191. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90192. // Alpha test
  90193. if (material && material.needAlphaTesting()) {
  90194. var alphaTexture = material.getAlphaTestTexture();
  90195. if (alphaTexture) {
  90196. this._effect.setTexture("diffuseSampler", alphaTexture);
  90197. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90198. }
  90199. }
  90200. engine.setZOffset(-this.zOffset);
  90201. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90202. engine.setZOffset(0);
  90203. };
  90204. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90205. var defines = [];
  90206. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90207. var mesh = subMesh.getMesh();
  90208. var material = subMesh.getMaterial();
  90209. if (material) {
  90210. // Alpha test
  90211. if (material.needAlphaTesting()) {
  90212. defines.push("#define ALPHATEST");
  90213. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90214. attribs.push(BABYLON.VertexBuffer.UVKind);
  90215. defines.push("#define UV1");
  90216. }
  90217. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90218. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90219. defines.push("#define UV2");
  90220. }
  90221. }
  90222. //Logarithmic depth
  90223. if (material.useLogarithmicDepth) {
  90224. defines.push("#define LOGARITHMICDEPTH");
  90225. }
  90226. }
  90227. // Bones
  90228. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90229. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90230. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90231. if (mesh.numBoneInfluencers > 4) {
  90232. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90233. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90234. }
  90235. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90236. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90237. }
  90238. else {
  90239. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90240. }
  90241. // Instances
  90242. if (useInstances) {
  90243. defines.push("#define INSTANCES");
  90244. attribs.push("world0");
  90245. attribs.push("world1");
  90246. attribs.push("world2");
  90247. attribs.push("world3");
  90248. }
  90249. // Get correct effect
  90250. var join = defines.join("\n");
  90251. if (this._cachedDefines !== join) {
  90252. this._cachedDefines = join;
  90253. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90254. }
  90255. return this._effect.isReady();
  90256. };
  90257. return OutlineRenderer;
  90258. }());
  90259. BABYLON.OutlineRenderer = OutlineRenderer;
  90260. })(BABYLON || (BABYLON = {}));
  90261. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90262. var BABYLON;
  90263. (function (BABYLON) {
  90264. var FaceAdjacencies = /** @class */ (function () {
  90265. function FaceAdjacencies() {
  90266. this.edges = new Array();
  90267. this.edgesConnectedCount = 0;
  90268. }
  90269. return FaceAdjacencies;
  90270. }());
  90271. var EdgesRenderer = /** @class */ (function () {
  90272. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90273. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90274. if (epsilon === void 0) { epsilon = 0.95; }
  90275. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90276. this.edgesWidthScalerForOrthographic = 1000.0;
  90277. this.edgesWidthScalerForPerspective = 50.0;
  90278. this._linesPositions = new Array();
  90279. this._linesNormals = new Array();
  90280. this._linesIndices = new Array();
  90281. this._buffers = {};
  90282. this._checkVerticesInsteadOfIndices = false;
  90283. this._source = source;
  90284. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90285. this._epsilon = epsilon;
  90286. this._prepareRessources();
  90287. this._generateEdgesLines();
  90288. }
  90289. EdgesRenderer.prototype._prepareRessources = function () {
  90290. if (this._lineShader) {
  90291. return;
  90292. }
  90293. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90294. attributes: ["position", "normal"],
  90295. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90296. });
  90297. this._lineShader.disableDepthWrite = true;
  90298. this._lineShader.backFaceCulling = false;
  90299. };
  90300. EdgesRenderer.prototype._rebuild = function () {
  90301. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90302. if (buffer) {
  90303. buffer._rebuild();
  90304. }
  90305. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90306. if (buffer) {
  90307. buffer._rebuild();
  90308. }
  90309. var scene = this._source.getScene();
  90310. var engine = scene.getEngine();
  90311. this._ib = engine.createIndexBuffer(this._linesIndices);
  90312. };
  90313. EdgesRenderer.prototype.dispose = function () {
  90314. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90315. if (buffer) {
  90316. buffer.dispose();
  90317. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90318. }
  90319. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90320. if (buffer) {
  90321. buffer.dispose();
  90322. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90323. }
  90324. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90325. this._lineShader.dispose();
  90326. };
  90327. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90328. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90329. return 0;
  90330. }
  90331. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90332. return 1;
  90333. }
  90334. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90335. return 2;
  90336. }
  90337. return -1;
  90338. };
  90339. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90340. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90341. return 0;
  90342. }
  90343. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90344. return 1;
  90345. }
  90346. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90347. return 2;
  90348. }
  90349. return -1;
  90350. };
  90351. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90352. var needToCreateLine;
  90353. if (edge === undefined) {
  90354. needToCreateLine = true;
  90355. }
  90356. else {
  90357. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90358. needToCreateLine = dotProduct < this._epsilon;
  90359. }
  90360. if (needToCreateLine) {
  90361. var offset = this._linesPositions.length / 3;
  90362. var normal = p0.subtract(p1);
  90363. normal.normalize();
  90364. // Positions
  90365. this._linesPositions.push(p0.x);
  90366. this._linesPositions.push(p0.y);
  90367. this._linesPositions.push(p0.z);
  90368. this._linesPositions.push(p0.x);
  90369. this._linesPositions.push(p0.y);
  90370. this._linesPositions.push(p0.z);
  90371. this._linesPositions.push(p1.x);
  90372. this._linesPositions.push(p1.y);
  90373. this._linesPositions.push(p1.z);
  90374. this._linesPositions.push(p1.x);
  90375. this._linesPositions.push(p1.y);
  90376. this._linesPositions.push(p1.z);
  90377. // Normals
  90378. this._linesNormals.push(p1.x);
  90379. this._linesNormals.push(p1.y);
  90380. this._linesNormals.push(p1.z);
  90381. this._linesNormals.push(-1);
  90382. this._linesNormals.push(p1.x);
  90383. this._linesNormals.push(p1.y);
  90384. this._linesNormals.push(p1.z);
  90385. this._linesNormals.push(1);
  90386. this._linesNormals.push(p0.x);
  90387. this._linesNormals.push(p0.y);
  90388. this._linesNormals.push(p0.z);
  90389. this._linesNormals.push(-1);
  90390. this._linesNormals.push(p0.x);
  90391. this._linesNormals.push(p0.y);
  90392. this._linesNormals.push(p0.z);
  90393. this._linesNormals.push(1);
  90394. // Indices
  90395. this._linesIndices.push(offset);
  90396. this._linesIndices.push(offset + 1);
  90397. this._linesIndices.push(offset + 2);
  90398. this._linesIndices.push(offset);
  90399. this._linesIndices.push(offset + 2);
  90400. this._linesIndices.push(offset + 3);
  90401. }
  90402. };
  90403. EdgesRenderer.prototype._generateEdgesLines = function () {
  90404. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90405. var indices = this._source.getIndices();
  90406. if (!indices || !positions) {
  90407. return;
  90408. }
  90409. // First let's find adjacencies
  90410. var adjacencies = new Array();
  90411. var faceNormals = new Array();
  90412. var index;
  90413. var faceAdjacencies;
  90414. // Prepare faces
  90415. for (index = 0; index < indices.length; index += 3) {
  90416. faceAdjacencies = new FaceAdjacencies();
  90417. var p0Index = indices[index];
  90418. var p1Index = indices[index + 1];
  90419. var p2Index = indices[index + 2];
  90420. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  90421. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  90422. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  90423. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  90424. faceNormal.normalize();
  90425. faceNormals.push(faceNormal);
  90426. adjacencies.push(faceAdjacencies);
  90427. }
  90428. // Scan
  90429. for (index = 0; index < adjacencies.length; index++) {
  90430. faceAdjacencies = adjacencies[index];
  90431. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  90432. var otherFaceAdjacencies = adjacencies[otherIndex];
  90433. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  90434. break;
  90435. }
  90436. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  90437. continue;
  90438. }
  90439. var otherP0 = indices[otherIndex * 3];
  90440. var otherP1 = indices[otherIndex * 3 + 1];
  90441. var otherP2 = indices[otherIndex * 3 + 2];
  90442. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  90443. var otherEdgeIndex = 0;
  90444. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  90445. continue;
  90446. }
  90447. switch (edgeIndex) {
  90448. case 0:
  90449. if (this._checkVerticesInsteadOfIndices) {
  90450. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90451. }
  90452. else {
  90453. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  90454. }
  90455. break;
  90456. case 1:
  90457. if (this._checkVerticesInsteadOfIndices) {
  90458. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90459. }
  90460. else {
  90461. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  90462. }
  90463. break;
  90464. case 2:
  90465. if (this._checkVerticesInsteadOfIndices) {
  90466. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90467. }
  90468. else {
  90469. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  90470. }
  90471. break;
  90472. }
  90473. if (otherEdgeIndex === -1) {
  90474. continue;
  90475. }
  90476. faceAdjacencies.edges[edgeIndex] = otherIndex;
  90477. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  90478. faceAdjacencies.edgesConnectedCount++;
  90479. otherFaceAdjacencies.edgesConnectedCount++;
  90480. if (faceAdjacencies.edgesConnectedCount === 3) {
  90481. break;
  90482. }
  90483. }
  90484. }
  90485. }
  90486. // Create lines
  90487. for (index = 0; index < adjacencies.length; index++) {
  90488. // 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
  90489. var current = adjacencies[index];
  90490. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  90491. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  90492. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  90493. }
  90494. // Merge into a single mesh
  90495. var engine = this._source.getScene().getEngine();
  90496. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  90497. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  90498. this._ib = engine.createIndexBuffer(this._linesIndices);
  90499. this._indicesCount = this._linesIndices.length;
  90500. };
  90501. EdgesRenderer.prototype.render = function () {
  90502. var scene = this._source.getScene();
  90503. if (!this._lineShader.isReady() || !scene.activeCamera) {
  90504. return;
  90505. }
  90506. var engine = scene.getEngine();
  90507. this._lineShader._preBind();
  90508. // VBOs
  90509. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  90510. scene.resetCachedMaterial();
  90511. this._lineShader.setColor4("color", this._source.edgesColor);
  90512. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  90513. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  90514. }
  90515. else {
  90516. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  90517. }
  90518. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  90519. this._lineShader.bind(this._source.getWorldMatrix());
  90520. // Draw order
  90521. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  90522. this._lineShader.unbind();
  90523. engine.setDepthWrite(true);
  90524. };
  90525. return EdgesRenderer;
  90526. }());
  90527. BABYLON.EdgesRenderer = EdgesRenderer;
  90528. })(BABYLON || (BABYLON = {}));
  90529. //# sourceMappingURL=babylon.edgesRenderer.js.map
  90530. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90531. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90532. s = arguments[i];
  90533. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90534. t[p] = s[p];
  90535. }
  90536. return t;
  90537. };
  90538. var BABYLON;
  90539. (function (BABYLON) {
  90540. /**
  90541. * The effect layer Helps adding post process effect blended with the main pass.
  90542. *
  90543. * This can be for instance use to generate glow or higlight effects on the scene.
  90544. *
  90545. * The effect layer class can not be used directly and is intented to inherited from to be
  90546. * customized per effects.
  90547. */
  90548. var EffectLayer = /** @class */ (function () {
  90549. /**
  90550. * Instantiates a new effect Layer and references it in the scene.
  90551. * @param name The name of the layer
  90552. * @param scene The scene to use the layer in
  90553. */
  90554. function EffectLayer(
  90555. /** The Friendly of the effect in the scene */
  90556. name, scene) {
  90557. this._vertexBuffers = {};
  90558. this._maxSize = 0;
  90559. this._mainTextureDesiredSize = { width: 0, height: 0 };
  90560. this._shouldRender = true;
  90561. this._postProcesses = [];
  90562. this._textures = [];
  90563. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  90564. /**
  90565. * The clear color of the texture used to generate the glow map.
  90566. */
  90567. this.neutralColor = new BABYLON.Color4();
  90568. /**
  90569. * Specifies wether the highlight layer is enabled or not.
  90570. */
  90571. this.isEnabled = true;
  90572. /**
  90573. * An event triggered when the effect layer has been disposed.
  90574. */
  90575. this.onDisposeObservable = new BABYLON.Observable();
  90576. /**
  90577. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  90578. */
  90579. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  90580. /**
  90581. * An event triggered when the generated texture is being merged in the scene.
  90582. */
  90583. this.onBeforeComposeObservable = new BABYLON.Observable();
  90584. /**
  90585. * An event triggered when the generated texture has been merged in the scene.
  90586. */
  90587. this.onAfterComposeObservable = new BABYLON.Observable();
  90588. /**
  90589. * An event triggered when the efffect layer changes its size.
  90590. */
  90591. this.onSizeChangedObservable = new BABYLON.Observable();
  90592. this.name = name;
  90593. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90594. this._engine = scene.getEngine();
  90595. this._maxSize = this._engine.getCaps().maxTextureSize;
  90596. this._scene.effectLayers.push(this);
  90597. // Generate Buffers
  90598. this._generateIndexBuffer();
  90599. this._genrateVertexBuffer();
  90600. }
  90601. Object.defineProperty(EffectLayer.prototype, "camera", {
  90602. /**
  90603. * Gets the camera attached to the layer.
  90604. */
  90605. get: function () {
  90606. return this._effectLayerOptions.camera;
  90607. },
  90608. enumerable: true,
  90609. configurable: true
  90610. });
  90611. /**
  90612. * Initializes the effect layer with the required options.
  90613. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  90614. */
  90615. EffectLayer.prototype._init = function (options) {
  90616. // Adapt options
  90617. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90618. this._setMainTextureSize();
  90619. this._createMainTexture();
  90620. this._createTextureAndPostProcesses();
  90621. this._mergeEffect = this._createMergeEffect();
  90622. };
  90623. /**
  90624. * Generates the index buffer of the full screen quad blending to the main canvas.
  90625. */
  90626. EffectLayer.prototype._generateIndexBuffer = function () {
  90627. // Indices
  90628. var indices = [];
  90629. indices.push(0);
  90630. indices.push(1);
  90631. indices.push(2);
  90632. indices.push(0);
  90633. indices.push(2);
  90634. indices.push(3);
  90635. this._indexBuffer = this._engine.createIndexBuffer(indices);
  90636. };
  90637. /**
  90638. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  90639. */
  90640. EffectLayer.prototype._genrateVertexBuffer = function () {
  90641. // VBO
  90642. var vertices = [];
  90643. vertices.push(1, 1);
  90644. vertices.push(-1, 1);
  90645. vertices.push(-1, -1);
  90646. vertices.push(1, -1);
  90647. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90648. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  90649. };
  90650. /**
  90651. * Sets the main texture desired size which is the closest power of two
  90652. * of the engine canvas size.
  90653. */
  90654. EffectLayer.prototype._setMainTextureSize = function () {
  90655. if (this._effectLayerOptions.mainTextureFixedSize) {
  90656. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  90657. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  90658. }
  90659. else {
  90660. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  90661. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  90662. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  90663. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  90664. }
  90665. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  90666. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  90667. };
  90668. /**
  90669. * Creates the main texture for the effect layer.
  90670. */
  90671. EffectLayer.prototype._createMainTexture = function () {
  90672. var _this = this;
  90673. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  90674. width: this._mainTextureDesiredSize.width,
  90675. height: this._mainTextureDesiredSize.height
  90676. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90677. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  90678. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90679. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90680. this._mainTexture.anisotropicFilteringLevel = 1;
  90681. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90682. this._mainTexture.renderParticles = false;
  90683. this._mainTexture.renderList = null;
  90684. this._mainTexture.ignoreCameraViewport = true;
  90685. // Custom render function
  90686. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90687. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  90688. var index;
  90689. var engine = _this._scene.getEngine();
  90690. if (depthOnlySubMeshes.length) {
  90691. engine.setColorWrite(false);
  90692. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90693. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  90694. }
  90695. engine.setColorWrite(true);
  90696. }
  90697. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90698. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  90699. }
  90700. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90701. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  90702. }
  90703. for (index = 0; index < transparentSubMeshes.length; index++) {
  90704. _this._renderSubMesh(transparentSubMeshes.data[index]);
  90705. }
  90706. };
  90707. this._mainTexture.onClearObservable.add(function (engine) {
  90708. engine.clear(_this.neutralColor, true, true, true);
  90709. });
  90710. };
  90711. /**
  90712. * Checks for the readiness of the element composing the layer.
  90713. * @param subMesh the mesh to check for
  90714. * @param useInstances specify wether or not to use instances to render the mesh
  90715. * @param emissiveTexture the associated emissive texture used to generate the glow
  90716. * @return true if ready otherwise, false
  90717. */
  90718. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  90719. var material = subMesh.getMaterial();
  90720. if (!material) {
  90721. return false;
  90722. }
  90723. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  90724. return false;
  90725. }
  90726. var defines = [];
  90727. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90728. var mesh = subMesh.getMesh();
  90729. var uv1 = false;
  90730. var uv2 = false;
  90731. // Alpha test
  90732. if (material && material.needAlphaTesting()) {
  90733. var alphaTexture = material.getAlphaTestTexture();
  90734. if (alphaTexture) {
  90735. defines.push("#define ALPHATEST");
  90736. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90737. alphaTexture.coordinatesIndex === 1) {
  90738. defines.push("#define DIFFUSEUV2");
  90739. uv2 = true;
  90740. }
  90741. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90742. defines.push("#define DIFFUSEUV1");
  90743. uv1 = true;
  90744. }
  90745. }
  90746. }
  90747. // Emissive
  90748. if (emissiveTexture) {
  90749. defines.push("#define EMISSIVE");
  90750. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90751. emissiveTexture.coordinatesIndex === 1) {
  90752. defines.push("#define EMISSIVEUV2");
  90753. uv2 = true;
  90754. }
  90755. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90756. defines.push("#define EMISSIVEUV1");
  90757. uv1 = true;
  90758. }
  90759. }
  90760. if (uv1) {
  90761. attribs.push(BABYLON.VertexBuffer.UVKind);
  90762. defines.push("#define UV1");
  90763. }
  90764. if (uv2) {
  90765. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90766. defines.push("#define UV2");
  90767. }
  90768. // Bones
  90769. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90770. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90771. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90772. if (mesh.numBoneInfluencers > 4) {
  90773. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90774. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90775. }
  90776. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90777. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90778. }
  90779. else {
  90780. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90781. }
  90782. // Morph targets
  90783. var manager = mesh.morphTargetManager;
  90784. var morphInfluencers = 0;
  90785. if (manager) {
  90786. if (manager.numInfluencers > 0) {
  90787. defines.push("#define MORPHTARGETS");
  90788. morphInfluencers = manager.numInfluencers;
  90789. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  90790. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  90791. }
  90792. }
  90793. // Instances
  90794. if (useInstances) {
  90795. defines.push("#define INSTANCES");
  90796. attribs.push("world0");
  90797. attribs.push("world1");
  90798. attribs.push("world2");
  90799. attribs.push("world3");
  90800. }
  90801. // Get correct effect
  90802. var join = defines.join("\n");
  90803. if (this._cachedDefines !== join) {
  90804. this._cachedDefines = join;
  90805. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  90806. }
  90807. return this._effectLayerMapGenerationEffect.isReady();
  90808. };
  90809. /**
  90810. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  90811. */
  90812. EffectLayer.prototype.render = function () {
  90813. var currentEffect = this._mergeEffect;
  90814. // Check
  90815. if (!currentEffect.isReady())
  90816. return;
  90817. for (var i = 0; i < this._postProcesses.length; i++) {
  90818. if (!this._postProcesses[i].isReady()) {
  90819. return;
  90820. }
  90821. }
  90822. var engine = this._scene.getEngine();
  90823. this.onBeforeComposeObservable.notifyObservers(this);
  90824. // Render
  90825. engine.enableEffect(currentEffect);
  90826. engine.setState(false);
  90827. // VBOs
  90828. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  90829. // Cache
  90830. var previousAlphaMode = engine.getAlphaMode();
  90831. // Go Blend.
  90832. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  90833. // Blends the map on the main canvas.
  90834. this._internalRender(currentEffect);
  90835. // Restore Alpha
  90836. engine.setAlphaMode(previousAlphaMode);
  90837. this.onAfterComposeObservable.notifyObservers(this);
  90838. // Handle size changes.
  90839. var size = this._mainTexture.getSize();
  90840. this._setMainTextureSize();
  90841. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  90842. // Recreate RTT and post processes on size change.
  90843. this.onSizeChangedObservable.notifyObservers(this);
  90844. this._disposeTextureAndPostProcesses();
  90845. this._createMainTexture();
  90846. this._createTextureAndPostProcesses();
  90847. }
  90848. };
  90849. /**
  90850. * Determine if a given mesh will be used in the current effect.
  90851. * @param mesh mesh to test
  90852. * @returns true if the mesh will be used
  90853. */
  90854. EffectLayer.prototype.hasMesh = function (mesh) {
  90855. return true;
  90856. };
  90857. /**
  90858. * Returns true if the layer contains information to display, otherwise false.
  90859. * @returns true if the glow layer should be rendered
  90860. */
  90861. EffectLayer.prototype.shouldRender = function () {
  90862. return this.isEnabled && this._shouldRender;
  90863. };
  90864. /**
  90865. * Returns true if the mesh should render, otherwise false.
  90866. * @param mesh The mesh to render
  90867. * @returns true if it should render otherwise false
  90868. */
  90869. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  90870. return true;
  90871. };
  90872. /**
  90873. * Returns true if the mesh should render, otherwise false.
  90874. * @param mesh The mesh to render
  90875. * @returns true if it should render otherwise false
  90876. */
  90877. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  90878. return true;
  90879. };
  90880. /**
  90881. * Renders the submesh passed in parameter to the generation map.
  90882. */
  90883. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  90884. var _this = this;
  90885. if (!this.shouldRender()) {
  90886. return;
  90887. }
  90888. var material = subMesh.getMaterial();
  90889. var mesh = subMesh.getRenderingMesh();
  90890. var scene = this._scene;
  90891. var engine = scene.getEngine();
  90892. if (!material) {
  90893. return;
  90894. }
  90895. // Do not block in blend mode.
  90896. if (material.needAlphaBlendingForMesh(mesh)) {
  90897. return;
  90898. }
  90899. // Culling
  90900. engine.setState(material.backFaceCulling);
  90901. // Managing instances
  90902. var batch = mesh._getInstancesRenderList(subMesh._id);
  90903. if (batch.mustReturn) {
  90904. return;
  90905. }
  90906. // Early Exit per mesh
  90907. if (!this._shouldRenderMesh(mesh)) {
  90908. return;
  90909. }
  90910. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90911. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  90912. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  90913. engine.enableEffect(this._effectLayerMapGenerationEffect);
  90914. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  90915. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  90916. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  90917. // Alpha test
  90918. if (material && material.needAlphaTesting()) {
  90919. var alphaTexture = material.getAlphaTestTexture();
  90920. if (alphaTexture) {
  90921. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  90922. var textureMatrix = alphaTexture.getTextureMatrix();
  90923. if (textureMatrix) {
  90924. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  90925. }
  90926. }
  90927. }
  90928. // Glow emissive only
  90929. if (this._emissiveTextureAndColor.texture) {
  90930. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  90931. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  90932. }
  90933. // Bones
  90934. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90935. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90936. }
  90937. // Morph targets
  90938. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  90939. // Draw
  90940. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  90941. }
  90942. else {
  90943. // Need to reset refresh rate of the shadowMap
  90944. this._mainTexture.resetRefreshCounter();
  90945. }
  90946. };
  90947. /**
  90948. * Rebuild the required buffers.
  90949. * @ignore Internal use only.
  90950. */
  90951. EffectLayer.prototype._rebuild = function () {
  90952. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90953. if (vb) {
  90954. vb._rebuild();
  90955. }
  90956. this._generateIndexBuffer();
  90957. };
  90958. /**
  90959. * Dispose only the render target textures and post process.
  90960. */
  90961. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  90962. this._mainTexture.dispose();
  90963. for (var i = 0; i < this._postProcesses.length; i++) {
  90964. if (this._postProcesses[i]) {
  90965. this._postProcesses[i].dispose();
  90966. }
  90967. }
  90968. this._postProcesses = [];
  90969. for (var i = 0; i < this._textures.length; i++) {
  90970. if (this._textures[i]) {
  90971. this._textures[i].dispose();
  90972. }
  90973. }
  90974. this._textures = [];
  90975. };
  90976. /**
  90977. * Dispose the highlight layer and free resources.
  90978. */
  90979. EffectLayer.prototype.dispose = function () {
  90980. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90981. if (vertexBuffer) {
  90982. vertexBuffer.dispose();
  90983. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90984. }
  90985. if (this._indexBuffer) {
  90986. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90987. this._indexBuffer = null;
  90988. }
  90989. // Clean textures and post processes
  90990. this._disposeTextureAndPostProcesses();
  90991. // Remove from scene
  90992. var index = this._scene.effectLayers.indexOf(this, 0);
  90993. if (index > -1) {
  90994. this._scene.effectLayers.splice(index, 1);
  90995. }
  90996. // Callback
  90997. this.onDisposeObservable.notifyObservers(this);
  90998. this.onDisposeObservable.clear();
  90999. this.onBeforeRenderMainTextureObservable.clear();
  91000. this.onBeforeComposeObservable.clear();
  91001. this.onAfterComposeObservable.clear();
  91002. this.onSizeChangedObservable.clear();
  91003. };
  91004. /**
  91005. * Gets the class name of the effect layer
  91006. * @returns the string with the class name of the effect layer
  91007. */
  91008. EffectLayer.prototype.getClassName = function () {
  91009. return "EffectLayer";
  91010. };
  91011. /**
  91012. * Creates an effect layer from parsed effect layer data
  91013. * @param parsedEffectLayer defines effect layer data
  91014. * @param scene defines the current scene
  91015. * @param rootUrl defines the root URL containing the effect layer information
  91016. * @returns a parsed effect Layer
  91017. */
  91018. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91019. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91020. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91021. };
  91022. __decorate([
  91023. BABYLON.serialize()
  91024. ], EffectLayer.prototype, "name", void 0);
  91025. __decorate([
  91026. BABYLON.serializeAsColor4()
  91027. ], EffectLayer.prototype, "neutralColor", void 0);
  91028. __decorate([
  91029. BABYLON.serialize()
  91030. ], EffectLayer.prototype, "isEnabled", void 0);
  91031. __decorate([
  91032. BABYLON.serializeAsCameraReference()
  91033. ], EffectLayer.prototype, "camera", null);
  91034. return EffectLayer;
  91035. }());
  91036. BABYLON.EffectLayer = EffectLayer;
  91037. })(BABYLON || (BABYLON = {}));
  91038. //# sourceMappingURL=babylon.effectLayer.js.map
  91039. var BABYLON;
  91040. (function (BABYLON) {
  91041. /**
  91042. * Special Glow Blur post process only blurring the alpha channel
  91043. * It enforces keeping the most luminous color in the color channel.
  91044. */
  91045. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91046. __extends(GlowBlurPostProcess, _super);
  91047. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91048. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91049. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91050. _this.direction = direction;
  91051. _this.kernel = kernel;
  91052. _this.onApplyObservable.add(function (effect) {
  91053. effect.setFloat2("screenSize", _this.width, _this.height);
  91054. effect.setVector2("direction", _this.direction);
  91055. effect.setFloat("blurWidth", _this.kernel);
  91056. });
  91057. return _this;
  91058. }
  91059. return GlowBlurPostProcess;
  91060. }(BABYLON.PostProcess));
  91061. /**
  91062. * The highlight layer Helps adding a glow effect around a mesh.
  91063. *
  91064. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91065. * glowy meshes to your scene.
  91066. *
  91067. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91068. */
  91069. var HighlightLayer = /** @class */ (function (_super) {
  91070. __extends(HighlightLayer, _super);
  91071. /**
  91072. * Instantiates a new highlight Layer and references it to the scene..
  91073. * @param name The name of the layer
  91074. * @param scene The scene to use the layer in
  91075. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91076. */
  91077. function HighlightLayer(name, scene, options) {
  91078. var _this = _super.call(this, name, scene) || this;
  91079. _this.name = name;
  91080. /**
  91081. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91082. */
  91083. _this.innerGlow = true;
  91084. /**
  91085. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91086. */
  91087. _this.outerGlow = true;
  91088. /**
  91089. * An event triggered when the highlight layer is being blurred.
  91090. */
  91091. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91092. /**
  91093. * An event triggered when the highlight layer has been blurred.
  91094. */
  91095. _this.onAfterBlurObservable = new BABYLON.Observable();
  91096. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91097. _this._meshes = {};
  91098. _this._excludedMeshes = {};
  91099. _this.neutralColor = HighlightLayer.NeutralColor;
  91100. // Warn on stencil
  91101. if (!_this._engine.isStencilEnable) {
  91102. 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 }");
  91103. }
  91104. // Adapt options
  91105. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91106. // Initialize the layer
  91107. _this._init({
  91108. alphaBlendingMode: _this._options.alphaBlendingMode,
  91109. camera: _this._options.camera,
  91110. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91111. mainTextureRatio: _this._options.mainTextureRatio
  91112. });
  91113. // Do not render as long as no meshes have been added
  91114. _this._shouldRender = false;
  91115. return _this;
  91116. }
  91117. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91118. /**
  91119. * Gets the horizontal size of the blur.
  91120. */
  91121. get: function () {
  91122. return this._horizontalBlurPostprocess.kernel;
  91123. },
  91124. /**
  91125. * Specifies the horizontal size of the blur.
  91126. */
  91127. set: function (value) {
  91128. this._horizontalBlurPostprocess.kernel = value;
  91129. },
  91130. enumerable: true,
  91131. configurable: true
  91132. });
  91133. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91134. /**
  91135. * Gets the vertical size of the blur.
  91136. */
  91137. get: function () {
  91138. return this._verticalBlurPostprocess.kernel;
  91139. },
  91140. /**
  91141. * Specifies the vertical size of the blur.
  91142. */
  91143. set: function (value) {
  91144. this._verticalBlurPostprocess.kernel = value;
  91145. },
  91146. enumerable: true,
  91147. configurable: true
  91148. });
  91149. /**
  91150. * Get the effect name of the layer.
  91151. * @return The effect name
  91152. */
  91153. HighlightLayer.prototype.getEffectName = function () {
  91154. return HighlightLayer.EffectName;
  91155. };
  91156. /**
  91157. * Create the merge effect. This is the shader use to blit the information back
  91158. * to the main canvas at the end of the scene rendering.
  91159. */
  91160. HighlightLayer.prototype._createMergeEffect = function () {
  91161. // Effect
  91162. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91163. };
  91164. /**
  91165. * Creates the render target textures and post processes used in the highlight layer.
  91166. */
  91167. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91168. var _this = this;
  91169. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91170. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91171. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91172. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91173. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91174. width: blurTextureWidth,
  91175. height: blurTextureHeight
  91176. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91177. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91178. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91179. this._blurTexture.anisotropicFilteringLevel = 16;
  91180. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91181. this._blurTexture.renderParticles = false;
  91182. this._blurTexture.ignoreCameraViewport = true;
  91183. this._textures = [this._blurTexture];
  91184. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91185. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91186. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91187. effect.setTexture("textureSampler", _this._mainTexture);
  91188. });
  91189. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91190. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91191. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91192. });
  91193. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91194. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91195. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91196. });
  91197. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91198. }
  91199. else {
  91200. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91201. width: blurTextureWidth,
  91202. height: blurTextureHeight
  91203. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91204. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91205. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91206. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91207. effect.setTexture("textureSampler", _this._mainTexture);
  91208. });
  91209. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91210. width: blurTextureWidth,
  91211. height: blurTextureHeight
  91212. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91213. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91214. }
  91215. this._mainTexture.onAfterUnbindObservable.add(function () {
  91216. _this.onBeforeBlurObservable.notifyObservers(_this);
  91217. var internalTexture = _this._blurTexture.getInternalTexture();
  91218. if (internalTexture) {
  91219. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91220. }
  91221. _this.onAfterBlurObservable.notifyObservers(_this);
  91222. });
  91223. // Prevent autoClear.
  91224. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91225. };
  91226. /**
  91227. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91228. */
  91229. HighlightLayer.prototype.needStencil = function () {
  91230. return true;
  91231. };
  91232. /**
  91233. * Checks for the readiness of the element composing the layer.
  91234. * @param subMesh the mesh to check for
  91235. * @param useInstances specify wether or not to use instances to render the mesh
  91236. * @param emissiveTexture the associated emissive texture used to generate the glow
  91237. * @return true if ready otherwise, false
  91238. */
  91239. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91240. var material = subMesh.getMaterial();
  91241. var mesh = subMesh.getRenderingMesh();
  91242. if (!material || !mesh || !this._meshes) {
  91243. return false;
  91244. }
  91245. var emissiveTexture = null;
  91246. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91247. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91248. emissiveTexture = material.emissiveTexture;
  91249. }
  91250. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91251. };
  91252. /**
  91253. * Implementation specific of rendering the generating effect on the main canvas.
  91254. * @param effect The effect used to render through
  91255. */
  91256. HighlightLayer.prototype._internalRender = function (effect) {
  91257. // Texture
  91258. effect.setTexture("textureSampler", this._blurTexture);
  91259. // Cache
  91260. var engine = this._engine;
  91261. var previousStencilBuffer = engine.getStencilBuffer();
  91262. var previousStencilFunction = engine.getStencilFunction();
  91263. var previousStencilMask = engine.getStencilMask();
  91264. var previousStencilOperationPass = engine.getStencilOperationPass();
  91265. var previousStencilOperationFail = engine.getStencilOperationFail();
  91266. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91267. var previousStencilReference = engine.getStencilFunctionReference();
  91268. // Stencil operations
  91269. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91270. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91271. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91272. // Draw order
  91273. engine.setStencilMask(0x00);
  91274. engine.setStencilBuffer(true);
  91275. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91276. // 2 passes inner outer
  91277. if (this.outerGlow) {
  91278. effect.setFloat("offset", 0);
  91279. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91280. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91281. }
  91282. if (this.innerGlow) {
  91283. effect.setFloat("offset", 1);
  91284. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91285. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91286. }
  91287. // Restore Cache
  91288. engine.setStencilFunction(previousStencilFunction);
  91289. engine.setStencilMask(previousStencilMask);
  91290. engine.setStencilBuffer(previousStencilBuffer);
  91291. engine.setStencilOperationPass(previousStencilOperationPass);
  91292. engine.setStencilOperationFail(previousStencilOperationFail);
  91293. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91294. engine.setStencilFunctionReference(previousStencilReference);
  91295. };
  91296. /**
  91297. * Returns true if the layer contains information to display, otherwise false.
  91298. */
  91299. HighlightLayer.prototype.shouldRender = function () {
  91300. if (_super.prototype.shouldRender.call(this)) {
  91301. return this._meshes ? true : false;
  91302. }
  91303. return false;
  91304. };
  91305. /**
  91306. * Returns true if the mesh should render, otherwise false.
  91307. * @param mesh The mesh to render
  91308. * @returns true if it should render otherwise false
  91309. */
  91310. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91311. // Excluded Mesh
  91312. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91313. return false;
  91314. }
  91315. ;
  91316. return true;
  91317. };
  91318. /**
  91319. * Sets the required values for both the emissive texture and and the main color.
  91320. */
  91321. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91322. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91323. if (highlightLayerMesh) {
  91324. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91325. }
  91326. else {
  91327. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91328. }
  91329. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91330. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91331. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91332. }
  91333. else {
  91334. this._emissiveTextureAndColor.texture = null;
  91335. }
  91336. };
  91337. /**
  91338. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91339. * @param mesh The mesh to exclude from the highlight layer
  91340. */
  91341. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91342. if (!this._excludedMeshes) {
  91343. return;
  91344. }
  91345. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91346. if (!meshExcluded) {
  91347. this._excludedMeshes[mesh.uniqueId] = {
  91348. mesh: mesh,
  91349. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91350. mesh.getEngine().setStencilBuffer(false);
  91351. }),
  91352. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91353. mesh.getEngine().setStencilBuffer(true);
  91354. }),
  91355. };
  91356. }
  91357. };
  91358. /**
  91359. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91360. * @param mesh The mesh to highlight
  91361. */
  91362. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91363. if (!this._excludedMeshes) {
  91364. return;
  91365. }
  91366. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91367. if (meshExcluded) {
  91368. if (meshExcluded.beforeRender) {
  91369. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91370. }
  91371. if (meshExcluded.afterRender) {
  91372. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91373. }
  91374. }
  91375. this._excludedMeshes[mesh.uniqueId] = null;
  91376. };
  91377. /**
  91378. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91379. * @param mesh mesh to test
  91380. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91381. */
  91382. HighlightLayer.prototype.hasMesh = function (mesh) {
  91383. if (!this._meshes) {
  91384. return false;
  91385. }
  91386. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91387. };
  91388. /**
  91389. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91390. * @param mesh The mesh to highlight
  91391. * @param color The color of the highlight
  91392. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91393. */
  91394. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91395. var _this = this;
  91396. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91397. if (!this._meshes) {
  91398. return;
  91399. }
  91400. var meshHighlight = this._meshes[mesh.uniqueId];
  91401. if (meshHighlight) {
  91402. meshHighlight.color = color;
  91403. }
  91404. else {
  91405. this._meshes[mesh.uniqueId] = {
  91406. mesh: mesh,
  91407. color: color,
  91408. // Lambda required for capture due to Observable this context
  91409. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  91410. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  91411. _this._defaultStencilReference(mesh);
  91412. }
  91413. else {
  91414. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  91415. }
  91416. }),
  91417. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  91418. glowEmissiveOnly: glowEmissiveOnly
  91419. };
  91420. }
  91421. this._shouldRender = true;
  91422. };
  91423. /**
  91424. * Remove a mesh from the highlight layer in order to make it stop glowing.
  91425. * @param mesh The mesh to highlight
  91426. */
  91427. HighlightLayer.prototype.removeMesh = function (mesh) {
  91428. if (!this._meshes) {
  91429. return;
  91430. }
  91431. var meshHighlight = this._meshes[mesh.uniqueId];
  91432. if (meshHighlight) {
  91433. if (meshHighlight.observerHighlight) {
  91434. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91435. }
  91436. if (meshHighlight.observerDefault) {
  91437. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91438. }
  91439. delete this._meshes[mesh.uniqueId];
  91440. }
  91441. this._shouldRender = false;
  91442. for (var meshHighlightToCheck in this._meshes) {
  91443. if (this._meshes[meshHighlightToCheck]) {
  91444. this._shouldRender = true;
  91445. break;
  91446. }
  91447. }
  91448. };
  91449. /**
  91450. * Force the stencil to the normal expected value for none glowing parts
  91451. */
  91452. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  91453. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  91454. };
  91455. /**
  91456. * Free any resources and references associated to a mesh.
  91457. * Internal use
  91458. * @param mesh The mesh to free.
  91459. */
  91460. HighlightLayer.prototype._disposeMesh = function (mesh) {
  91461. this.removeMesh(mesh);
  91462. this.removeExcludedMesh(mesh);
  91463. };
  91464. /**
  91465. * Dispose the highlight layer and free resources.
  91466. */
  91467. HighlightLayer.prototype.dispose = function () {
  91468. if (this._meshes) {
  91469. // Clean mesh references
  91470. for (var id in this._meshes) {
  91471. var meshHighlight = this._meshes[id];
  91472. if (meshHighlight && meshHighlight.mesh) {
  91473. if (meshHighlight.observerHighlight) {
  91474. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91475. }
  91476. if (meshHighlight.observerDefault) {
  91477. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91478. }
  91479. }
  91480. }
  91481. this._meshes = null;
  91482. }
  91483. if (this._excludedMeshes) {
  91484. for (var id in this._excludedMeshes) {
  91485. var meshHighlight = this._excludedMeshes[id];
  91486. if (meshHighlight) {
  91487. if (meshHighlight.beforeRender) {
  91488. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  91489. }
  91490. if (meshHighlight.afterRender) {
  91491. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  91492. }
  91493. }
  91494. }
  91495. this._excludedMeshes = null;
  91496. }
  91497. _super.prototype.dispose.call(this);
  91498. };
  91499. /**
  91500. * Gets the class name of the effect layer
  91501. * @returns the string with the class name of the effect layer
  91502. */
  91503. HighlightLayer.prototype.getClassName = function () {
  91504. return "HighlightLayer";
  91505. };
  91506. /**
  91507. * Serializes this Highlight layer
  91508. * @returns a serialized Highlight layer object
  91509. */
  91510. HighlightLayer.prototype.serialize = function () {
  91511. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91512. serializationObject.customType = "BABYLON.HighlightLayer";
  91513. // Highlighted meshes
  91514. serializationObject.meshes = [];
  91515. if (this._meshes) {
  91516. for (var m in this._meshes) {
  91517. var mesh = this._meshes[m];
  91518. if (mesh) {
  91519. serializationObject.meshes.push({
  91520. glowEmissiveOnly: mesh.glowEmissiveOnly,
  91521. color: mesh.color.asArray(),
  91522. meshId: mesh.mesh.id
  91523. });
  91524. }
  91525. }
  91526. }
  91527. // Excluded meshes
  91528. serializationObject.excludedMeshes = [];
  91529. if (this._excludedMeshes) {
  91530. for (var e in this._excludedMeshes) {
  91531. var excludedMesh = this._excludedMeshes[e];
  91532. if (excludedMesh) {
  91533. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  91534. }
  91535. }
  91536. }
  91537. return serializationObject;
  91538. };
  91539. /**
  91540. * Creates a Highlight layer from parsed Highlight layer data
  91541. * @param parsedHightlightLayer defines the Highlight layer data
  91542. * @param scene defines the current scene
  91543. * @param rootUrl defines the root URL containing the Highlight layer information
  91544. * @returns a parsed Highlight layer
  91545. */
  91546. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  91547. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  91548. var index;
  91549. // Excluded meshes
  91550. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  91551. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  91552. if (mesh) {
  91553. hl.addExcludedMesh(mesh);
  91554. }
  91555. }
  91556. // Included meshes
  91557. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  91558. var highlightedMesh = parsedHightlightLayer.meshes[index];
  91559. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  91560. if (mesh) {
  91561. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  91562. }
  91563. }
  91564. return hl;
  91565. };
  91566. /**
  91567. * Effect Name of the highlight layer.
  91568. */
  91569. HighlightLayer.EffectName = "HighlightLayer";
  91570. /**
  91571. * The neutral color used during the preparation of the glow effect.
  91572. * This is black by default as the blend operation is a blend operation.
  91573. */
  91574. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  91575. /**
  91576. * Stencil value used for glowing meshes.
  91577. */
  91578. HighlightLayer.GlowingMeshStencilReference = 0x02;
  91579. /**
  91580. * Stencil value used for the other meshes in the scene.
  91581. */
  91582. HighlightLayer.NormalMeshStencilReference = 0x01;
  91583. __decorate([
  91584. BABYLON.serialize()
  91585. ], HighlightLayer.prototype, "innerGlow", void 0);
  91586. __decorate([
  91587. BABYLON.serialize()
  91588. ], HighlightLayer.prototype, "outerGlow", void 0);
  91589. __decorate([
  91590. BABYLON.serialize()
  91591. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  91592. __decorate([
  91593. BABYLON.serialize()
  91594. ], HighlightLayer.prototype, "blurVerticalSize", null);
  91595. __decorate([
  91596. BABYLON.serialize("options")
  91597. ], HighlightLayer.prototype, "_options", void 0);
  91598. return HighlightLayer;
  91599. }(BABYLON.EffectLayer));
  91600. BABYLON.HighlightLayer = HighlightLayer;
  91601. })(BABYLON || (BABYLON = {}));
  91602. //# sourceMappingURL=babylon.highlightLayer.js.map
  91603. var BABYLON;
  91604. (function (BABYLON) {
  91605. /**
  91606. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  91607. *
  91608. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91609. * glowy meshes to your scene.
  91610. *
  91611. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  91612. */
  91613. var GlowLayer = /** @class */ (function (_super) {
  91614. __extends(GlowLayer, _super);
  91615. /**
  91616. * Instantiates a new glow Layer and references it to the scene.
  91617. * @param name The name of the layer
  91618. * @param scene The scene to use the layer in
  91619. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  91620. */
  91621. function GlowLayer(name, scene, options) {
  91622. var _this = _super.call(this, name, scene) || this;
  91623. _this._intensity = 1.0;
  91624. _this._includedOnlyMeshes = [];
  91625. _this._excludedMeshes = [];
  91626. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  91627. // Adapt options
  91628. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  91629. // Initialize the layer
  91630. _this._init({
  91631. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  91632. camera: _this._options.camera,
  91633. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91634. mainTextureRatio: _this._options.mainTextureRatio
  91635. });
  91636. return _this;
  91637. }
  91638. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  91639. /**
  91640. * Gets the kernel size of the blur.
  91641. */
  91642. get: function () {
  91643. return this._horizontalBlurPostprocess1.kernel;
  91644. },
  91645. /**
  91646. * Sets the kernel size of the blur.
  91647. */
  91648. set: function (value) {
  91649. this._horizontalBlurPostprocess1.kernel = value;
  91650. this._verticalBlurPostprocess1.kernel = value;
  91651. this._horizontalBlurPostprocess2.kernel = value;
  91652. this._verticalBlurPostprocess2.kernel = value;
  91653. },
  91654. enumerable: true,
  91655. configurable: true
  91656. });
  91657. Object.defineProperty(GlowLayer.prototype, "intensity", {
  91658. /**
  91659. * Gets the glow intensity.
  91660. */
  91661. get: function () {
  91662. return this._intensity;
  91663. },
  91664. /**
  91665. * Sets the glow intensity.
  91666. */
  91667. set: function (value) {
  91668. this._intensity = value;
  91669. },
  91670. enumerable: true,
  91671. configurable: true
  91672. });
  91673. /**
  91674. * Get the effect name of the layer.
  91675. * @return The effect name
  91676. */
  91677. GlowLayer.prototype.getEffectName = function () {
  91678. return GlowLayer.EffectName;
  91679. };
  91680. /**
  91681. * Create the merge effect. This is the shader use to blit the information back
  91682. * to the main canvas at the end of the scene rendering.
  91683. */
  91684. GlowLayer.prototype._createMergeEffect = function () {
  91685. // Effect
  91686. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  91687. };
  91688. /**
  91689. * Creates the render target textures and post processes used in the glow layer.
  91690. */
  91691. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  91692. var _this = this;
  91693. var blurTextureWidth = this._mainTextureDesiredSize.width;
  91694. var blurTextureHeight = this._mainTextureDesiredSize.height;
  91695. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91696. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91697. var textureType = 0;
  91698. if (this._engine.getCaps().textureHalfFloatRender) {
  91699. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91700. }
  91701. else {
  91702. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91703. }
  91704. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  91705. width: blurTextureWidth,
  91706. height: blurTextureHeight
  91707. }, this._scene, false, true, textureType);
  91708. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91709. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91710. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91711. this._blurTexture1.renderParticles = false;
  91712. this._blurTexture1.ignoreCameraViewport = true;
  91713. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  91714. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  91715. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  91716. width: blurTextureWidth2,
  91717. height: blurTextureHeight2
  91718. }, this._scene, false, true, textureType);
  91719. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91720. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91721. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91722. this._blurTexture2.renderParticles = false;
  91723. this._blurTexture2.ignoreCameraViewport = true;
  91724. this._textures = [this._blurTexture1, this._blurTexture2];
  91725. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91726. width: blurTextureWidth,
  91727. height: blurTextureHeight
  91728. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91729. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  91730. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  91731. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  91732. effect.setTexture("textureSampler", _this._mainTexture);
  91733. });
  91734. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91735. width: blurTextureWidth,
  91736. height: blurTextureHeight
  91737. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91738. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91739. width: blurTextureWidth2,
  91740. height: blurTextureHeight2
  91741. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91742. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  91743. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  91744. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  91745. effect.setTexture("textureSampler", _this._blurTexture1);
  91746. });
  91747. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91748. width: blurTextureWidth2,
  91749. height: blurTextureHeight2
  91750. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91751. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91752. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  91753. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91754. this._mainTexture.samples = this._options.mainTextureSamples;
  91755. this._mainTexture.onAfterUnbindObservable.add(function () {
  91756. var internalTexture = _this._blurTexture1.getInternalTexture();
  91757. if (internalTexture) {
  91758. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  91759. internalTexture = _this._blurTexture2.getInternalTexture();
  91760. if (internalTexture) {
  91761. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  91762. }
  91763. }
  91764. });
  91765. // Prevent autoClear.
  91766. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91767. };
  91768. /**
  91769. * Checks for the readiness of the element composing the layer.
  91770. * @param subMesh the mesh to check for
  91771. * @param useInstances specify wether or not to use instances to render the mesh
  91772. * @param emissiveTexture the associated emissive texture used to generate the glow
  91773. * @return true if ready otherwise, false
  91774. */
  91775. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  91776. var material = subMesh.getMaterial();
  91777. var mesh = subMesh.getRenderingMesh();
  91778. if (!material || !mesh) {
  91779. return false;
  91780. }
  91781. var emissiveTexture = material.emissiveTexture;
  91782. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91783. };
  91784. /**
  91785. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91786. */
  91787. GlowLayer.prototype.needStencil = function () {
  91788. return false;
  91789. };
  91790. /**
  91791. * Implementation specific of rendering the generating effect on the main canvas.
  91792. * @param effect The effect used to render through
  91793. */
  91794. GlowLayer.prototype._internalRender = function (effect) {
  91795. // Texture
  91796. effect.setTexture("textureSampler", this._blurTexture1);
  91797. effect.setTexture("textureSampler2", this._blurTexture2);
  91798. effect.setFloat("offset", this._intensity);
  91799. // Cache
  91800. var engine = this._engine;
  91801. var previousStencilBuffer = engine.getStencilBuffer();
  91802. // Draw order
  91803. engine.setStencilBuffer(false);
  91804. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91805. // Draw order
  91806. engine.setStencilBuffer(previousStencilBuffer);
  91807. };
  91808. /**
  91809. * Sets the required values for both the emissive texture and and the main color.
  91810. */
  91811. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91812. var textureLevel = 1.0;
  91813. if (this.customEmissiveTextureSelector) {
  91814. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  91815. }
  91816. else {
  91817. if (material) {
  91818. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91819. if (this._emissiveTextureAndColor.texture) {
  91820. textureLevel = this._emissiveTextureAndColor.texture.level;
  91821. }
  91822. }
  91823. else {
  91824. this._emissiveTextureAndColor.texture = null;
  91825. }
  91826. }
  91827. if (this.customEmissiveColorSelector) {
  91828. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  91829. }
  91830. else {
  91831. if (material.emissiveColor) {
  91832. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  91833. }
  91834. else {
  91835. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91836. }
  91837. }
  91838. };
  91839. /**
  91840. * Returns true if the mesh should render, otherwise false.
  91841. * @param mesh The mesh to render
  91842. * @returns true if it should render otherwise false
  91843. */
  91844. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  91845. return this.hasMesh(mesh);
  91846. };
  91847. /**
  91848. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  91849. * @param mesh The mesh to exclude from the glow layer
  91850. */
  91851. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  91852. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  91853. this._excludedMeshes.push(mesh.uniqueId);
  91854. }
  91855. };
  91856. /**
  91857. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  91858. * @param mesh The mesh to remove
  91859. */
  91860. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  91861. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  91862. if (index !== -1) {
  91863. this._excludedMeshes.splice(index, 1);
  91864. }
  91865. };
  91866. /**
  91867. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  91868. * @param mesh The mesh to include in the glow layer
  91869. */
  91870. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  91871. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  91872. this._includedOnlyMeshes.push(mesh.uniqueId);
  91873. }
  91874. };
  91875. /**
  91876. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  91877. * @param mesh The mesh to remove
  91878. */
  91879. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  91880. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  91881. if (index !== -1) {
  91882. this._includedOnlyMeshes.splice(index, 1);
  91883. }
  91884. };
  91885. /**
  91886. * Determine if a given mesh will be used in the glow layer
  91887. * @param mesh The mesh to test
  91888. * @returns true if the mesh will be highlighted by the current glow layer
  91889. */
  91890. GlowLayer.prototype.hasMesh = function (mesh) {
  91891. // Included Mesh
  91892. if (this._includedOnlyMeshes.length) {
  91893. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  91894. }
  91895. ;
  91896. // Excluded Mesh
  91897. if (this._excludedMeshes.length) {
  91898. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  91899. }
  91900. ;
  91901. return true;
  91902. };
  91903. /**
  91904. * Free any resources and references associated to a mesh.
  91905. * Internal use
  91906. * @param mesh The mesh to free.
  91907. */
  91908. GlowLayer.prototype._disposeMesh = function (mesh) {
  91909. this.removeIncludedOnlyMesh(mesh);
  91910. this.removeExcludedMesh(mesh);
  91911. };
  91912. /**
  91913. * Gets the class name of the effect layer
  91914. * @returns the string with the class name of the effect layer
  91915. */
  91916. GlowLayer.prototype.getClassName = function () {
  91917. return "GlowLayer";
  91918. };
  91919. /**
  91920. * Serializes this glow layer
  91921. * @returns a serialized glow layer object
  91922. */
  91923. GlowLayer.prototype.serialize = function () {
  91924. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91925. serializationObject.customType = "BABYLON.GlowLayer";
  91926. var index;
  91927. // Included meshes
  91928. serializationObject.includedMeshes = [];
  91929. if (this._includedOnlyMeshes.length) {
  91930. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  91931. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  91932. if (mesh) {
  91933. serializationObject.includedMeshes.push(mesh.id);
  91934. }
  91935. }
  91936. }
  91937. // Excluded meshes
  91938. serializationObject.excludedMeshes = [];
  91939. if (this._excludedMeshes.length) {
  91940. for (index = 0; index < this._excludedMeshes.length; index++) {
  91941. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  91942. if (mesh) {
  91943. serializationObject.excludedMeshes.push(mesh.id);
  91944. }
  91945. }
  91946. }
  91947. return serializationObject;
  91948. };
  91949. /**
  91950. * Creates a Glow Layer from parsed glow layer data
  91951. * @param parsedGlowLayer defines glow layer data
  91952. * @param scene defines the current scene
  91953. * @param rootUrl defines the root URL containing the glow layer information
  91954. * @returns a parsed Glow Layer
  91955. */
  91956. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  91957. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  91958. var index;
  91959. // Excluded meshes
  91960. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  91961. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  91962. if (mesh) {
  91963. gl.addExcludedMesh(mesh);
  91964. }
  91965. }
  91966. // Included meshes
  91967. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  91968. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  91969. if (mesh) {
  91970. gl.addIncludedOnlyMesh(mesh);
  91971. }
  91972. }
  91973. return gl;
  91974. };
  91975. /**
  91976. * Effect Name of the layer.
  91977. */
  91978. GlowLayer.EffectName = "GlowLayer";
  91979. /**
  91980. * The default blur kernel size used for the glow.
  91981. */
  91982. GlowLayer.DefaultBlurKernelSize = 32;
  91983. /**
  91984. * The default texture size ratio used for the glow.
  91985. */
  91986. GlowLayer.DefaultTextureRatio = 0.5;
  91987. __decorate([
  91988. BABYLON.serialize()
  91989. ], GlowLayer.prototype, "blurKernelSize", null);
  91990. __decorate([
  91991. BABYLON.serialize()
  91992. ], GlowLayer.prototype, "intensity", null);
  91993. __decorate([
  91994. BABYLON.serialize("options")
  91995. ], GlowLayer.prototype, "_options", void 0);
  91996. return GlowLayer;
  91997. }(BABYLON.EffectLayer));
  91998. BABYLON.GlowLayer = GlowLayer;
  91999. })(BABYLON || (BABYLON = {}));
  92000. //# sourceMappingURL=babylon.glowLayer.js.map
  92001. var BABYLON;
  92002. (function (BABYLON) {
  92003. /**
  92004. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92005. */
  92006. var AssetTaskState;
  92007. (function (AssetTaskState) {
  92008. /**
  92009. * Initialization
  92010. */
  92011. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92012. /**
  92013. * Running
  92014. */
  92015. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92016. /**
  92017. * Done
  92018. */
  92019. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92020. /**
  92021. * Error
  92022. */
  92023. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92024. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92025. /**
  92026. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92027. */
  92028. var AbstractAssetTask = /** @class */ (function () {
  92029. /**
  92030. * Creates a new {BABYLON.AssetsManager}
  92031. * @param name defines the name of the task
  92032. */
  92033. function AbstractAssetTask(
  92034. /**
  92035. * Task name
  92036. */ name) {
  92037. this.name = name;
  92038. this._isCompleted = false;
  92039. this._taskState = AssetTaskState.INIT;
  92040. }
  92041. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92042. /**
  92043. * Get if the task is completed
  92044. */
  92045. get: function () {
  92046. return this._isCompleted;
  92047. },
  92048. enumerable: true,
  92049. configurable: true
  92050. });
  92051. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92052. /**
  92053. * Gets the current state of the task
  92054. */
  92055. get: function () {
  92056. return this._taskState;
  92057. },
  92058. enumerable: true,
  92059. configurable: true
  92060. });
  92061. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92062. /**
  92063. * Gets the current error object (if task is in error)
  92064. */
  92065. get: function () {
  92066. return this._errorObject;
  92067. },
  92068. enumerable: true,
  92069. configurable: true
  92070. });
  92071. /**
  92072. * Internal only
  92073. * @ignore
  92074. */
  92075. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92076. if (this._errorObject) {
  92077. return;
  92078. }
  92079. this._errorObject = {
  92080. message: message,
  92081. exception: exception
  92082. };
  92083. };
  92084. /**
  92085. * Execute the current task
  92086. * @param scene defines the scene where you want your assets to be loaded
  92087. * @param onSuccess is a callback called when the task is successfully executed
  92088. * @param onError is a callback called if an error occurs
  92089. */
  92090. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92091. var _this = this;
  92092. this._taskState = AssetTaskState.RUNNING;
  92093. this.runTask(scene, function () {
  92094. _this.onDoneCallback(onSuccess, onError);
  92095. }, function (msg, exception) {
  92096. _this.onErrorCallback(onError, msg, exception);
  92097. });
  92098. };
  92099. /**
  92100. * Execute the current task
  92101. * @param scene defines the scene where you want your assets to be loaded
  92102. * @param onSuccess is a callback called when the task is successfully executed
  92103. * @param onError is a callback called if an error occurs
  92104. */
  92105. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92106. throw new Error("runTask is not implemented");
  92107. };
  92108. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92109. this._taskState = AssetTaskState.ERROR;
  92110. this._errorObject = {
  92111. message: message,
  92112. exception: exception
  92113. };
  92114. if (this.onError) {
  92115. this.onError(this, message, exception);
  92116. }
  92117. onError();
  92118. };
  92119. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92120. try {
  92121. this._taskState = AssetTaskState.DONE;
  92122. this._isCompleted = true;
  92123. if (this.onSuccess) {
  92124. this.onSuccess(this);
  92125. }
  92126. onSuccess();
  92127. }
  92128. catch (e) {
  92129. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92130. }
  92131. };
  92132. return AbstractAssetTask;
  92133. }());
  92134. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92135. /**
  92136. * Class used to share progress information about assets loading
  92137. */
  92138. var AssetsProgressEvent = /** @class */ (function () {
  92139. /**
  92140. * Creates a {BABYLON.AssetsProgressEvent}
  92141. * @param remainingCount defines the number of remaining tasks to process
  92142. * @param totalCount defines the total number of tasks
  92143. * @param task defines the task that was just processed
  92144. */
  92145. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92146. this.remainingCount = remainingCount;
  92147. this.totalCount = totalCount;
  92148. this.task = task;
  92149. }
  92150. return AssetsProgressEvent;
  92151. }());
  92152. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92153. /**
  92154. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92155. */
  92156. var MeshAssetTask = /** @class */ (function (_super) {
  92157. __extends(MeshAssetTask, _super);
  92158. /**
  92159. * Creates a new {BABYLON.MeshAssetTask}
  92160. * @param name defines the name of the task
  92161. * @param meshesNames defines the list of mesh's names you want to load
  92162. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92163. * @param sceneFilename defines the filename of the scene to load from
  92164. */
  92165. function MeshAssetTask(
  92166. /**
  92167. * Defines the name of the task
  92168. */
  92169. name,
  92170. /**
  92171. * Defines the list of mesh's names you want to load
  92172. */
  92173. meshesNames,
  92174. /**
  92175. * Defines the root url to use as a base to load your meshes and associated resources
  92176. */
  92177. rootUrl,
  92178. /**
  92179. * Defines the filename of the scene to load from
  92180. */
  92181. sceneFilename) {
  92182. var _this = _super.call(this, name) || this;
  92183. _this.name = name;
  92184. _this.meshesNames = meshesNames;
  92185. _this.rootUrl = rootUrl;
  92186. _this.sceneFilename = sceneFilename;
  92187. return _this;
  92188. }
  92189. /**
  92190. * Execute the current task
  92191. * @param scene defines the scene where you want your assets to be loaded
  92192. * @param onSuccess is a callback called when the task is successfully executed
  92193. * @param onError is a callback called if an error occurs
  92194. */
  92195. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92196. var _this = this;
  92197. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92198. _this.loadedMeshes = meshes;
  92199. _this.loadedParticleSystems = particleSystems;
  92200. _this.loadedSkeletons = skeletons;
  92201. onSuccess();
  92202. }, null, function (scene, message, exception) {
  92203. onError(message, exception);
  92204. });
  92205. };
  92206. return MeshAssetTask;
  92207. }(AbstractAssetTask));
  92208. BABYLON.MeshAssetTask = MeshAssetTask;
  92209. /**
  92210. * Define a task used by {BABYLON.AssetsManager} to load text content
  92211. */
  92212. var TextFileAssetTask = /** @class */ (function (_super) {
  92213. __extends(TextFileAssetTask, _super);
  92214. /**
  92215. * Creates a new TextFileAssetTask object
  92216. * @param name defines the name of the task
  92217. * @param url defines the location of the file to load
  92218. */
  92219. function TextFileAssetTask(
  92220. /**
  92221. * Defines the name of the task
  92222. */
  92223. name,
  92224. /**
  92225. * Defines the location of the file to load
  92226. */
  92227. url) {
  92228. var _this = _super.call(this, name) || this;
  92229. _this.name = name;
  92230. _this.url = url;
  92231. return _this;
  92232. }
  92233. /**
  92234. * Execute the current task
  92235. * @param scene defines the scene where you want your assets to be loaded
  92236. * @param onSuccess is a callback called when the task is successfully executed
  92237. * @param onError is a callback called if an error occurs
  92238. */
  92239. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92240. var _this = this;
  92241. scene._loadFile(this.url, function (data) {
  92242. _this.text = data;
  92243. onSuccess();
  92244. }, undefined, false, false, function (request, exception) {
  92245. if (request) {
  92246. onError(request.status + " " + request.statusText, exception);
  92247. }
  92248. });
  92249. };
  92250. return TextFileAssetTask;
  92251. }(AbstractAssetTask));
  92252. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92253. /**
  92254. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92255. */
  92256. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92257. __extends(BinaryFileAssetTask, _super);
  92258. /**
  92259. * Creates a new BinaryFileAssetTask object
  92260. * @param name defines the name of the new task
  92261. * @param url defines the location of the file to load
  92262. */
  92263. function BinaryFileAssetTask(
  92264. /**
  92265. * Defines the name of the task
  92266. */
  92267. name,
  92268. /**
  92269. * Defines the location of the file to load
  92270. */
  92271. url) {
  92272. var _this = _super.call(this, name) || this;
  92273. _this.name = name;
  92274. _this.url = url;
  92275. return _this;
  92276. }
  92277. /**
  92278. * Execute the current task
  92279. * @param scene defines the scene where you want your assets to be loaded
  92280. * @param onSuccess is a callback called when the task is successfully executed
  92281. * @param onError is a callback called if an error occurs
  92282. */
  92283. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92284. var _this = this;
  92285. scene._loadFile(this.url, function (data) {
  92286. _this.data = data;
  92287. onSuccess();
  92288. }, undefined, true, true, function (request, exception) {
  92289. if (request) {
  92290. onError(request.status + " " + request.statusText, exception);
  92291. }
  92292. });
  92293. };
  92294. return BinaryFileAssetTask;
  92295. }(AbstractAssetTask));
  92296. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92297. /**
  92298. * Define a task used by {BABYLON.AssetsManager} to load images
  92299. */
  92300. var ImageAssetTask = /** @class */ (function (_super) {
  92301. __extends(ImageAssetTask, _super);
  92302. /**
  92303. * Creates a new ImageAssetTask
  92304. * @param name defines the name of the task
  92305. * @param url defines the location of the image to load
  92306. */
  92307. function ImageAssetTask(
  92308. /**
  92309. * Defines the name of the task
  92310. */
  92311. name,
  92312. /**
  92313. * Defines the location of the image to load
  92314. */
  92315. url) {
  92316. var _this = _super.call(this, name) || this;
  92317. _this.name = name;
  92318. _this.url = url;
  92319. return _this;
  92320. }
  92321. /**
  92322. * Execute the current task
  92323. * @param scene defines the scene where you want your assets to be loaded
  92324. * @param onSuccess is a callback called when the task is successfully executed
  92325. * @param onError is a callback called if an error occurs
  92326. */
  92327. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92328. var _this = this;
  92329. var img = new Image();
  92330. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92331. img.onload = function () {
  92332. _this.image = img;
  92333. onSuccess();
  92334. };
  92335. img.onerror = function (err) {
  92336. onError("Error loading image", err);
  92337. };
  92338. img.src = this.url;
  92339. };
  92340. return ImageAssetTask;
  92341. }(AbstractAssetTask));
  92342. BABYLON.ImageAssetTask = ImageAssetTask;
  92343. /**
  92344. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92345. */
  92346. var TextureAssetTask = /** @class */ (function (_super) {
  92347. __extends(TextureAssetTask, _super);
  92348. /**
  92349. * Creates a new TextureAssetTask object
  92350. * @param name defines the name of the task
  92351. * @param url defines the location of the file to load
  92352. * @param noMipmap defines if mipmap should not be generated (default is false)
  92353. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92354. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92355. */
  92356. function TextureAssetTask(
  92357. /**
  92358. * Defines the name of the task
  92359. */
  92360. name,
  92361. /**
  92362. * Defines the location of the file to load
  92363. */
  92364. url,
  92365. /**
  92366. * Defines if mipmap should not be generated (default is false)
  92367. */
  92368. noMipmap,
  92369. /**
  92370. * Defines if texture must be inverted on Y axis (default is false)
  92371. */
  92372. invertY,
  92373. /**
  92374. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92375. */
  92376. samplingMode) {
  92377. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92378. var _this = _super.call(this, name) || this;
  92379. _this.name = name;
  92380. _this.url = url;
  92381. _this.noMipmap = noMipmap;
  92382. _this.invertY = invertY;
  92383. _this.samplingMode = samplingMode;
  92384. return _this;
  92385. }
  92386. /**
  92387. * Execute the current task
  92388. * @param scene defines the scene where you want your assets to be loaded
  92389. * @param onSuccess is a callback called when the task is successfully executed
  92390. * @param onError is a callback called if an error occurs
  92391. */
  92392. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92393. var onload = function () {
  92394. onSuccess();
  92395. };
  92396. var onerror = function (message, exception) {
  92397. onError(message, exception);
  92398. };
  92399. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92400. };
  92401. return TextureAssetTask;
  92402. }(AbstractAssetTask));
  92403. BABYLON.TextureAssetTask = TextureAssetTask;
  92404. /**
  92405. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92406. */
  92407. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92408. __extends(CubeTextureAssetTask, _super);
  92409. /**
  92410. * Creates a new CubeTextureAssetTask
  92411. * @param name defines the name of the task
  92412. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92413. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92414. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92415. * @param files defines the explicit list of files (undefined by default)
  92416. */
  92417. function CubeTextureAssetTask(
  92418. /**
  92419. * Defines the name of the task
  92420. */
  92421. name,
  92422. /**
  92423. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92424. */
  92425. url,
  92426. /**
  92427. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92428. */
  92429. extensions,
  92430. /**
  92431. * Defines if mipmaps should not be generated (default is false)
  92432. */
  92433. noMipmap,
  92434. /**
  92435. * Defines the explicit list of files (undefined by default)
  92436. */
  92437. files) {
  92438. var _this = _super.call(this, name) || this;
  92439. _this.name = name;
  92440. _this.url = url;
  92441. _this.extensions = extensions;
  92442. _this.noMipmap = noMipmap;
  92443. _this.files = files;
  92444. return _this;
  92445. }
  92446. /**
  92447. * Execute the current task
  92448. * @param scene defines the scene where you want your assets to be loaded
  92449. * @param onSuccess is a callback called when the task is successfully executed
  92450. * @param onError is a callback called if an error occurs
  92451. */
  92452. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92453. var onload = function () {
  92454. onSuccess();
  92455. };
  92456. var onerror = function (message, exception) {
  92457. onError(message, exception);
  92458. };
  92459. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  92460. };
  92461. return CubeTextureAssetTask;
  92462. }(AbstractAssetTask));
  92463. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  92464. /**
  92465. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  92466. */
  92467. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  92468. __extends(HDRCubeTextureAssetTask, _super);
  92469. /**
  92470. * Creates a new HDRCubeTextureAssetTask object
  92471. * @param name defines the name of the task
  92472. * @param url defines the location of the file to load
  92473. * @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.
  92474. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92475. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92476. * @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)
  92477. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92478. */
  92479. function HDRCubeTextureAssetTask(
  92480. /**
  92481. * Defines the name of the task
  92482. */
  92483. name,
  92484. /**
  92485. * Defines the location of the file to load
  92486. */
  92487. url,
  92488. /**
  92489. * 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.
  92490. */
  92491. size,
  92492. /**
  92493. * Defines if mipmaps should not be generated (default is false)
  92494. */
  92495. noMipmap,
  92496. /**
  92497. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92498. */
  92499. generateHarmonics,
  92500. /**
  92501. * 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)
  92502. */
  92503. useInGammaSpace,
  92504. /**
  92505. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92506. */
  92507. usePMREMGenerator) {
  92508. if (noMipmap === void 0) { noMipmap = false; }
  92509. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92510. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92511. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92512. var _this = _super.call(this, name) || this;
  92513. _this.name = name;
  92514. _this.url = url;
  92515. _this.size = size;
  92516. _this.noMipmap = noMipmap;
  92517. _this.generateHarmonics = generateHarmonics;
  92518. _this.useInGammaSpace = useInGammaSpace;
  92519. _this.usePMREMGenerator = usePMREMGenerator;
  92520. return _this;
  92521. }
  92522. /**
  92523. * Execute the current task
  92524. * @param scene defines the scene where you want your assets to be loaded
  92525. * @param onSuccess is a callback called when the task is successfully executed
  92526. * @param onError is a callback called if an error occurs
  92527. */
  92528. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92529. var onload = function () {
  92530. onSuccess();
  92531. };
  92532. var onerror = function (message, exception) {
  92533. onError(message, exception);
  92534. };
  92535. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  92536. };
  92537. return HDRCubeTextureAssetTask;
  92538. }(AbstractAssetTask));
  92539. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  92540. /**
  92541. * This class can be used to easily import assets into a scene
  92542. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  92543. */
  92544. var AssetsManager = /** @class */ (function () {
  92545. /**
  92546. * Creates a new AssetsManager
  92547. * @param scene defines the scene to work on
  92548. */
  92549. function AssetsManager(scene) {
  92550. this._isLoading = false;
  92551. this._tasks = new Array();
  92552. this._waitingTasksCount = 0;
  92553. this._totalTasksCount = 0;
  92554. /**
  92555. * Observable called when all tasks are processed
  92556. */
  92557. this.onTaskSuccessObservable = new BABYLON.Observable();
  92558. /**
  92559. * Observable called when a task had an error
  92560. */
  92561. this.onTaskErrorObservable = new BABYLON.Observable();
  92562. /**
  92563. * Observable called when a task is successful
  92564. */
  92565. this.onTasksDoneObservable = new BABYLON.Observable();
  92566. /**
  92567. * Observable called when a task is done (whatever the result is)
  92568. */
  92569. this.onProgressObservable = new BABYLON.Observable();
  92570. /**
  92571. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  92572. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  92573. */
  92574. this.useDefaultLoadingScreen = true;
  92575. this._scene = scene;
  92576. }
  92577. /**
  92578. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  92579. * @param taskName defines the name of the new task
  92580. * @param meshesNames defines the name of meshes to load
  92581. * @param rootUrl defines the root url to use to locate files
  92582. * @param sceneFilename defines the filename of the scene file
  92583. * @returns a new {BABYLON.MeshAssetTask} object
  92584. */
  92585. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  92586. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  92587. this._tasks.push(task);
  92588. return task;
  92589. };
  92590. /**
  92591. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  92592. * @param taskName defines the name of the new task
  92593. * @param url defines the url of the file to load
  92594. * @returns a new {BABYLON.TextFileAssetTask} object
  92595. */
  92596. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  92597. var task = new TextFileAssetTask(taskName, url);
  92598. this._tasks.push(task);
  92599. return task;
  92600. };
  92601. /**
  92602. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  92603. * @param taskName defines the name of the new task
  92604. * @param url defines the url of the file to load
  92605. * @returns a new {BABYLON.BinaryFileAssetTask} object
  92606. */
  92607. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  92608. var task = new BinaryFileAssetTask(taskName, url);
  92609. this._tasks.push(task);
  92610. return task;
  92611. };
  92612. /**
  92613. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  92614. * @param taskName defines the name of the new task
  92615. * @param url defines the url of the file to load
  92616. * @returns a new {BABYLON.ImageAssetTask} object
  92617. */
  92618. AssetsManager.prototype.addImageTask = function (taskName, url) {
  92619. var task = new ImageAssetTask(taskName, url);
  92620. this._tasks.push(task);
  92621. return task;
  92622. };
  92623. /**
  92624. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  92625. * @param taskName defines the name of the new task
  92626. * @param url defines the url of the file to load
  92627. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92628. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  92629. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  92630. * @returns a new {BABYLON.TextureAssetTask} object
  92631. */
  92632. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  92633. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92634. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  92635. this._tasks.push(task);
  92636. return task;
  92637. };
  92638. /**
  92639. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  92640. * @param taskName defines the name of the new task
  92641. * @param url defines the url of the file to load
  92642. * @param extensions defines the extension to use to load the cube map (can be null)
  92643. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92644. * @param files defines the list of files to load (can be null)
  92645. * @returns a new {BABYLON.CubeTextureAssetTask} object
  92646. */
  92647. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  92648. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  92649. this._tasks.push(task);
  92650. return task;
  92651. };
  92652. /**
  92653. *
  92654. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  92655. * @param taskName defines the name of the new task
  92656. * @param url defines the url of the file to load
  92657. * @param size defines the size you want for the cubemap (can be null)
  92658. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92659. * @param generateHarmonics defines if you want to automatically generate (true by default)
  92660. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  92661. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  92662. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  92663. */
  92664. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  92665. if (noMipmap === void 0) { noMipmap = false; }
  92666. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92667. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92668. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92669. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  92670. this._tasks.push(task);
  92671. return task;
  92672. };
  92673. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  92674. var _this = this;
  92675. this._waitingTasksCount--;
  92676. try {
  92677. if (task.taskState === AssetTaskState.DONE) {
  92678. // Let's remove successfull tasks
  92679. BABYLON.Tools.SetImmediate(function () {
  92680. var index = _this._tasks.indexOf(task);
  92681. if (index > -1) {
  92682. _this._tasks.splice(index, 1);
  92683. }
  92684. });
  92685. }
  92686. if (this.onProgress) {
  92687. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  92688. }
  92689. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  92690. }
  92691. catch (e) {
  92692. BABYLON.Tools.Error("Error running progress callbacks.");
  92693. console.log(e);
  92694. }
  92695. if (this._waitingTasksCount === 0) {
  92696. try {
  92697. if (this.onFinish) {
  92698. this.onFinish(this._tasks);
  92699. }
  92700. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92701. }
  92702. catch (e) {
  92703. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  92704. console.log(e);
  92705. }
  92706. this._isLoading = false;
  92707. this._scene.getEngine().hideLoadingUI();
  92708. }
  92709. };
  92710. AssetsManager.prototype._runTask = function (task) {
  92711. var _this = this;
  92712. var done = function () {
  92713. try {
  92714. if (_this.onTaskSuccess) {
  92715. _this.onTaskSuccess(task);
  92716. }
  92717. _this.onTaskSuccessObservable.notifyObservers(task);
  92718. _this._decreaseWaitingTasksCount(task);
  92719. }
  92720. catch (e) {
  92721. error("Error executing task success callbacks", e);
  92722. }
  92723. };
  92724. var error = function (message, exception) {
  92725. task._setErrorObject(message, exception);
  92726. if (_this.onTaskError) {
  92727. _this.onTaskError(task);
  92728. }
  92729. _this.onTaskErrorObservable.notifyObservers(task);
  92730. _this._decreaseWaitingTasksCount(task);
  92731. };
  92732. task.run(this._scene, done, error);
  92733. };
  92734. /**
  92735. * Reset the {BABYLON.AssetsManager} and remove all tasks
  92736. * @return the current instance of the {BABYLON.AssetsManager}
  92737. */
  92738. AssetsManager.prototype.reset = function () {
  92739. this._isLoading = false;
  92740. this._tasks = new Array();
  92741. return this;
  92742. };
  92743. /**
  92744. * Start the loading process
  92745. * @return the current instance of the {BABYLON.AssetsManager}
  92746. */
  92747. AssetsManager.prototype.load = function () {
  92748. if (this._isLoading) {
  92749. return this;
  92750. }
  92751. this._isLoading = true;
  92752. this._waitingTasksCount = this._tasks.length;
  92753. this._totalTasksCount = this._tasks.length;
  92754. if (this._waitingTasksCount === 0) {
  92755. this._isLoading = false;
  92756. if (this.onFinish) {
  92757. this.onFinish(this._tasks);
  92758. }
  92759. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92760. return this;
  92761. }
  92762. if (this.useDefaultLoadingScreen) {
  92763. this._scene.getEngine().displayLoadingUI();
  92764. }
  92765. for (var index = 0; index < this._tasks.length; index++) {
  92766. var task = this._tasks[index];
  92767. this._runTask(task);
  92768. }
  92769. return this;
  92770. };
  92771. return AssetsManager;
  92772. }());
  92773. BABYLON.AssetsManager = AssetsManager;
  92774. })(BABYLON || (BABYLON = {}));
  92775. //# sourceMappingURL=babylon.assetsManager.js.map
  92776. var BABYLON;
  92777. (function (BABYLON) {
  92778. var serializedGeometries = [];
  92779. var serializeGeometry = function (geometry, serializationGeometries) {
  92780. if (serializedGeometries[geometry.id]) {
  92781. return;
  92782. }
  92783. if (geometry.doNotSerialize) {
  92784. return;
  92785. }
  92786. if (geometry instanceof BABYLON.BoxGeometry) {
  92787. serializationGeometries.boxes.push(geometry.serialize());
  92788. }
  92789. else if (geometry instanceof BABYLON.SphereGeometry) {
  92790. serializationGeometries.spheres.push(geometry.serialize());
  92791. }
  92792. else if (geometry instanceof BABYLON.CylinderGeometry) {
  92793. serializationGeometries.cylinders.push(geometry.serialize());
  92794. }
  92795. else if (geometry instanceof BABYLON.TorusGeometry) {
  92796. serializationGeometries.toruses.push(geometry.serialize());
  92797. }
  92798. else if (geometry instanceof BABYLON.GroundGeometry) {
  92799. serializationGeometries.grounds.push(geometry.serialize());
  92800. }
  92801. else if (geometry instanceof BABYLON.Plane) {
  92802. serializationGeometries.planes.push(geometry.serialize());
  92803. }
  92804. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  92805. serializationGeometries.torusKnots.push(geometry.serialize());
  92806. }
  92807. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  92808. throw new Error("Unknown primitive type");
  92809. }
  92810. else {
  92811. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  92812. }
  92813. serializedGeometries[geometry.id] = true;
  92814. };
  92815. var serializeMesh = function (mesh, serializationScene) {
  92816. var serializationObject = {};
  92817. // Geometry
  92818. var geometry = mesh._geometry;
  92819. if (geometry) {
  92820. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  92821. // 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
  92822. serializeGeometry(geometry, serializationScene.geometries);
  92823. }
  92824. }
  92825. // Custom
  92826. if (mesh.serialize) {
  92827. mesh.serialize(serializationObject);
  92828. }
  92829. return serializationObject;
  92830. };
  92831. var finalizeSingleMesh = function (mesh, serializationObject) {
  92832. //only works if the mesh is already loaded
  92833. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92834. //serialize material
  92835. if (mesh.material) {
  92836. if (mesh.material instanceof BABYLON.StandardMaterial) {
  92837. serializationObject.materials = serializationObject.materials || [];
  92838. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92839. serializationObject.materials.push(mesh.material.serialize());
  92840. }
  92841. }
  92842. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  92843. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  92844. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92845. serializationObject.multiMaterials.push(mesh.material.serialize());
  92846. }
  92847. }
  92848. }
  92849. //serialize geometry
  92850. var geometry = mesh._geometry;
  92851. if (geometry) {
  92852. if (!serializationObject.geometries) {
  92853. serializationObject.geometries = {};
  92854. serializationObject.geometries.boxes = [];
  92855. serializationObject.geometries.spheres = [];
  92856. serializationObject.geometries.cylinders = [];
  92857. serializationObject.geometries.toruses = [];
  92858. serializationObject.geometries.grounds = [];
  92859. serializationObject.geometries.planes = [];
  92860. serializationObject.geometries.torusKnots = [];
  92861. serializationObject.geometries.vertexData = [];
  92862. }
  92863. serializeGeometry(geometry, serializationObject.geometries);
  92864. }
  92865. // Skeletons
  92866. if (mesh.skeleton) {
  92867. serializationObject.skeletons = serializationObject.skeletons || [];
  92868. serializationObject.skeletons.push(mesh.skeleton.serialize());
  92869. }
  92870. //serialize the actual mesh
  92871. serializationObject.meshes = serializationObject.meshes || [];
  92872. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92873. }
  92874. };
  92875. var SceneSerializer = /** @class */ (function () {
  92876. function SceneSerializer() {
  92877. }
  92878. SceneSerializer.ClearCache = function () {
  92879. serializedGeometries = [];
  92880. };
  92881. SceneSerializer.Serialize = function (scene) {
  92882. var serializationObject = {};
  92883. SceneSerializer.ClearCache();
  92884. // Scene
  92885. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  92886. serializationObject.autoClear = scene.autoClear;
  92887. serializationObject.clearColor = scene.clearColor.asArray();
  92888. serializationObject.ambientColor = scene.ambientColor.asArray();
  92889. serializationObject.gravity = scene.gravity.asArray();
  92890. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  92891. serializationObject.workerCollisions = scene.workerCollisions;
  92892. // Fog
  92893. if (scene.fogMode && scene.fogMode !== 0) {
  92894. serializationObject.fogMode = scene.fogMode;
  92895. serializationObject.fogColor = scene.fogColor.asArray();
  92896. serializationObject.fogStart = scene.fogStart;
  92897. serializationObject.fogEnd = scene.fogEnd;
  92898. serializationObject.fogDensity = scene.fogDensity;
  92899. }
  92900. //Physics
  92901. if (scene.isPhysicsEnabled()) {
  92902. var physicEngine = scene.getPhysicsEngine();
  92903. if (physicEngine) {
  92904. serializationObject.physicsEnabled = true;
  92905. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  92906. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  92907. }
  92908. }
  92909. // Metadata
  92910. if (scene.metadata) {
  92911. serializationObject.metadata = scene.metadata;
  92912. }
  92913. // Morph targets
  92914. serializationObject.morphTargetManagers = [];
  92915. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  92916. var abstractMesh = _a[_i];
  92917. var manager = abstractMesh.morphTargetManager;
  92918. if (manager) {
  92919. serializationObject.morphTargetManagers.push(manager.serialize());
  92920. }
  92921. }
  92922. // Lights
  92923. serializationObject.lights = [];
  92924. var index;
  92925. var light;
  92926. for (index = 0; index < scene.lights.length; index++) {
  92927. light = scene.lights[index];
  92928. if (!light.doNotSerialize) {
  92929. serializationObject.lights.push(light.serialize());
  92930. }
  92931. }
  92932. // Cameras
  92933. serializationObject.cameras = [];
  92934. for (index = 0; index < scene.cameras.length; index++) {
  92935. var camera = scene.cameras[index];
  92936. if (!camera.doNotSerialize) {
  92937. serializationObject.cameras.push(camera.serialize());
  92938. }
  92939. }
  92940. if (scene.activeCamera) {
  92941. serializationObject.activeCameraID = scene.activeCamera.id;
  92942. }
  92943. // Animations
  92944. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  92945. // Materials
  92946. serializationObject.materials = [];
  92947. serializationObject.multiMaterials = [];
  92948. var material;
  92949. for (index = 0; index < scene.materials.length; index++) {
  92950. material = scene.materials[index];
  92951. if (!material.doNotSerialize) {
  92952. serializationObject.materials.push(material.serialize());
  92953. }
  92954. }
  92955. // MultiMaterials
  92956. serializationObject.multiMaterials = [];
  92957. for (index = 0; index < scene.multiMaterials.length; index++) {
  92958. var multiMaterial = scene.multiMaterials[index];
  92959. serializationObject.multiMaterials.push(multiMaterial.serialize());
  92960. }
  92961. // Environment texture
  92962. if (scene.environmentTexture) {
  92963. serializationObject.environmentTexture = scene.environmentTexture.name;
  92964. }
  92965. // Skeletons
  92966. serializationObject.skeletons = [];
  92967. for (index = 0; index < scene.skeletons.length; index++) {
  92968. var skeleton = scene.skeletons[index];
  92969. if (!skeleton.doNotSerialize) {
  92970. serializationObject.skeletons.push(skeleton.serialize());
  92971. }
  92972. }
  92973. // Transform nodes
  92974. serializationObject.transformNodes = [];
  92975. for (index = 0; index < scene.transformNodes.length; index++) {
  92976. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  92977. }
  92978. // Geometries
  92979. serializationObject.geometries = {};
  92980. serializationObject.geometries.boxes = [];
  92981. serializationObject.geometries.spheres = [];
  92982. serializationObject.geometries.cylinders = [];
  92983. serializationObject.geometries.toruses = [];
  92984. serializationObject.geometries.grounds = [];
  92985. serializationObject.geometries.planes = [];
  92986. serializationObject.geometries.torusKnots = [];
  92987. serializationObject.geometries.vertexData = [];
  92988. serializedGeometries = [];
  92989. var geometries = scene.getGeometries();
  92990. for (index = 0; index < geometries.length; index++) {
  92991. var geometry = geometries[index];
  92992. if (geometry.isReady()) {
  92993. serializeGeometry(geometry, serializationObject.geometries);
  92994. }
  92995. }
  92996. // Meshes
  92997. serializationObject.meshes = [];
  92998. for (index = 0; index < scene.meshes.length; index++) {
  92999. var abstractMesh = scene.meshes[index];
  93000. if (abstractMesh instanceof BABYLON.Mesh) {
  93001. var mesh = abstractMesh;
  93002. if (!mesh.doNotSerialize) {
  93003. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93004. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93005. }
  93006. }
  93007. }
  93008. }
  93009. // Particles Systems
  93010. serializationObject.particleSystems = [];
  93011. for (index = 0; index < scene.particleSystems.length; index++) {
  93012. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93013. }
  93014. // Lens flares
  93015. serializationObject.lensFlareSystems = [];
  93016. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93017. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93018. }
  93019. // Shadows
  93020. serializationObject.shadowGenerators = [];
  93021. for (index = 0; index < scene.lights.length; index++) {
  93022. light = scene.lights[index];
  93023. var shadowGenerator = light.getShadowGenerator();
  93024. if (shadowGenerator) {
  93025. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93026. }
  93027. }
  93028. // Action Manager
  93029. if (scene.actionManager) {
  93030. serializationObject.actions = scene.actionManager.serialize("scene");
  93031. }
  93032. // Audio
  93033. serializationObject.sounds = [];
  93034. for (index = 0; index < scene.soundTracks.length; index++) {
  93035. var soundtrack = scene.soundTracks[index];
  93036. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93037. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93038. }
  93039. }
  93040. // Effect layers
  93041. serializationObject.effectLayers = [];
  93042. for (index = 0; index < scene.effectLayers.length; index++) {
  93043. var layer = scene.effectLayers[index];
  93044. if (layer.serialize) {
  93045. serializationObject.effectLayers.push(layer.serialize());
  93046. }
  93047. }
  93048. return serializationObject;
  93049. };
  93050. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93051. if (withParents === void 0) { withParents = false; }
  93052. if (withChildren === void 0) { withChildren = false; }
  93053. var serializationObject = {};
  93054. SceneSerializer.ClearCache();
  93055. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93056. if (withParents || withChildren) {
  93057. //deliberate for loop! not for each, appended should be processed as well.
  93058. for (var i = 0; i < toSerialize.length; ++i) {
  93059. if (withChildren) {
  93060. toSerialize[i].getDescendants().forEach(function (node) {
  93061. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93062. toSerialize.push(node);
  93063. }
  93064. });
  93065. }
  93066. //make sure the array doesn't contain the object already
  93067. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93068. toSerialize.push(toSerialize[i].parent);
  93069. }
  93070. }
  93071. }
  93072. toSerialize.forEach(function (mesh) {
  93073. finalizeSingleMesh(mesh, serializationObject);
  93074. });
  93075. return serializationObject;
  93076. };
  93077. return SceneSerializer;
  93078. }());
  93079. BABYLON.SceneSerializer = SceneSerializer;
  93080. })(BABYLON || (BABYLON = {}));
  93081. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93082. var BABYLON;
  93083. (function (BABYLON) {
  93084. var ReflectionProbe = /** @class */ (function () {
  93085. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93086. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93087. var _this = this;
  93088. this.name = name;
  93089. this._viewMatrix = BABYLON.Matrix.Identity();
  93090. this._target = BABYLON.Vector3.Zero();
  93091. this._add = BABYLON.Vector3.Zero();
  93092. this._invertYAxis = false;
  93093. this.position = BABYLON.Vector3.Zero();
  93094. this._scene = scene;
  93095. this._scene.reflectionProbes.push(this);
  93096. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93097. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93098. switch (faceIndex) {
  93099. case 0:
  93100. _this._add.copyFromFloats(1, 0, 0);
  93101. break;
  93102. case 1:
  93103. _this._add.copyFromFloats(-1, 0, 0);
  93104. break;
  93105. case 2:
  93106. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93107. break;
  93108. case 3:
  93109. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93110. break;
  93111. case 4:
  93112. _this._add.copyFromFloats(0, 0, 1);
  93113. break;
  93114. case 5:
  93115. _this._add.copyFromFloats(0, 0, -1);
  93116. break;
  93117. }
  93118. if (_this._attachedMesh) {
  93119. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93120. }
  93121. _this.position.addToRef(_this._add, _this._target);
  93122. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93123. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93124. scene._forcedViewPosition = _this.position;
  93125. });
  93126. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93127. scene._forcedViewPosition = null;
  93128. scene.updateTransformMatrix(true);
  93129. });
  93130. if (scene.activeCamera) {
  93131. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93132. }
  93133. }
  93134. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93135. get: function () {
  93136. return this._renderTargetTexture.samples;
  93137. },
  93138. set: function (value) {
  93139. this._renderTargetTexture.samples = value;
  93140. },
  93141. enumerable: true,
  93142. configurable: true
  93143. });
  93144. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93145. get: function () {
  93146. return this._renderTargetTexture.refreshRate;
  93147. },
  93148. set: function (value) {
  93149. this._renderTargetTexture.refreshRate = value;
  93150. },
  93151. enumerable: true,
  93152. configurable: true
  93153. });
  93154. ReflectionProbe.prototype.getScene = function () {
  93155. return this._scene;
  93156. };
  93157. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93158. get: function () {
  93159. return this._renderTargetTexture;
  93160. },
  93161. enumerable: true,
  93162. configurable: true
  93163. });
  93164. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93165. get: function () {
  93166. return this._renderTargetTexture.renderList;
  93167. },
  93168. enumerable: true,
  93169. configurable: true
  93170. });
  93171. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93172. this._attachedMesh = mesh;
  93173. };
  93174. /**
  93175. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93176. *
  93177. * @param renderingGroupId The rendering group id corresponding to its index
  93178. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93179. */
  93180. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93181. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93182. };
  93183. ReflectionProbe.prototype.dispose = function () {
  93184. var index = this._scene.reflectionProbes.indexOf(this);
  93185. if (index !== -1) {
  93186. // Remove from the scene if found
  93187. this._scene.reflectionProbes.splice(index, 1);
  93188. }
  93189. if (this._renderTargetTexture) {
  93190. this._renderTargetTexture.dispose();
  93191. this._renderTargetTexture = null;
  93192. }
  93193. };
  93194. return ReflectionProbe;
  93195. }());
  93196. BABYLON.ReflectionProbe = ReflectionProbe;
  93197. })(BABYLON || (BABYLON = {}));
  93198. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93199. var BABYLON;
  93200. (function (BABYLON) {
  93201. var Layer = /** @class */ (function () {
  93202. function Layer(name, imgUrl, scene, isBackground, color) {
  93203. this.name = name;
  93204. this.scale = new BABYLON.Vector2(1, 1);
  93205. this.offset = new BABYLON.Vector2(0, 0);
  93206. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93207. this.layerMask = 0x0FFFFFFF;
  93208. this._vertexBuffers = {};
  93209. // Events
  93210. /**
  93211. * An event triggered when the layer is disposed.
  93212. */
  93213. this.onDisposeObservable = new BABYLON.Observable();
  93214. /**
  93215. * An event triggered before rendering the scene
  93216. */
  93217. this.onBeforeRenderObservable = new BABYLON.Observable();
  93218. /**
  93219. * An event triggered after rendering the scene
  93220. */
  93221. this.onAfterRenderObservable = new BABYLON.Observable();
  93222. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93223. this.isBackground = isBackground === undefined ? true : isBackground;
  93224. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93225. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93226. this._scene.layers.push(this);
  93227. var engine = this._scene.getEngine();
  93228. // VBO
  93229. var vertices = [];
  93230. vertices.push(1, 1);
  93231. vertices.push(-1, 1);
  93232. vertices.push(-1, -1);
  93233. vertices.push(1, -1);
  93234. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93235. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93236. this._createIndexBuffer();
  93237. // Effects
  93238. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93239. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93240. }
  93241. Object.defineProperty(Layer.prototype, "onDispose", {
  93242. set: function (callback) {
  93243. if (this._onDisposeObserver) {
  93244. this.onDisposeObservable.remove(this._onDisposeObserver);
  93245. }
  93246. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93247. },
  93248. enumerable: true,
  93249. configurable: true
  93250. });
  93251. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93252. set: function (callback) {
  93253. if (this._onBeforeRenderObserver) {
  93254. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93255. }
  93256. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93257. },
  93258. enumerable: true,
  93259. configurable: true
  93260. });
  93261. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93262. set: function (callback) {
  93263. if (this._onAfterRenderObserver) {
  93264. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93265. }
  93266. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93267. },
  93268. enumerable: true,
  93269. configurable: true
  93270. });
  93271. Layer.prototype._createIndexBuffer = function () {
  93272. var engine = this._scene.getEngine();
  93273. // Indices
  93274. var indices = [];
  93275. indices.push(0);
  93276. indices.push(1);
  93277. indices.push(2);
  93278. indices.push(0);
  93279. indices.push(2);
  93280. indices.push(3);
  93281. this._indexBuffer = engine.createIndexBuffer(indices);
  93282. };
  93283. Layer.prototype._rebuild = function () {
  93284. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93285. if (vb) {
  93286. vb._rebuild();
  93287. }
  93288. this._createIndexBuffer();
  93289. };
  93290. Layer.prototype.render = function () {
  93291. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93292. // Check
  93293. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93294. return;
  93295. var engine = this._scene.getEngine();
  93296. this.onBeforeRenderObservable.notifyObservers(this);
  93297. // Render
  93298. engine.enableEffect(currentEffect);
  93299. engine.setState(false);
  93300. // Texture
  93301. currentEffect.setTexture("textureSampler", this.texture);
  93302. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93303. // Color
  93304. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93305. // Scale / offset
  93306. currentEffect.setVector2("offset", this.offset);
  93307. currentEffect.setVector2("scale", this.scale);
  93308. // VBOs
  93309. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93310. // Draw order
  93311. if (!this.alphaTest) {
  93312. engine.setAlphaMode(this.alphaBlendingMode);
  93313. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93314. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93315. }
  93316. else {
  93317. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93318. }
  93319. this.onAfterRenderObservable.notifyObservers(this);
  93320. };
  93321. Layer.prototype.dispose = function () {
  93322. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93323. if (vertexBuffer) {
  93324. vertexBuffer.dispose();
  93325. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93326. }
  93327. if (this._indexBuffer) {
  93328. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93329. this._indexBuffer = null;
  93330. }
  93331. if (this.texture) {
  93332. this.texture.dispose();
  93333. this.texture = null;
  93334. }
  93335. // Remove from scene
  93336. var index = this._scene.layers.indexOf(this);
  93337. this._scene.layers.splice(index, 1);
  93338. // Callback
  93339. this.onDisposeObservable.notifyObservers(this);
  93340. this.onDisposeObservable.clear();
  93341. this.onAfterRenderObservable.clear();
  93342. this.onBeforeRenderObservable.clear();
  93343. };
  93344. return Layer;
  93345. }());
  93346. BABYLON.Layer = Layer;
  93347. })(BABYLON || (BABYLON = {}));
  93348. //# sourceMappingURL=babylon.layer.js.map
  93349. var BABYLON;
  93350. (function (BABYLON) {
  93351. var TextureTools = /** @class */ (function () {
  93352. function TextureTools() {
  93353. }
  93354. /**
  93355. * Uses the GPU to create a copy texture rescaled at a given size
  93356. * @param texture Texture to copy from
  93357. * @param width Desired width
  93358. * @param height Desired height
  93359. * @return Generated texture
  93360. */
  93361. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93362. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93363. var scene = texture.getScene();
  93364. var engine = scene.getEngine();
  93365. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93366. rtt.wrapU = texture.wrapU;
  93367. rtt.wrapV = texture.wrapV;
  93368. rtt.uOffset = texture.uOffset;
  93369. rtt.vOffset = texture.vOffset;
  93370. rtt.uScale = texture.uScale;
  93371. rtt.vScale = texture.vScale;
  93372. rtt.uAng = texture.uAng;
  93373. rtt.vAng = texture.vAng;
  93374. rtt.wAng = texture.wAng;
  93375. rtt.coordinatesIndex = texture.coordinatesIndex;
  93376. rtt.level = texture.level;
  93377. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93378. rtt._texture.isReady = false;
  93379. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93380. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93381. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93382. passPostProcess.getEffect().executeWhenCompiled(function () {
  93383. passPostProcess.onApply = function (effect) {
  93384. effect.setTexture("textureSampler", texture);
  93385. };
  93386. var internalTexture = rtt.getInternalTexture();
  93387. if (internalTexture) {
  93388. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93389. engine.unBindFramebuffer(internalTexture);
  93390. rtt.disposeFramebufferObjects();
  93391. passPostProcess.dispose();
  93392. internalTexture.isReady = true;
  93393. }
  93394. });
  93395. return rtt;
  93396. };
  93397. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93398. if (!scene._environmentBRDFTexture) {
  93399. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93400. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93401. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93402. scene._environmentBRDFTexture = texture;
  93403. }
  93404. return scene._environmentBRDFTexture;
  93405. };
  93406. 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=";
  93407. return TextureTools;
  93408. }());
  93409. BABYLON.TextureTools = TextureTools;
  93410. })(BABYLON || (BABYLON = {}));
  93411. //# sourceMappingURL=babylon.textureTools.js.map
  93412. var BABYLON;
  93413. (function (BABYLON) {
  93414. var FramingBehavior = /** @class */ (function () {
  93415. function FramingBehavior() {
  93416. this._mode = FramingBehavior.FitFrustumSidesMode;
  93417. this._radiusScale = 1.0;
  93418. this._positionScale = 0.5;
  93419. this._defaultElevation = 0.3;
  93420. this._elevationReturnTime = 1500;
  93421. this._elevationReturnWaitTime = 1000;
  93422. this._zoomStopsAnimation = false;
  93423. this._framingTime = 1500;
  93424. this._isPointerDown = false;
  93425. this._lastInteractionTime = -Infinity;
  93426. // Framing control
  93427. this._animatables = new Array();
  93428. this._betaIsAnimating = false;
  93429. }
  93430. Object.defineProperty(FramingBehavior.prototype, "name", {
  93431. get: function () {
  93432. return "Framing";
  93433. },
  93434. enumerable: true,
  93435. configurable: true
  93436. });
  93437. Object.defineProperty(FramingBehavior.prototype, "mode", {
  93438. /**
  93439. * Gets current mode used by the behavior.
  93440. */
  93441. get: function () {
  93442. return this._mode;
  93443. },
  93444. /**
  93445. * Sets the current mode used by the behavior
  93446. */
  93447. set: function (mode) {
  93448. this._mode = mode;
  93449. },
  93450. enumerable: true,
  93451. configurable: true
  93452. });
  93453. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  93454. /**
  93455. * Gets the scale applied to the radius
  93456. */
  93457. get: function () {
  93458. return this._radiusScale;
  93459. },
  93460. /**
  93461. * Sets the scale applied to the radius (1 by default)
  93462. */
  93463. set: function (radius) {
  93464. this._radiusScale = radius;
  93465. },
  93466. enumerable: true,
  93467. configurable: true
  93468. });
  93469. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  93470. /**
  93471. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93472. */
  93473. get: function () {
  93474. return this._positionScale;
  93475. },
  93476. /**
  93477. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93478. */
  93479. set: function (scale) {
  93480. this._positionScale = scale;
  93481. },
  93482. enumerable: true,
  93483. configurable: true
  93484. });
  93485. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  93486. /**
  93487. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93488. * behaviour is triggered, in radians.
  93489. */
  93490. get: function () {
  93491. return this._defaultElevation;
  93492. },
  93493. /**
  93494. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93495. * behaviour is triggered, in radians.
  93496. */
  93497. set: function (elevation) {
  93498. this._defaultElevation = elevation;
  93499. },
  93500. enumerable: true,
  93501. configurable: true
  93502. });
  93503. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  93504. /**
  93505. * Gets the time (in milliseconds) taken to return to the default beta position.
  93506. * Negative value indicates camera should not return to default.
  93507. */
  93508. get: function () {
  93509. return this._elevationReturnTime;
  93510. },
  93511. /**
  93512. * Sets the time (in milliseconds) taken to return to the default beta position.
  93513. * Negative value indicates camera should not return to default.
  93514. */
  93515. set: function (speed) {
  93516. this._elevationReturnTime = speed;
  93517. },
  93518. enumerable: true,
  93519. configurable: true
  93520. });
  93521. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  93522. /**
  93523. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93524. */
  93525. get: function () {
  93526. return this._elevationReturnWaitTime;
  93527. },
  93528. /**
  93529. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93530. */
  93531. set: function (time) {
  93532. this._elevationReturnWaitTime = time;
  93533. },
  93534. enumerable: true,
  93535. configurable: true
  93536. });
  93537. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  93538. /**
  93539. * Gets the flag that indicates if user zooming should stop animation.
  93540. */
  93541. get: function () {
  93542. return this._zoomStopsAnimation;
  93543. },
  93544. /**
  93545. * Sets the flag that indicates if user zooming should stop animation.
  93546. */
  93547. set: function (flag) {
  93548. this._zoomStopsAnimation = flag;
  93549. },
  93550. enumerable: true,
  93551. configurable: true
  93552. });
  93553. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  93554. /**
  93555. * Gets the transition time when framing the mesh, in milliseconds
  93556. */
  93557. get: function () {
  93558. return this._framingTime;
  93559. },
  93560. /**
  93561. * Sets the transition time when framing the mesh, in milliseconds
  93562. */
  93563. set: function (time) {
  93564. this._framingTime = time;
  93565. },
  93566. enumerable: true,
  93567. configurable: true
  93568. });
  93569. FramingBehavior.prototype.init = function () {
  93570. // Do notihng
  93571. };
  93572. FramingBehavior.prototype.attach = function (camera) {
  93573. var _this = this;
  93574. this._attachedCamera = camera;
  93575. var scene = this._attachedCamera.getScene();
  93576. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  93577. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93578. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93579. _this._isPointerDown = true;
  93580. return;
  93581. }
  93582. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93583. _this._isPointerDown = false;
  93584. }
  93585. });
  93586. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93587. if (mesh) {
  93588. _this.zoomOnMesh(mesh);
  93589. }
  93590. });
  93591. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93592. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93593. _this._applyUserInteraction();
  93594. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  93595. // back to the default position after a given timeout
  93596. _this._maintainCameraAboveGround();
  93597. });
  93598. };
  93599. FramingBehavior.prototype.detach = function () {
  93600. if (!this._attachedCamera) {
  93601. return;
  93602. }
  93603. var scene = this._attachedCamera.getScene();
  93604. if (this._onPrePointerObservableObserver) {
  93605. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  93606. }
  93607. if (this._onAfterCheckInputsObserver) {
  93608. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93609. }
  93610. if (this._onMeshTargetChangedObserver) {
  93611. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93612. }
  93613. this._attachedCamera = null;
  93614. };
  93615. /**
  93616. * Targets the given mesh and updates zoom level accordingly.
  93617. * @param mesh The mesh to target.
  93618. * @param radius Optional. If a cached radius position already exists, overrides default.
  93619. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93620. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93621. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93622. */
  93623. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93624. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93625. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93626. mesh.computeWorldMatrix(true);
  93627. var boundingBox = mesh.getBoundingInfo().boundingBox;
  93628. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  93629. };
  93630. /**
  93631. * Targets the given mesh with its children and updates zoom level accordingly.
  93632. * @param mesh The mesh to target.
  93633. * @param radius Optional. If a cached radius position already exists, overrides default.
  93634. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93635. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93636. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93637. */
  93638. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93639. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93640. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93641. mesh.computeWorldMatrix(true);
  93642. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  93643. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  93644. };
  93645. /**
  93646. * Targets the given meshes with their children and updates zoom level accordingly.
  93647. * @param meshes The mesh to target.
  93648. * @param radius Optional. If a cached radius position already exists, overrides default.
  93649. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93650. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93651. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93652. */
  93653. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  93654. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93655. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93656. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  93657. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  93658. for (var i = 0; i < meshes.length; i++) {
  93659. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  93660. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  93661. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  93662. }
  93663. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  93664. };
  93665. /**
  93666. * Targets the given mesh and updates zoom level accordingly.
  93667. * @param mesh The mesh to target.
  93668. * @param radius Optional. If a cached radius position already exists, overrides default.
  93669. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93670. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93671. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93672. */
  93673. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  93674. var _this = this;
  93675. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93676. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93677. var zoomTarget;
  93678. if (!this._attachedCamera) {
  93679. return;
  93680. }
  93681. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  93682. var bottom = minimumWorld.y;
  93683. var top = maximumWorld.y;
  93684. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  93685. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  93686. if (focusOnOriginXZ) {
  93687. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  93688. }
  93689. else {
  93690. var centerWorld = minimumWorld.add(radiusWorld);
  93691. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  93692. }
  93693. if (!this._vectorTransition) {
  93694. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  93695. }
  93696. this._betaIsAnimating = true;
  93697. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  93698. if (animatable) {
  93699. this._animatables.push(animatable);
  93700. }
  93701. // sets the radius and lower radius bounds
  93702. // Small delta ensures camera is not always at lower zoom limit.
  93703. var radius = 0;
  93704. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  93705. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93706. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  93707. radius = position;
  93708. }
  93709. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93710. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93711. if (this._attachedCamera.lowerRadiusLimit === null) {
  93712. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  93713. }
  93714. }
  93715. // Set sensibilities
  93716. var extend = maximumWorld.subtract(minimumWorld).length();
  93717. this._attachedCamera.panningSensibility = 5000 / extend;
  93718. this._attachedCamera.wheelPrecision = 100 / radius;
  93719. // transition to new radius
  93720. if (!this._radiusTransition) {
  93721. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93722. }
  93723. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  93724. _this.stopAllAnimations();
  93725. if (onAnimationEnd) {
  93726. onAnimationEnd();
  93727. }
  93728. if (_this._attachedCamera) {
  93729. _this._attachedCamera.storeState();
  93730. }
  93731. });
  93732. if (animatable) {
  93733. this._animatables.push(animatable);
  93734. }
  93735. };
  93736. /**
  93737. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  93738. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  93739. * frustum width.
  93740. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  93741. * to fully enclose the mesh in the viewing frustum.
  93742. */
  93743. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  93744. var size = maximumWorld.subtract(minimumWorld);
  93745. var boxVectorGlobalDiagonal = size.length();
  93746. var frustumSlope = this._getFrustumSlope();
  93747. // Formula for setting distance
  93748. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  93749. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  93750. // Horizon distance
  93751. var radius = radiusWithoutFraming * this._radiusScale;
  93752. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  93753. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  93754. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  93755. var camera = this._attachedCamera;
  93756. if (!camera) {
  93757. return 0;
  93758. }
  93759. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93760. // Don't exceed the requested limit
  93761. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  93762. }
  93763. // Don't exceed the upper radius limit
  93764. if (camera.upperRadiusLimit) {
  93765. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  93766. }
  93767. return distance;
  93768. };
  93769. /**
  93770. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  93771. * is automatically returned to its default position (expected to be above ground plane).
  93772. */
  93773. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  93774. var _this = this;
  93775. if (this._elevationReturnTime < 0) {
  93776. return;
  93777. }
  93778. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  93779. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  93780. var limitBeta = Math.PI * 0.5;
  93781. // Bring the camera back up if below the ground plane
  93782. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  93783. this._betaIsAnimating = true;
  93784. //Transition to new position
  93785. this.stopAllAnimations();
  93786. if (!this._betaTransition) {
  93787. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93788. }
  93789. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  93790. _this._clearAnimationLocks();
  93791. _this.stopAllAnimations();
  93792. });
  93793. if (animatabe) {
  93794. this._animatables.push(animatabe);
  93795. }
  93796. }
  93797. };
  93798. /**
  93799. * Returns the frustum slope based on the canvas ratio and camera FOV
  93800. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  93801. */
  93802. FramingBehavior.prototype._getFrustumSlope = function () {
  93803. // Calculate the viewport ratio
  93804. // Aspect Ratio is Height/Width.
  93805. var camera = this._attachedCamera;
  93806. if (!camera) {
  93807. return BABYLON.Vector2.Zero();
  93808. }
  93809. var engine = camera.getScene().getEngine();
  93810. var aspectRatio = engine.getAspectRatio(camera);
  93811. // Camera FOV is the vertical field of view (top-bottom) in radians.
  93812. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  93813. var frustumSlopeY = Math.tan(camera.fov / 2);
  93814. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  93815. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  93816. // along the forward vector.
  93817. var frustumSlopeX = frustumSlopeY * aspectRatio;
  93818. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  93819. };
  93820. /**
  93821. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  93822. */
  93823. FramingBehavior.prototype._clearAnimationLocks = function () {
  93824. this._betaIsAnimating = false;
  93825. };
  93826. /**
  93827. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93828. */
  93829. FramingBehavior.prototype._applyUserInteraction = function () {
  93830. if (this.isUserIsMoving) {
  93831. this._lastInteractionTime = BABYLON.Tools.Now;
  93832. this.stopAllAnimations();
  93833. this._clearAnimationLocks();
  93834. }
  93835. };
  93836. /**
  93837. * Stops and removes all animations that have been applied to the camera
  93838. */
  93839. FramingBehavior.prototype.stopAllAnimations = function () {
  93840. if (this._attachedCamera) {
  93841. this._attachedCamera.animations = [];
  93842. }
  93843. while (this._animatables.length) {
  93844. if (this._animatables[0]) {
  93845. this._animatables[0].onAnimationEnd = null;
  93846. this._animatables[0].stop();
  93847. }
  93848. this._animatables.shift();
  93849. }
  93850. };
  93851. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  93852. /**
  93853. * Gets a value indicating if the user is moving the camera
  93854. */
  93855. get: function () {
  93856. if (!this._attachedCamera) {
  93857. return false;
  93858. }
  93859. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93860. this._attachedCamera.inertialBetaOffset !== 0 ||
  93861. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93862. this._attachedCamera.inertialPanningX !== 0 ||
  93863. this._attachedCamera.inertialPanningY !== 0 ||
  93864. this._isPointerDown;
  93865. },
  93866. enumerable: true,
  93867. configurable: true
  93868. });
  93869. /**
  93870. * The easing function used by animations
  93871. */
  93872. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  93873. /**
  93874. * The easing mode used by animations
  93875. */
  93876. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  93877. // Statics
  93878. /**
  93879. * The camera can move all the way towards the mesh.
  93880. */
  93881. FramingBehavior.IgnoreBoundsSizeMode = 0;
  93882. /**
  93883. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  93884. */
  93885. FramingBehavior.FitFrustumSidesMode = 1;
  93886. return FramingBehavior;
  93887. }());
  93888. BABYLON.FramingBehavior = FramingBehavior;
  93889. })(BABYLON || (BABYLON = {}));
  93890. //# sourceMappingURL=babylon.framingBehavior.js.map
  93891. var BABYLON;
  93892. (function (BABYLON) {
  93893. /**
  93894. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  93895. */
  93896. var BouncingBehavior = /** @class */ (function () {
  93897. function BouncingBehavior() {
  93898. /**
  93899. * The duration of the animation, in milliseconds
  93900. */
  93901. this.transitionDuration = 450;
  93902. /**
  93903. * Length of the distance animated by the transition when lower radius is reached
  93904. */
  93905. this.lowerRadiusTransitionRange = 2;
  93906. /**
  93907. * Length of the distance animated by the transition when upper radius is reached
  93908. */
  93909. this.upperRadiusTransitionRange = -2;
  93910. this._autoTransitionRange = false;
  93911. // Animations
  93912. this._radiusIsAnimating = false;
  93913. this._radiusBounceTransition = null;
  93914. this._animatables = new Array();
  93915. }
  93916. Object.defineProperty(BouncingBehavior.prototype, "name", {
  93917. get: function () {
  93918. return "Bouncing";
  93919. },
  93920. enumerable: true,
  93921. configurable: true
  93922. });
  93923. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  93924. /**
  93925. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93926. */
  93927. get: function () {
  93928. return this._autoTransitionRange;
  93929. },
  93930. /**
  93931. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93932. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  93933. */
  93934. set: function (value) {
  93935. var _this = this;
  93936. if (this._autoTransitionRange === value) {
  93937. return;
  93938. }
  93939. this._autoTransitionRange = value;
  93940. var camera = this._attachedCamera;
  93941. if (!camera) {
  93942. return;
  93943. }
  93944. if (value) {
  93945. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93946. if (!mesh) {
  93947. return;
  93948. }
  93949. mesh.computeWorldMatrix(true);
  93950. var diagonal = mesh.getBoundingInfo().diagonalLength;
  93951. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  93952. _this.upperRadiusTransitionRange = diagonal * 0.05;
  93953. });
  93954. }
  93955. else if (this._onMeshTargetChangedObserver) {
  93956. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93957. }
  93958. },
  93959. enumerable: true,
  93960. configurable: true
  93961. });
  93962. BouncingBehavior.prototype.init = function () {
  93963. // Do notihng
  93964. };
  93965. BouncingBehavior.prototype.attach = function (camera) {
  93966. var _this = this;
  93967. this._attachedCamera = camera;
  93968. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93969. if (!_this._attachedCamera) {
  93970. return;
  93971. }
  93972. // Add the bounce animation to the lower radius limit
  93973. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  93974. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  93975. }
  93976. // Add the bounce animation to the upper radius limit
  93977. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  93978. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  93979. }
  93980. });
  93981. };
  93982. BouncingBehavior.prototype.detach = function () {
  93983. if (!this._attachedCamera) {
  93984. return;
  93985. }
  93986. if (this._onAfterCheckInputsObserver) {
  93987. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93988. }
  93989. if (this._onMeshTargetChangedObserver) {
  93990. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93991. }
  93992. this._attachedCamera = null;
  93993. };
  93994. /**
  93995. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  93996. * @param radiusLimit The limit to check against.
  93997. * @return Bool to indicate if at limit.
  93998. */
  93999. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94000. if (!this._attachedCamera) {
  94001. return false;
  94002. }
  94003. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94004. return true;
  94005. }
  94006. return false;
  94007. };
  94008. /**
  94009. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94010. * @param radiusDelta The delta by which to animate to. Can be negative.
  94011. */
  94012. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94013. var _this = this;
  94014. if (!this._attachedCamera) {
  94015. return;
  94016. }
  94017. if (!this._radiusBounceTransition) {
  94018. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94019. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94020. }
  94021. // Prevent zoom until bounce has completed
  94022. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94023. this._attachedCamera.wheelPrecision = Infinity;
  94024. this._attachedCamera.inertialRadiusOffset = 0;
  94025. // Animate to the radius limit
  94026. this.stopAllAnimations();
  94027. this._radiusIsAnimating = true;
  94028. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94029. if (animatable) {
  94030. this._animatables.push(animatable);
  94031. }
  94032. };
  94033. /**
  94034. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94035. */
  94036. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94037. this._radiusIsAnimating = false;
  94038. if (this._attachedCamera) {
  94039. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94040. }
  94041. };
  94042. /**
  94043. * Stops and removes all animations that have been applied to the camera
  94044. */
  94045. BouncingBehavior.prototype.stopAllAnimations = function () {
  94046. if (this._attachedCamera) {
  94047. this._attachedCamera.animations = [];
  94048. }
  94049. while (this._animatables.length) {
  94050. this._animatables[0].onAnimationEnd = null;
  94051. this._animatables[0].stop();
  94052. this._animatables.shift();
  94053. }
  94054. };
  94055. /**
  94056. * The easing function used by animations
  94057. */
  94058. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94059. /**
  94060. * The easing mode used by animations
  94061. */
  94062. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94063. return BouncingBehavior;
  94064. }());
  94065. BABYLON.BouncingBehavior = BouncingBehavior;
  94066. })(BABYLON || (BABYLON = {}));
  94067. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94068. var BABYLON;
  94069. (function (BABYLON) {
  94070. var AutoRotationBehavior = /** @class */ (function () {
  94071. function AutoRotationBehavior() {
  94072. this._zoomStopsAnimation = false;
  94073. this._idleRotationSpeed = 0.05;
  94074. this._idleRotationWaitTime = 2000;
  94075. this._idleRotationSpinupTime = 2000;
  94076. this._isPointerDown = false;
  94077. this._lastFrameTime = null;
  94078. this._lastInteractionTime = -Infinity;
  94079. this._cameraRotationSpeed = 0;
  94080. this._lastFrameRadius = 0;
  94081. }
  94082. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94083. get: function () {
  94084. return "AutoRotation";
  94085. },
  94086. enumerable: true,
  94087. configurable: true
  94088. });
  94089. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94090. /**
  94091. * Gets the flag that indicates if user zooming should stop animation.
  94092. */
  94093. get: function () {
  94094. return this._zoomStopsAnimation;
  94095. },
  94096. /**
  94097. * Sets the flag that indicates if user zooming should stop animation.
  94098. */
  94099. set: function (flag) {
  94100. this._zoomStopsAnimation = flag;
  94101. },
  94102. enumerable: true,
  94103. configurable: true
  94104. });
  94105. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94106. /**
  94107. * Gets the default speed at which the camera rotates around the model.
  94108. */
  94109. get: function () {
  94110. return this._idleRotationSpeed;
  94111. },
  94112. /**
  94113. * Sets the default speed at which the camera rotates around the model.
  94114. */
  94115. set: function (speed) {
  94116. this._idleRotationSpeed = speed;
  94117. },
  94118. enumerable: true,
  94119. configurable: true
  94120. });
  94121. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94122. /**
  94123. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94124. */
  94125. get: function () {
  94126. return this._idleRotationWaitTime;
  94127. },
  94128. /**
  94129. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94130. */
  94131. set: function (time) {
  94132. this._idleRotationWaitTime = time;
  94133. },
  94134. enumerable: true,
  94135. configurable: true
  94136. });
  94137. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94138. /**
  94139. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94140. */
  94141. get: function () {
  94142. return this._idleRotationSpinupTime;
  94143. },
  94144. /**
  94145. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94146. */
  94147. set: function (time) {
  94148. this._idleRotationSpinupTime = time;
  94149. },
  94150. enumerable: true,
  94151. configurable: true
  94152. });
  94153. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94154. /**
  94155. * Gets a value indicating if the camera is currently rotating because of this behavior
  94156. */
  94157. get: function () {
  94158. return Math.abs(this._cameraRotationSpeed) > 0;
  94159. },
  94160. enumerable: true,
  94161. configurable: true
  94162. });
  94163. AutoRotationBehavior.prototype.init = function () {
  94164. // Do notihng
  94165. };
  94166. AutoRotationBehavior.prototype.attach = function (camera) {
  94167. var _this = this;
  94168. this._attachedCamera = camera;
  94169. var scene = this._attachedCamera.getScene();
  94170. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94171. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94172. _this._isPointerDown = true;
  94173. return;
  94174. }
  94175. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94176. _this._isPointerDown = false;
  94177. }
  94178. });
  94179. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94180. var now = BABYLON.Tools.Now;
  94181. var dt = 0;
  94182. if (_this._lastFrameTime != null) {
  94183. dt = now - _this._lastFrameTime;
  94184. }
  94185. _this._lastFrameTime = now;
  94186. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94187. _this._applyUserInteraction();
  94188. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94189. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94190. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94191. // Step camera rotation by rotation speed
  94192. if (_this._attachedCamera) {
  94193. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94194. }
  94195. });
  94196. };
  94197. AutoRotationBehavior.prototype.detach = function () {
  94198. if (!this._attachedCamera) {
  94199. return;
  94200. }
  94201. var scene = this._attachedCamera.getScene();
  94202. if (this._onPrePointerObservableObserver) {
  94203. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94204. }
  94205. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94206. this._attachedCamera = null;
  94207. };
  94208. /**
  94209. * Returns true if user is scrolling.
  94210. * @return true if user is scrolling.
  94211. */
  94212. AutoRotationBehavior.prototype._userIsZooming = function () {
  94213. if (!this._attachedCamera) {
  94214. return false;
  94215. }
  94216. return this._attachedCamera.inertialRadiusOffset !== 0;
  94217. };
  94218. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94219. if (!this._attachedCamera) {
  94220. return false;
  94221. }
  94222. var zoomHasHitLimit = false;
  94223. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94224. zoomHasHitLimit = true;
  94225. }
  94226. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94227. this._lastFrameRadius = this._attachedCamera.radius;
  94228. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94229. };
  94230. /**
  94231. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94232. */
  94233. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94234. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94235. this._lastInteractionTime = BABYLON.Tools.Now;
  94236. }
  94237. };
  94238. // Tools
  94239. AutoRotationBehavior.prototype._userIsMoving = function () {
  94240. if (!this._attachedCamera) {
  94241. return false;
  94242. }
  94243. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94244. this._attachedCamera.inertialBetaOffset !== 0 ||
  94245. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94246. this._attachedCamera.inertialPanningX !== 0 ||
  94247. this._attachedCamera.inertialPanningY !== 0 ||
  94248. this._isPointerDown;
  94249. };
  94250. return AutoRotationBehavior;
  94251. }());
  94252. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94253. })(BABYLON || (BABYLON = {}));
  94254. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94255. var BABYLON;
  94256. (function (BABYLON) {
  94257. var NullEngineOptions = /** @class */ (function () {
  94258. function NullEngineOptions() {
  94259. this.renderWidth = 512;
  94260. this.renderHeight = 256;
  94261. this.textureSize = 512;
  94262. this.deterministicLockstep = false;
  94263. this.lockstepMaxSteps = 4;
  94264. }
  94265. return NullEngineOptions;
  94266. }());
  94267. BABYLON.NullEngineOptions = NullEngineOptions;
  94268. /**
  94269. * The null engine class provides support for headless version of babylon.js.
  94270. * This can be used in server side scenario or for testing purposes
  94271. */
  94272. var NullEngine = /** @class */ (function (_super) {
  94273. __extends(NullEngine, _super);
  94274. function NullEngine(options) {
  94275. if (options === void 0) { options = new NullEngineOptions(); }
  94276. var _this = _super.call(this, null) || this;
  94277. if (options.deterministicLockstep === undefined) {
  94278. options.deterministicLockstep = false;
  94279. }
  94280. if (options.lockstepMaxSteps === undefined) {
  94281. options.lockstepMaxSteps = 4;
  94282. }
  94283. _this._options = options;
  94284. // Init caps
  94285. // We consider we are on a webgl1 capable device
  94286. _this._caps = new BABYLON.EngineCapabilities();
  94287. _this._caps.maxTexturesImageUnits = 16;
  94288. _this._caps.maxVertexTextureImageUnits = 16;
  94289. _this._caps.maxTextureSize = 512;
  94290. _this._caps.maxCubemapTextureSize = 512;
  94291. _this._caps.maxRenderTextureSize = 512;
  94292. _this._caps.maxVertexAttribs = 16;
  94293. _this._caps.maxVaryingVectors = 16;
  94294. _this._caps.maxFragmentUniformVectors = 16;
  94295. _this._caps.maxVertexUniformVectors = 16;
  94296. // Extensions
  94297. _this._caps.standardDerivatives = false;
  94298. _this._caps.astc = null;
  94299. _this._caps.s3tc = null;
  94300. _this._caps.pvrtc = null;
  94301. _this._caps.etc1 = null;
  94302. _this._caps.etc2 = null;
  94303. _this._caps.textureAnisotropicFilterExtension = null;
  94304. _this._caps.maxAnisotropy = 0;
  94305. _this._caps.uintIndices = false;
  94306. _this._caps.fragmentDepthSupported = false;
  94307. _this._caps.highPrecisionShaderSupported = true;
  94308. _this._caps.colorBufferFloat = false;
  94309. _this._caps.textureFloat = false;
  94310. _this._caps.textureFloatLinearFiltering = false;
  94311. _this._caps.textureFloatRender = false;
  94312. _this._caps.textureHalfFloat = false;
  94313. _this._caps.textureHalfFloatLinearFiltering = false;
  94314. _this._caps.textureHalfFloatRender = false;
  94315. _this._caps.textureLOD = false;
  94316. _this._caps.drawBuffersExtension = false;
  94317. _this._caps.depthTextureExtension = false;
  94318. _this._caps.vertexArrayObject = false;
  94319. _this._caps.instancedArrays = false;
  94320. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94321. // Wrappers
  94322. if (typeof URL === "undefined") {
  94323. URL = {
  94324. createObjectURL: function () { },
  94325. revokeObjectURL: function () { }
  94326. };
  94327. }
  94328. if (typeof Blob === "undefined") {
  94329. Blob = function () { };
  94330. }
  94331. return _this;
  94332. }
  94333. NullEngine.prototype.isDeterministicLockStep = function () {
  94334. return this._options.deterministicLockstep;
  94335. };
  94336. NullEngine.prototype.getLockstepMaxSteps = function () {
  94337. return this._options.lockstepMaxSteps;
  94338. };
  94339. NullEngine.prototype.getHardwareScalingLevel = function () {
  94340. return 1.0;
  94341. };
  94342. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94343. return {
  94344. capacity: 0,
  94345. references: 1,
  94346. is32Bits: false
  94347. };
  94348. };
  94349. NullEngine.prototype.createIndexBuffer = function (indices) {
  94350. return {
  94351. capacity: 0,
  94352. references: 1,
  94353. is32Bits: false
  94354. };
  94355. };
  94356. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94357. if (stencil === void 0) { stencil = false; }
  94358. };
  94359. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94360. if (useScreen === void 0) { useScreen = false; }
  94361. if (!useScreen && this._currentRenderTarget) {
  94362. return this._currentRenderTarget.width;
  94363. }
  94364. return this._options.renderWidth;
  94365. };
  94366. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94367. if (useScreen === void 0) { useScreen = false; }
  94368. if (!useScreen && this._currentRenderTarget) {
  94369. return this._currentRenderTarget.height;
  94370. }
  94371. return this._options.renderHeight;
  94372. };
  94373. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94374. this._cachedViewport = viewport;
  94375. };
  94376. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94377. return {
  94378. transformFeedback: null,
  94379. __SPECTOR_rebuildProgram: null
  94380. };
  94381. };
  94382. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94383. return [];
  94384. };
  94385. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94386. return [];
  94387. };
  94388. NullEngine.prototype.bindSamplers = function (effect) {
  94389. this._currentEffect = null;
  94390. };
  94391. NullEngine.prototype.enableEffect = function (effect) {
  94392. this._currentEffect = effect;
  94393. if (effect.onBind) {
  94394. effect.onBind(effect);
  94395. }
  94396. effect.onBindObservable.notifyObservers(effect);
  94397. };
  94398. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94399. if (zOffset === void 0) { zOffset = 0; }
  94400. if (reverseSide === void 0) { reverseSide = false; }
  94401. };
  94402. NullEngine.prototype.setIntArray = function (uniform, array) {
  94403. };
  94404. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94405. };
  94406. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94407. };
  94408. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94409. };
  94410. NullEngine.prototype.setFloatArray = function (uniform, array) {
  94411. };
  94412. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  94413. };
  94414. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  94415. };
  94416. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  94417. };
  94418. NullEngine.prototype.setArray = function (uniform, array) {
  94419. };
  94420. NullEngine.prototype.setArray2 = function (uniform, array) {
  94421. };
  94422. NullEngine.prototype.setArray3 = function (uniform, array) {
  94423. };
  94424. NullEngine.prototype.setArray4 = function (uniform, array) {
  94425. };
  94426. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  94427. };
  94428. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  94429. };
  94430. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  94431. };
  94432. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  94433. };
  94434. NullEngine.prototype.setFloat = function (uniform, value) {
  94435. };
  94436. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  94437. };
  94438. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  94439. };
  94440. NullEngine.prototype.setBool = function (uniform, bool) {
  94441. };
  94442. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  94443. };
  94444. NullEngine.prototype.setColor3 = function (uniform, color3) {
  94445. };
  94446. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  94447. };
  94448. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  94449. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  94450. if (this._alphaMode === mode) {
  94451. return;
  94452. }
  94453. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  94454. if (!noDepthWriteChange) {
  94455. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  94456. }
  94457. this._alphaMode = mode;
  94458. };
  94459. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  94460. };
  94461. NullEngine.prototype.wipeCaches = function (bruteForce) {
  94462. if (this.preventCacheWipeBetweenFrames) {
  94463. return;
  94464. }
  94465. this.resetTextureCache();
  94466. this._currentEffect = null;
  94467. if (bruteForce) {
  94468. this._currentProgram = null;
  94469. this._stencilState.reset();
  94470. this._depthCullingState.reset();
  94471. this._alphaState.reset();
  94472. }
  94473. this._cachedVertexBuffers = null;
  94474. this._cachedIndexBuffer = null;
  94475. this._cachedEffectForVertexBuffers = null;
  94476. };
  94477. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  94478. };
  94479. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  94480. };
  94481. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  94482. };
  94483. NullEngine.prototype._createTexture = function () {
  94484. return {};
  94485. };
  94486. NullEngine.prototype._releaseTexture = function (texture) {
  94487. };
  94488. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  94489. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94490. if (onLoad === void 0) { onLoad = null; }
  94491. if (onError === void 0) { onError = null; }
  94492. if (buffer === void 0) { buffer = null; }
  94493. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  94494. var url = String(urlArg);
  94495. texture.url = url;
  94496. texture.generateMipMaps = !noMipmap;
  94497. texture.samplingMode = samplingMode;
  94498. texture.invertY = invertY;
  94499. texture.baseWidth = this._options.textureSize;
  94500. texture.baseHeight = this._options.textureSize;
  94501. texture.width = this._options.textureSize;
  94502. texture.height = this._options.textureSize;
  94503. if (format) {
  94504. texture.format = format;
  94505. }
  94506. texture.isReady = true;
  94507. if (onLoad) {
  94508. onLoad();
  94509. }
  94510. return texture;
  94511. };
  94512. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  94513. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  94514. if (options !== undefined && typeof options === "object") {
  94515. fullOptions.generateMipMaps = options.generateMipMaps;
  94516. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  94517. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  94518. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  94519. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  94520. }
  94521. else {
  94522. fullOptions.generateMipMaps = options;
  94523. fullOptions.generateDepthBuffer = true;
  94524. fullOptions.generateStencilBuffer = false;
  94525. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94526. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  94527. }
  94528. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  94529. var width = size.width || size;
  94530. var height = size.height || size;
  94531. texture._depthStencilBuffer = {};
  94532. texture._framebuffer = {};
  94533. texture.baseWidth = width;
  94534. texture.baseHeight = height;
  94535. texture.width = width;
  94536. texture.height = height;
  94537. texture.isReady = true;
  94538. texture.samples = 1;
  94539. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  94540. texture.samplingMode = fullOptions.samplingMode;
  94541. texture.type = fullOptions.type;
  94542. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  94543. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  94544. return texture;
  94545. };
  94546. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  94547. texture.samplingMode = samplingMode;
  94548. };
  94549. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  94550. if (this._currentRenderTarget) {
  94551. this.unBindFramebuffer(this._currentRenderTarget);
  94552. }
  94553. this._currentRenderTarget = texture;
  94554. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  94555. if (this._cachedViewport && !forceFullscreenViewport) {
  94556. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  94557. }
  94558. };
  94559. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  94560. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  94561. this._currentRenderTarget = null;
  94562. if (onBeforeUnbind) {
  94563. if (texture._MSAAFramebuffer) {
  94564. this._currentFramebuffer = texture._framebuffer;
  94565. }
  94566. onBeforeUnbind();
  94567. }
  94568. this._currentFramebuffer = null;
  94569. };
  94570. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  94571. var vbo = {
  94572. capacity: 1,
  94573. references: 1,
  94574. is32Bits: false
  94575. };
  94576. return vbo;
  94577. };
  94578. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  94579. if (offset === void 0) { offset = 0; }
  94580. };
  94581. /**
  94582. * Updates a dynamic vertex buffer.
  94583. * @param vertexBuffer the vertex buffer to update
  94584. * @param data the data used to update the vertex buffer
  94585. * @param byteOffset the byte offset of the data (optional)
  94586. * @param byteLength the byte length of the data (optional)
  94587. */
  94588. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  94589. };
  94590. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  94591. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  94592. this._boundTexturesCache[this._activeChannel] = texture;
  94593. }
  94594. };
  94595. NullEngine.prototype._bindTexture = function (channel, texture) {
  94596. if (channel < 0) {
  94597. return;
  94598. }
  94599. this._bindTextureDirectly(0, texture);
  94600. };
  94601. NullEngine.prototype._releaseBuffer = function (buffer) {
  94602. buffer.references--;
  94603. if (buffer.references === 0) {
  94604. return true;
  94605. }
  94606. return false;
  94607. };
  94608. return NullEngine;
  94609. }(BABYLON.Engine));
  94610. BABYLON.NullEngine = NullEngine;
  94611. })(BABYLON || (BABYLON = {}));
  94612. //# sourceMappingURL=babylon.nullEngine.js.map
  94613. var BABYLON;
  94614. (function (BABYLON) {
  94615. /**
  94616. * This class can be used to get instrumentation data from a Babylon engine
  94617. */
  94618. var EngineInstrumentation = /** @class */ (function () {
  94619. function EngineInstrumentation(engine) {
  94620. this.engine = engine;
  94621. this._captureGPUFrameTime = false;
  94622. this._gpuFrameTime = new BABYLON.PerfCounter();
  94623. this._captureShaderCompilationTime = false;
  94624. this._shaderCompilationTime = new BABYLON.PerfCounter();
  94625. // Observers
  94626. this._onBeginFrameObserver = null;
  94627. this._onEndFrameObserver = null;
  94628. this._onBeforeShaderCompilationObserver = null;
  94629. this._onAfterShaderCompilationObserver = null;
  94630. }
  94631. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  94632. // Properties
  94633. /**
  94634. * Gets the perf counter used for GPU frame time
  94635. */
  94636. get: function () {
  94637. return this._gpuFrameTime;
  94638. },
  94639. enumerable: true,
  94640. configurable: true
  94641. });
  94642. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  94643. /**
  94644. * Gets the GPU frame time capture status
  94645. */
  94646. get: function () {
  94647. return this._captureGPUFrameTime;
  94648. },
  94649. /**
  94650. * Enable or disable the GPU frame time capture
  94651. */
  94652. set: function (value) {
  94653. var _this = this;
  94654. if (value === this._captureGPUFrameTime) {
  94655. return;
  94656. }
  94657. this._captureGPUFrameTime = value;
  94658. if (value) {
  94659. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  94660. if (!_this._gpuFrameTimeToken) {
  94661. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  94662. }
  94663. });
  94664. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  94665. if (!_this._gpuFrameTimeToken) {
  94666. return;
  94667. }
  94668. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  94669. if (time > -1) {
  94670. _this._gpuFrameTimeToken = null;
  94671. _this._gpuFrameTime.fetchNewFrame();
  94672. _this._gpuFrameTime.addCount(time, true);
  94673. }
  94674. });
  94675. }
  94676. else {
  94677. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94678. this._onBeginFrameObserver = null;
  94679. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94680. this._onEndFrameObserver = null;
  94681. }
  94682. },
  94683. enumerable: true,
  94684. configurable: true
  94685. });
  94686. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  94687. /**
  94688. * Gets the perf counter used for shader compilation time
  94689. */
  94690. get: function () {
  94691. return this._shaderCompilationTime;
  94692. },
  94693. enumerable: true,
  94694. configurable: true
  94695. });
  94696. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  94697. /**
  94698. * Gets the shader compilation time capture status
  94699. */
  94700. get: function () {
  94701. return this._captureShaderCompilationTime;
  94702. },
  94703. /**
  94704. * Enable or disable the shader compilation time capture
  94705. */
  94706. set: function (value) {
  94707. var _this = this;
  94708. if (value === this._captureShaderCompilationTime) {
  94709. return;
  94710. }
  94711. this._captureShaderCompilationTime = value;
  94712. if (value) {
  94713. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  94714. _this._shaderCompilationTime.fetchNewFrame();
  94715. _this._shaderCompilationTime.beginMonitoring();
  94716. });
  94717. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  94718. _this._shaderCompilationTime.endMonitoring();
  94719. });
  94720. }
  94721. else {
  94722. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94723. this._onBeforeShaderCompilationObserver = null;
  94724. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94725. this._onAfterShaderCompilationObserver = null;
  94726. }
  94727. },
  94728. enumerable: true,
  94729. configurable: true
  94730. });
  94731. EngineInstrumentation.prototype.dispose = function () {
  94732. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94733. this._onBeginFrameObserver = null;
  94734. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94735. this._onEndFrameObserver = null;
  94736. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94737. this._onBeforeShaderCompilationObserver = null;
  94738. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94739. this._onAfterShaderCompilationObserver = null;
  94740. this.engine = null;
  94741. };
  94742. return EngineInstrumentation;
  94743. }());
  94744. BABYLON.EngineInstrumentation = EngineInstrumentation;
  94745. })(BABYLON || (BABYLON = {}));
  94746. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  94747. var BABYLON;
  94748. (function (BABYLON) {
  94749. /**
  94750. * This class can be used to get instrumentation data from a Babylon engine
  94751. */
  94752. var SceneInstrumentation = /** @class */ (function () {
  94753. function SceneInstrumentation(scene) {
  94754. var _this = this;
  94755. this.scene = scene;
  94756. this._captureActiveMeshesEvaluationTime = false;
  94757. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  94758. this._captureRenderTargetsRenderTime = false;
  94759. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  94760. this._captureFrameTime = false;
  94761. this._frameTime = new BABYLON.PerfCounter();
  94762. this._captureRenderTime = false;
  94763. this._renderTime = new BABYLON.PerfCounter();
  94764. this._captureInterFrameTime = false;
  94765. this._interFrameTime = new BABYLON.PerfCounter();
  94766. this._captureParticlesRenderTime = false;
  94767. this._particlesRenderTime = new BABYLON.PerfCounter();
  94768. this._captureSpritesRenderTime = false;
  94769. this._spritesRenderTime = new BABYLON.PerfCounter();
  94770. this._capturePhysicsTime = false;
  94771. this._physicsTime = new BABYLON.PerfCounter();
  94772. this._captureAnimationsTime = false;
  94773. this._animationsTime = new BABYLON.PerfCounter();
  94774. // Observers
  94775. this._onBeforeActiveMeshesEvaluationObserver = null;
  94776. this._onAfterActiveMeshesEvaluationObserver = null;
  94777. this._onBeforeRenderTargetsRenderObserver = null;
  94778. this._onAfterRenderTargetsRenderObserver = null;
  94779. this._onAfterRenderObserver = null;
  94780. this._onBeforeDrawPhaseObserver = null;
  94781. this._onAfterDrawPhaseObserver = null;
  94782. this._onBeforeAnimationsObserver = null;
  94783. this._onBeforeParticlesRenderingObserver = null;
  94784. this._onAfterParticlesRenderingObserver = null;
  94785. this._onBeforeSpritesRenderingObserver = null;
  94786. this._onAfterSpritesRenderingObserver = null;
  94787. this._onBeforePhysicsObserver = null;
  94788. this._onAfterPhysicsObserver = null;
  94789. this._onAfterAnimationsObserver = null;
  94790. // Before render
  94791. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  94792. if (_this._captureActiveMeshesEvaluationTime) {
  94793. _this._activeMeshesEvaluationTime.fetchNewFrame();
  94794. }
  94795. if (_this._captureRenderTargetsRenderTime) {
  94796. _this._renderTargetsRenderTime.fetchNewFrame();
  94797. }
  94798. if (_this._captureFrameTime) {
  94799. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  94800. _this._frameTime.beginMonitoring();
  94801. }
  94802. if (_this._captureInterFrameTime) {
  94803. _this._interFrameTime.endMonitoring();
  94804. }
  94805. if (_this._captureParticlesRenderTime) {
  94806. _this._particlesRenderTime.fetchNewFrame();
  94807. }
  94808. if (_this._captureSpritesRenderTime) {
  94809. _this._spritesRenderTime.fetchNewFrame();
  94810. }
  94811. if (_this._captureAnimationsTime) {
  94812. _this._animationsTime.beginMonitoring();
  94813. }
  94814. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  94815. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  94816. });
  94817. // After render
  94818. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  94819. if (_this._captureFrameTime) {
  94820. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  94821. _this._frameTime.endMonitoring();
  94822. }
  94823. if (_this._captureRenderTime) {
  94824. _this._renderTime.endMonitoring(false);
  94825. }
  94826. if (_this._captureInterFrameTime) {
  94827. _this._interFrameTime.beginMonitoring();
  94828. }
  94829. });
  94830. }
  94831. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  94832. // Properties
  94833. /**
  94834. * Gets the perf counter used for active meshes evaluation time
  94835. */
  94836. get: function () {
  94837. return this._activeMeshesEvaluationTime;
  94838. },
  94839. enumerable: true,
  94840. configurable: true
  94841. });
  94842. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  94843. /**
  94844. * Gets the active meshes evaluation time capture status
  94845. */
  94846. get: function () {
  94847. return this._captureActiveMeshesEvaluationTime;
  94848. },
  94849. /**
  94850. * Enable or disable the active meshes evaluation time capture
  94851. */
  94852. set: function (value) {
  94853. var _this = this;
  94854. if (value === this._captureActiveMeshesEvaluationTime) {
  94855. return;
  94856. }
  94857. this._captureActiveMeshesEvaluationTime = value;
  94858. if (value) {
  94859. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  94860. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  94861. _this._activeMeshesEvaluationTime.beginMonitoring();
  94862. });
  94863. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  94864. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  94865. _this._activeMeshesEvaluationTime.endMonitoring();
  94866. });
  94867. }
  94868. else {
  94869. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94870. this._onBeforeActiveMeshesEvaluationObserver = null;
  94871. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94872. this._onAfterActiveMeshesEvaluationObserver = null;
  94873. }
  94874. },
  94875. enumerable: true,
  94876. configurable: true
  94877. });
  94878. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  94879. /**
  94880. * Gets the perf counter used for render targets render time
  94881. */
  94882. get: function () {
  94883. return this._renderTargetsRenderTime;
  94884. },
  94885. enumerable: true,
  94886. configurable: true
  94887. });
  94888. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  94889. /**
  94890. * Gets the render targets render time capture status
  94891. */
  94892. get: function () {
  94893. return this._captureRenderTargetsRenderTime;
  94894. },
  94895. /**
  94896. * Enable or disable the render targets render time capture
  94897. */
  94898. set: function (value) {
  94899. var _this = this;
  94900. if (value === this._captureRenderTargetsRenderTime) {
  94901. return;
  94902. }
  94903. this._captureRenderTargetsRenderTime = value;
  94904. if (value) {
  94905. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  94906. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  94907. _this._renderTargetsRenderTime.beginMonitoring();
  94908. });
  94909. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  94910. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  94911. _this._renderTargetsRenderTime.endMonitoring(false);
  94912. });
  94913. }
  94914. else {
  94915. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94916. this._onBeforeRenderTargetsRenderObserver = null;
  94917. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94918. this._onAfterRenderTargetsRenderObserver = null;
  94919. }
  94920. },
  94921. enumerable: true,
  94922. configurable: true
  94923. });
  94924. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  94925. /**
  94926. * Gets the perf counter used for particles render time
  94927. */
  94928. get: function () {
  94929. return this._particlesRenderTime;
  94930. },
  94931. enumerable: true,
  94932. configurable: true
  94933. });
  94934. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  94935. /**
  94936. * Gets the particles render time capture status
  94937. */
  94938. get: function () {
  94939. return this._captureParticlesRenderTime;
  94940. },
  94941. /**
  94942. * Enable or disable the particles render time capture
  94943. */
  94944. set: function (value) {
  94945. var _this = this;
  94946. if (value === this._captureParticlesRenderTime) {
  94947. return;
  94948. }
  94949. this._captureParticlesRenderTime = value;
  94950. if (value) {
  94951. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  94952. BABYLON.Tools.StartPerformanceCounter("Particles");
  94953. _this._particlesRenderTime.beginMonitoring();
  94954. });
  94955. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  94956. BABYLON.Tools.EndPerformanceCounter("Particles");
  94957. _this._particlesRenderTime.endMonitoring(false);
  94958. });
  94959. }
  94960. else {
  94961. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94962. this._onBeforeParticlesRenderingObserver = null;
  94963. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94964. this._onAfterParticlesRenderingObserver = null;
  94965. }
  94966. },
  94967. enumerable: true,
  94968. configurable: true
  94969. });
  94970. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  94971. /**
  94972. * Gets the perf counter used for sprites render time
  94973. */
  94974. get: function () {
  94975. return this._spritesRenderTime;
  94976. },
  94977. enumerable: true,
  94978. configurable: true
  94979. });
  94980. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  94981. /**
  94982. * Gets the sprites render time capture status
  94983. */
  94984. get: function () {
  94985. return this._captureSpritesRenderTime;
  94986. },
  94987. /**
  94988. * Enable or disable the sprites render time capture
  94989. */
  94990. set: function (value) {
  94991. var _this = this;
  94992. if (value === this._captureSpritesRenderTime) {
  94993. return;
  94994. }
  94995. this._captureSpritesRenderTime = value;
  94996. if (value) {
  94997. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  94998. BABYLON.Tools.StartPerformanceCounter("Sprites");
  94999. _this._spritesRenderTime.beginMonitoring();
  95000. });
  95001. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95002. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95003. _this._spritesRenderTime.endMonitoring(false);
  95004. });
  95005. }
  95006. else {
  95007. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95008. this._onBeforeSpritesRenderingObserver = null;
  95009. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95010. this._onAfterSpritesRenderingObserver = null;
  95011. }
  95012. },
  95013. enumerable: true,
  95014. configurable: true
  95015. });
  95016. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95017. /**
  95018. * Gets the perf counter used for physics time
  95019. */
  95020. get: function () {
  95021. return this._physicsTime;
  95022. },
  95023. enumerable: true,
  95024. configurable: true
  95025. });
  95026. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95027. /**
  95028. * Gets the physics time capture status
  95029. */
  95030. get: function () {
  95031. return this._capturePhysicsTime;
  95032. },
  95033. /**
  95034. * Enable or disable the physics time capture
  95035. */
  95036. set: function (value) {
  95037. var _this = this;
  95038. if (value === this._capturePhysicsTime) {
  95039. return;
  95040. }
  95041. this._capturePhysicsTime = value;
  95042. if (value) {
  95043. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95044. BABYLON.Tools.StartPerformanceCounter("Physics");
  95045. _this._physicsTime.beginMonitoring();
  95046. });
  95047. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95048. BABYLON.Tools.EndPerformanceCounter("Physics");
  95049. _this._physicsTime.endMonitoring();
  95050. });
  95051. }
  95052. else {
  95053. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95054. this._onBeforePhysicsObserver = null;
  95055. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95056. this._onAfterPhysicsObserver = null;
  95057. }
  95058. },
  95059. enumerable: true,
  95060. configurable: true
  95061. });
  95062. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95063. /**
  95064. * Gets the perf counter used for animations time
  95065. */
  95066. get: function () {
  95067. return this._animationsTime;
  95068. },
  95069. enumerable: true,
  95070. configurable: true
  95071. });
  95072. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95073. /**
  95074. * Gets the animations time capture status
  95075. */
  95076. get: function () {
  95077. return this._captureAnimationsTime;
  95078. },
  95079. /**
  95080. * Enable or disable the animations time capture
  95081. */
  95082. set: function (value) {
  95083. var _this = this;
  95084. if (value === this._captureAnimationsTime) {
  95085. return;
  95086. }
  95087. this._captureAnimationsTime = value;
  95088. if (value) {
  95089. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95090. _this._animationsTime.endMonitoring();
  95091. });
  95092. }
  95093. else {
  95094. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95095. this._onAfterAnimationsObserver = null;
  95096. }
  95097. },
  95098. enumerable: true,
  95099. configurable: true
  95100. });
  95101. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95102. /**
  95103. * Gets the perf counter used for frame time capture
  95104. */
  95105. get: function () {
  95106. return this._frameTime;
  95107. },
  95108. enumerable: true,
  95109. configurable: true
  95110. });
  95111. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95112. /**
  95113. * Gets the frame time capture status
  95114. */
  95115. get: function () {
  95116. return this._captureFrameTime;
  95117. },
  95118. /**
  95119. * Enable or disable the frame time capture
  95120. */
  95121. set: function (value) {
  95122. this._captureFrameTime = value;
  95123. },
  95124. enumerable: true,
  95125. configurable: true
  95126. });
  95127. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95128. /**
  95129. * Gets the perf counter used for inter-frames time capture
  95130. */
  95131. get: function () {
  95132. return this._interFrameTime;
  95133. },
  95134. enumerable: true,
  95135. configurable: true
  95136. });
  95137. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95138. /**
  95139. * Gets the inter-frames time capture status
  95140. */
  95141. get: function () {
  95142. return this._captureInterFrameTime;
  95143. },
  95144. /**
  95145. * Enable or disable the inter-frames time capture
  95146. */
  95147. set: function (value) {
  95148. this._captureInterFrameTime = value;
  95149. },
  95150. enumerable: true,
  95151. configurable: true
  95152. });
  95153. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95154. /**
  95155. * Gets the perf counter used for render time capture
  95156. */
  95157. get: function () {
  95158. return this._renderTime;
  95159. },
  95160. enumerable: true,
  95161. configurable: true
  95162. });
  95163. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95164. /**
  95165. * Gets the render time capture status
  95166. */
  95167. get: function () {
  95168. return this._captureRenderTime;
  95169. },
  95170. /**
  95171. * Enable or disable the render time capture
  95172. */
  95173. set: function (value) {
  95174. var _this = this;
  95175. if (value === this._captureRenderTime) {
  95176. return;
  95177. }
  95178. this._captureRenderTime = value;
  95179. if (value) {
  95180. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95181. _this._renderTime.beginMonitoring();
  95182. BABYLON.Tools.StartPerformanceCounter("Main render");
  95183. });
  95184. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95185. _this._renderTime.endMonitoring(false);
  95186. BABYLON.Tools.EndPerformanceCounter("Main render");
  95187. });
  95188. }
  95189. else {
  95190. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95191. this._onBeforeDrawPhaseObserver = null;
  95192. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95193. this._onAfterDrawPhaseObserver = null;
  95194. }
  95195. },
  95196. enumerable: true,
  95197. configurable: true
  95198. });
  95199. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95200. /**
  95201. * Gets the perf counter used for draw calls
  95202. */
  95203. get: function () {
  95204. return this.scene.getEngine()._drawCalls;
  95205. },
  95206. enumerable: true,
  95207. configurable: true
  95208. });
  95209. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95210. /**
  95211. * Gets the perf counter used for texture collisions
  95212. */
  95213. get: function () {
  95214. return this.scene.getEngine()._textureCollisions;
  95215. },
  95216. enumerable: true,
  95217. configurable: true
  95218. });
  95219. SceneInstrumentation.prototype.dispose = function () {
  95220. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95221. this._onAfterRenderObserver = null;
  95222. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95223. this._onBeforeActiveMeshesEvaluationObserver = null;
  95224. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95225. this._onAfterActiveMeshesEvaluationObserver = null;
  95226. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95227. this._onBeforeRenderTargetsRenderObserver = null;
  95228. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95229. this._onAfterRenderTargetsRenderObserver = null;
  95230. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95231. this._onBeforeAnimationsObserver = null;
  95232. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95233. this._onBeforeParticlesRenderingObserver = null;
  95234. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95235. this._onAfterParticlesRenderingObserver = null;
  95236. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95237. this._onBeforeSpritesRenderingObserver = null;
  95238. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95239. this._onAfterSpritesRenderingObserver = null;
  95240. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95241. this._onBeforeDrawPhaseObserver = null;
  95242. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95243. this._onAfterDrawPhaseObserver = null;
  95244. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95245. this._onBeforePhysicsObserver = null;
  95246. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95247. this._onAfterPhysicsObserver = null;
  95248. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95249. this._onAfterAnimationsObserver = null;
  95250. this.scene = null;
  95251. };
  95252. return SceneInstrumentation;
  95253. }());
  95254. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95255. })(BABYLON || (BABYLON = {}));
  95256. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95257. var BABYLON;
  95258. (function (BABYLON) {
  95259. var _TimeToken = /** @class */ (function () {
  95260. function _TimeToken() {
  95261. this._timeElapsedQueryEnded = false;
  95262. }
  95263. return _TimeToken;
  95264. }());
  95265. BABYLON._TimeToken = _TimeToken;
  95266. })(BABYLON || (BABYLON = {}));
  95267. //# sourceMappingURL=babylon.timeToken.js.map
  95268. var BABYLON;
  95269. (function (BABYLON) {
  95270. /**
  95271. * Background material defines definition.
  95272. * @ignore Mainly internal Use
  95273. */
  95274. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95275. __extends(BackgroundMaterialDefines, _super);
  95276. /**
  95277. * Constructor of the defines.
  95278. */
  95279. function BackgroundMaterialDefines() {
  95280. var _this = _super.call(this) || this;
  95281. /**
  95282. * True if the diffuse texture is in use.
  95283. */
  95284. _this.DIFFUSE = false;
  95285. /**
  95286. * The direct UV channel to use.
  95287. */
  95288. _this.DIFFUSEDIRECTUV = 0;
  95289. /**
  95290. * True if the diffuse texture is in gamma space.
  95291. */
  95292. _this.GAMMADIFFUSE = false;
  95293. /**
  95294. * True if the diffuse texture has opacity in the alpha channel.
  95295. */
  95296. _this.DIFFUSEHASALPHA = false;
  95297. /**
  95298. * True if you want the material to fade to transparent at grazing angle.
  95299. */
  95300. _this.OPACITYFRESNEL = false;
  95301. /**
  95302. * True if an extra blur needs to be added in the reflection.
  95303. */
  95304. _this.REFLECTIONBLUR = false;
  95305. /**
  95306. * True if you want the material to fade to reflection at grazing angle.
  95307. */
  95308. _this.REFLECTIONFRESNEL = false;
  95309. /**
  95310. * True if you want the material to falloff as far as you move away from the scene center.
  95311. */
  95312. _this.REFLECTIONFALLOFF = false;
  95313. /**
  95314. * False if the current Webgl implementation does not support the texture lod extension.
  95315. */
  95316. _this.TEXTURELODSUPPORT = false;
  95317. /**
  95318. * True to ensure the data are premultiplied.
  95319. */
  95320. _this.PREMULTIPLYALPHA = false;
  95321. /**
  95322. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95323. */
  95324. _this.USERGBCOLOR = false;
  95325. /**
  95326. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95327. * stays aligned with the desired configuration.
  95328. */
  95329. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95330. /**
  95331. * True to add noise in order to reduce the banding effect.
  95332. */
  95333. _this.NOISE = false;
  95334. /**
  95335. * is the reflection texture in BGR color scheme?
  95336. * Mainly used to solve a bug in ios10 video tag
  95337. */
  95338. _this.REFLECTIONBGR = false;
  95339. _this.IMAGEPROCESSING = false;
  95340. _this.VIGNETTE = false;
  95341. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95342. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95343. _this.TONEMAPPING = false;
  95344. _this.CONTRAST = false;
  95345. _this.COLORCURVES = false;
  95346. _this.COLORGRADING = false;
  95347. _this.COLORGRADING3D = false;
  95348. _this.SAMPLER3DGREENDEPTH = false;
  95349. _this.SAMPLER3DBGRMAP = false;
  95350. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95351. _this.EXPOSURE = false;
  95352. // Reflection.
  95353. _this.REFLECTION = false;
  95354. _this.REFLECTIONMAP_3D = false;
  95355. _this.REFLECTIONMAP_SPHERICAL = false;
  95356. _this.REFLECTIONMAP_PLANAR = false;
  95357. _this.REFLECTIONMAP_CUBIC = false;
  95358. _this.REFLECTIONMAP_PROJECTION = false;
  95359. _this.REFLECTIONMAP_SKYBOX = false;
  95360. _this.REFLECTIONMAP_EXPLICIT = false;
  95361. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95362. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95363. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95364. _this.INVERTCUBICMAP = false;
  95365. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95366. _this.LODINREFLECTIONALPHA = false;
  95367. _this.GAMMAREFLECTION = false;
  95368. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95369. // Default BJS.
  95370. _this.MAINUV1 = false;
  95371. _this.MAINUV2 = false;
  95372. _this.UV1 = false;
  95373. _this.UV2 = false;
  95374. _this.CLIPPLANE = false;
  95375. _this.POINTSIZE = false;
  95376. _this.FOG = false;
  95377. _this.NORMAL = false;
  95378. _this.NUM_BONE_INFLUENCERS = 0;
  95379. _this.BonesPerMesh = 0;
  95380. _this.INSTANCES = false;
  95381. _this.SHADOWFLOAT = false;
  95382. _this.rebuild();
  95383. return _this;
  95384. }
  95385. return BackgroundMaterialDefines;
  95386. }(BABYLON.MaterialDefines));
  95387. /**
  95388. * Background material used to create an efficient environement around your scene.
  95389. */
  95390. var BackgroundMaterial = /** @class */ (function (_super) {
  95391. __extends(BackgroundMaterial, _super);
  95392. /**
  95393. * Instantiates a Background Material in the given scene
  95394. * @param name The friendly name of the material
  95395. * @param scene The scene to add the material to
  95396. */
  95397. function BackgroundMaterial(name, scene) {
  95398. var _this = _super.call(this, name, scene) || this;
  95399. /**
  95400. * Key light Color (multiply against the environement texture)
  95401. */
  95402. _this.primaryColor = BABYLON.Color3.White();
  95403. _this._primaryColorShadowLevel = 0;
  95404. _this._primaryColorHighlightLevel = 0;
  95405. /**
  95406. * Reflection Texture used in the material.
  95407. * Should be author in a specific way for the best result (refer to the documentation).
  95408. */
  95409. _this.reflectionTexture = null;
  95410. /**
  95411. * Reflection Texture level of blur.
  95412. *
  95413. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  95414. * texture twice.
  95415. */
  95416. _this.reflectionBlur = 0;
  95417. /**
  95418. * Diffuse Texture used in the material.
  95419. * Should be author in a specific way for the best result (refer to the documentation).
  95420. */
  95421. _this.diffuseTexture = null;
  95422. _this._shadowLights = null;
  95423. /**
  95424. * Specify the list of lights casting shadow on the material.
  95425. * All scene shadow lights will be included if null.
  95426. */
  95427. _this.shadowLights = null;
  95428. /**
  95429. * Helps adjusting the shadow to a softer level if required.
  95430. * 0 means black shadows and 1 means no shadows.
  95431. */
  95432. _this.shadowLevel = 0;
  95433. /**
  95434. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  95435. * It is usually zero but might be interesting to modify according to your setup.
  95436. */
  95437. _this.sceneCenter = BABYLON.Vector3.Zero();
  95438. /**
  95439. * This helps specifying that the material is falling off to the sky box at grazing angle.
  95440. * This helps ensuring a nice transition when the camera goes under the ground.
  95441. */
  95442. _this.opacityFresnel = true;
  95443. /**
  95444. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  95445. * This helps adding a mirror texture on the ground.
  95446. */
  95447. _this.reflectionFresnel = false;
  95448. /**
  95449. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  95450. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  95451. */
  95452. _this.reflectionFalloffDistance = 0.0;
  95453. /**
  95454. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  95455. */
  95456. _this.reflectionAmount = 1.0;
  95457. /**
  95458. * This specifies the weight of the reflection at grazing angle.
  95459. */
  95460. _this.reflectionReflectance0 = 0.05;
  95461. /**
  95462. * This specifies the weight of the reflection at a perpendicular point of view.
  95463. */
  95464. _this.reflectionReflectance90 = 0.5;
  95465. /**
  95466. * Helps to directly use the maps channels instead of their level.
  95467. */
  95468. _this.useRGBColor = true;
  95469. /**
  95470. * This helps reducing the banding effect that could occur on the background.
  95471. */
  95472. _this.enableNoise = false;
  95473. _this._fovMultiplier = 1.0;
  95474. /**
  95475. * Enable the FOV adjustment feature controlled by fovMultiplier.
  95476. */
  95477. _this.useEquirectangularFOV = false;
  95478. _this._maxSimultaneousLights = 4;
  95479. /**
  95480. * Number of Simultaneous lights allowed on the material.
  95481. */
  95482. _this.maxSimultaneousLights = 4;
  95483. /**
  95484. * Keep track of the image processing observer to allow dispose and replace.
  95485. */
  95486. _this._imageProcessingObserver = null;
  95487. /**
  95488. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  95489. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  95490. */
  95491. _this.switchToBGR = false;
  95492. // Temp values kept as cache in the material.
  95493. _this._renderTargets = new BABYLON.SmartArray(16);
  95494. _this._reflectionControls = BABYLON.Vector4.Zero();
  95495. _this._white = BABYLON.Color3.White();
  95496. _this._primaryShadowColor = BABYLON.Color3.Black();
  95497. _this._primaryHighlightColor = BABYLON.Color3.Black();
  95498. // Setup the default processing configuration to the scene.
  95499. _this._attachImageProcessingConfiguration(null);
  95500. _this.getRenderTargetTextures = function () {
  95501. _this._renderTargets.reset();
  95502. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  95503. _this._renderTargets.push(_this._diffuseTexture);
  95504. }
  95505. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  95506. _this._renderTargets.push(_this._reflectionTexture);
  95507. }
  95508. return _this._renderTargets;
  95509. };
  95510. return _this;
  95511. }
  95512. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  95513. /**
  95514. * Experimental Internal Use Only.
  95515. *
  95516. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  95517. * This acts as a helper to set the primary color to a more "human friendly" value.
  95518. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  95519. * output color as close as possible from the chosen value.
  95520. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  95521. * part of lighting setup.)
  95522. */
  95523. get: function () {
  95524. return this.__perceptualColor;
  95525. },
  95526. set: function (value) {
  95527. this.__perceptualColor = value;
  95528. this._computePrimaryColorFromPerceptualColor();
  95529. this._markAllSubMeshesAsLightsDirty();
  95530. },
  95531. enumerable: true,
  95532. configurable: true
  95533. });
  95534. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  95535. /**
  95536. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  95537. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  95538. */
  95539. get: function () {
  95540. return this._primaryColorShadowLevel;
  95541. },
  95542. set: function (value) {
  95543. this._primaryColorShadowLevel = value;
  95544. this._computePrimaryColors();
  95545. this._markAllSubMeshesAsLightsDirty();
  95546. },
  95547. enumerable: true,
  95548. configurable: true
  95549. });
  95550. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  95551. /**
  95552. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  95553. * The primary color is used at the level chosen to define what the white area would look.
  95554. */
  95555. get: function () {
  95556. return this._primaryColorHighlightLevel;
  95557. },
  95558. set: function (value) {
  95559. this._primaryColorHighlightLevel = value;
  95560. this._computePrimaryColors();
  95561. this._markAllSubMeshesAsLightsDirty();
  95562. },
  95563. enumerable: true,
  95564. configurable: true
  95565. });
  95566. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  95567. /**
  95568. * Sets the reflection reflectance fresnel values according to the default standard
  95569. * empirically know to work well :-)
  95570. */
  95571. set: function (value) {
  95572. var reflectionWeight = value;
  95573. if (reflectionWeight < 0.5) {
  95574. reflectionWeight = reflectionWeight * 2.0;
  95575. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  95576. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  95577. }
  95578. else {
  95579. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  95580. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  95581. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  95582. }
  95583. },
  95584. enumerable: true,
  95585. configurable: true
  95586. });
  95587. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  95588. /**
  95589. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  95590. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  95591. * Recommended to be keep at 1.0 except for special cases.
  95592. */
  95593. get: function () {
  95594. return this._fovMultiplier;
  95595. },
  95596. set: function (value) {
  95597. if (isNaN(value)) {
  95598. value = 1.0;
  95599. }
  95600. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  95601. },
  95602. enumerable: true,
  95603. configurable: true
  95604. });
  95605. /**
  95606. * Attaches a new image processing configuration to the PBR Material.
  95607. * @param configuration (if null the scene configuration will be use)
  95608. */
  95609. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  95610. var _this = this;
  95611. if (configuration === this._imageProcessingConfiguration) {
  95612. return;
  95613. }
  95614. // Detaches observer.
  95615. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  95616. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  95617. }
  95618. // Pick the scene configuration if needed.
  95619. if (!configuration) {
  95620. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  95621. }
  95622. else {
  95623. this._imageProcessingConfiguration = configuration;
  95624. }
  95625. // Attaches observer.
  95626. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  95627. _this._computePrimaryColorFromPerceptualColor();
  95628. _this._markAllSubMeshesAsImageProcessingDirty();
  95629. });
  95630. };
  95631. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  95632. /**
  95633. * Gets the image processing configuration used either in this material.
  95634. */
  95635. get: function () {
  95636. return this._imageProcessingConfiguration;
  95637. },
  95638. /**
  95639. * Sets the Default image processing configuration used either in the this material.
  95640. *
  95641. * If sets to null, the scene one is in use.
  95642. */
  95643. set: function (value) {
  95644. this._attachImageProcessingConfiguration(value);
  95645. // Ensure the effect will be rebuilt.
  95646. this._markAllSubMeshesAsTexturesDirty();
  95647. },
  95648. enumerable: true,
  95649. configurable: true
  95650. });
  95651. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  95652. /**
  95653. * Gets wether the color curves effect is enabled.
  95654. */
  95655. get: function () {
  95656. return this.imageProcessingConfiguration.colorCurvesEnabled;
  95657. },
  95658. /**
  95659. * Sets wether the color curves effect is enabled.
  95660. */
  95661. set: function (value) {
  95662. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  95663. },
  95664. enumerable: true,
  95665. configurable: true
  95666. });
  95667. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  95668. /**
  95669. * Gets wether the color grading effect is enabled.
  95670. */
  95671. get: function () {
  95672. return this.imageProcessingConfiguration.colorGradingEnabled;
  95673. },
  95674. /**
  95675. * Gets wether the color grading effect is enabled.
  95676. */
  95677. set: function (value) {
  95678. this.imageProcessingConfiguration.colorGradingEnabled = value;
  95679. },
  95680. enumerable: true,
  95681. configurable: true
  95682. });
  95683. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  95684. /**
  95685. * Gets wether tonemapping is enabled or not.
  95686. */
  95687. get: function () {
  95688. return this._imageProcessingConfiguration.toneMappingEnabled;
  95689. },
  95690. /**
  95691. * Sets wether tonemapping is enabled or not
  95692. */
  95693. set: function (value) {
  95694. this._imageProcessingConfiguration.toneMappingEnabled = value;
  95695. },
  95696. enumerable: true,
  95697. configurable: true
  95698. });
  95699. ;
  95700. ;
  95701. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  95702. /**
  95703. * The camera exposure used on this material.
  95704. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95705. * This corresponds to a photographic exposure.
  95706. */
  95707. get: function () {
  95708. return this._imageProcessingConfiguration.exposure;
  95709. },
  95710. /**
  95711. * The camera exposure used on this material.
  95712. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95713. * This corresponds to a photographic exposure.
  95714. */
  95715. set: function (value) {
  95716. this._imageProcessingConfiguration.exposure = value;
  95717. },
  95718. enumerable: true,
  95719. configurable: true
  95720. });
  95721. ;
  95722. ;
  95723. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  95724. /**
  95725. * Gets The camera contrast used on this material.
  95726. */
  95727. get: function () {
  95728. return this._imageProcessingConfiguration.contrast;
  95729. },
  95730. /**
  95731. * Sets The camera contrast used on this material.
  95732. */
  95733. set: function (value) {
  95734. this._imageProcessingConfiguration.contrast = value;
  95735. },
  95736. enumerable: true,
  95737. configurable: true
  95738. });
  95739. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  95740. /**
  95741. * Gets the Color Grading 2D Lookup Texture.
  95742. */
  95743. get: function () {
  95744. return this._imageProcessingConfiguration.colorGradingTexture;
  95745. },
  95746. /**
  95747. * Sets the Color Grading 2D Lookup Texture.
  95748. */
  95749. set: function (value) {
  95750. this.imageProcessingConfiguration.colorGradingTexture = value;
  95751. },
  95752. enumerable: true,
  95753. configurable: true
  95754. });
  95755. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  95756. /**
  95757. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95758. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95759. * 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;
  95760. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95761. */
  95762. get: function () {
  95763. return this.imageProcessingConfiguration.colorCurves;
  95764. },
  95765. /**
  95766. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95767. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95768. * 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;
  95769. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95770. */
  95771. set: function (value) {
  95772. this.imageProcessingConfiguration.colorCurves = value;
  95773. },
  95774. enumerable: true,
  95775. configurable: true
  95776. });
  95777. /**
  95778. * The entire material has been created in order to prevent overdraw.
  95779. * @returns false
  95780. */
  95781. BackgroundMaterial.prototype.needAlphaTesting = function () {
  95782. return true;
  95783. };
  95784. /**
  95785. * The entire material has been created in order to prevent overdraw.
  95786. * @returns true if blending is enable
  95787. */
  95788. BackgroundMaterial.prototype.needAlphaBlending = function () {
  95789. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  95790. };
  95791. /**
  95792. * Checks wether the material is ready to be rendered for a given mesh.
  95793. * @param mesh The mesh to render
  95794. * @param subMesh The submesh to check against
  95795. * @param useInstances Specify wether or not the material is used with instances
  95796. * @returns true if all the dependencies are ready (Textures, Effects...)
  95797. */
  95798. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  95799. var _this = this;
  95800. if (useInstances === void 0) { useInstances = false; }
  95801. if (subMesh.effect && this.isFrozen) {
  95802. if (this._wasPreviouslyReady) {
  95803. return true;
  95804. }
  95805. }
  95806. if (!subMesh._materialDefines) {
  95807. subMesh._materialDefines = new BackgroundMaterialDefines();
  95808. }
  95809. var scene = this.getScene();
  95810. var defines = subMesh._materialDefines;
  95811. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  95812. if (defines._renderId === scene.getRenderId()) {
  95813. return true;
  95814. }
  95815. }
  95816. var engine = scene.getEngine();
  95817. // Lights
  95818. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  95819. defines._needNormals = true;
  95820. // Textures
  95821. if (defines._areTexturesDirty) {
  95822. defines._needUVs = false;
  95823. if (scene.texturesEnabled) {
  95824. if (scene.getEngine().getCaps().textureLOD) {
  95825. defines.TEXTURELODSUPPORT = true;
  95826. }
  95827. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95828. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  95829. return false;
  95830. }
  95831. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  95832. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  95833. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  95834. defines.OPACITYFRESNEL = this._opacityFresnel;
  95835. }
  95836. else {
  95837. defines.DIFFUSE = false;
  95838. defines.DIFFUSEHASALPHA = false;
  95839. defines.GAMMADIFFUSE = false;
  95840. defines.OPACITYFRESNEL = false;
  95841. }
  95842. var reflectionTexture = this._reflectionTexture;
  95843. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95844. if (!reflectionTexture.isReadyOrNotBlocking()) {
  95845. return false;
  95846. }
  95847. defines.REFLECTION = true;
  95848. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  95849. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  95850. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  95851. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  95852. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  95853. defines.REFLECTIONBGR = this.switchToBGR;
  95854. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  95855. defines.INVERTCUBICMAP = true;
  95856. }
  95857. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  95858. switch (reflectionTexture.coordinatesMode) {
  95859. case BABYLON.Texture.CUBIC_MODE:
  95860. case BABYLON.Texture.INVCUBIC_MODE:
  95861. defines.REFLECTIONMAP_CUBIC = true;
  95862. break;
  95863. case BABYLON.Texture.EXPLICIT_MODE:
  95864. defines.REFLECTIONMAP_EXPLICIT = true;
  95865. break;
  95866. case BABYLON.Texture.PLANAR_MODE:
  95867. defines.REFLECTIONMAP_PLANAR = true;
  95868. break;
  95869. case BABYLON.Texture.PROJECTION_MODE:
  95870. defines.REFLECTIONMAP_PROJECTION = true;
  95871. break;
  95872. case BABYLON.Texture.SKYBOX_MODE:
  95873. defines.REFLECTIONMAP_SKYBOX = true;
  95874. break;
  95875. case BABYLON.Texture.SPHERICAL_MODE:
  95876. defines.REFLECTIONMAP_SPHERICAL = true;
  95877. break;
  95878. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  95879. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  95880. break;
  95881. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  95882. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  95883. break;
  95884. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  95885. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  95886. break;
  95887. }
  95888. if (this.reflectionFresnel) {
  95889. defines.REFLECTIONFRESNEL = true;
  95890. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  95891. this._reflectionControls.x = this.reflectionAmount;
  95892. this._reflectionControls.y = this.reflectionReflectance0;
  95893. this._reflectionControls.z = this.reflectionReflectance90;
  95894. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  95895. }
  95896. else {
  95897. defines.REFLECTIONFRESNEL = false;
  95898. defines.REFLECTIONFALLOFF = false;
  95899. }
  95900. }
  95901. else {
  95902. defines.REFLECTION = false;
  95903. defines.REFLECTIONFRESNEL = false;
  95904. defines.REFLECTIONFALLOFF = false;
  95905. defines.REFLECTIONBLUR = false;
  95906. defines.REFLECTIONMAP_3D = false;
  95907. defines.REFLECTIONMAP_SPHERICAL = false;
  95908. defines.REFLECTIONMAP_PLANAR = false;
  95909. defines.REFLECTIONMAP_CUBIC = false;
  95910. defines.REFLECTIONMAP_PROJECTION = false;
  95911. defines.REFLECTIONMAP_SKYBOX = false;
  95912. defines.REFLECTIONMAP_EXPLICIT = false;
  95913. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95914. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95915. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95916. defines.INVERTCUBICMAP = false;
  95917. defines.REFLECTIONMAP_OPPOSITEZ = false;
  95918. defines.LODINREFLECTIONALPHA = false;
  95919. defines.GAMMAREFLECTION = false;
  95920. }
  95921. }
  95922. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  95923. defines.USERGBCOLOR = this._useRGBColor;
  95924. defines.NOISE = this._enableNoise;
  95925. }
  95926. if (defines._areLightsDirty) {
  95927. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  95928. }
  95929. if (defines._areImageProcessingDirty) {
  95930. if (!this._imageProcessingConfiguration.isReady()) {
  95931. return false;
  95932. }
  95933. this._imageProcessingConfiguration.prepareDefines(defines);
  95934. }
  95935. // Misc.
  95936. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  95937. // Values that need to be evaluated on every frame
  95938. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  95939. // Attribs
  95940. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  95941. if (mesh) {
  95942. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95943. mesh.createNormals(true);
  95944. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  95945. }
  95946. }
  95947. }
  95948. // Get correct effect
  95949. if (defines.isDirty) {
  95950. defines.markAsProcessed();
  95951. scene.resetCachedMaterial();
  95952. // Fallbacks
  95953. var fallbacks = new BABYLON.EffectFallbacks();
  95954. if (defines.FOG) {
  95955. fallbacks.addFallback(0, "FOG");
  95956. }
  95957. if (defines.POINTSIZE) {
  95958. fallbacks.addFallback(1, "POINTSIZE");
  95959. }
  95960. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  95961. if (defines.NUM_BONE_INFLUENCERS > 0) {
  95962. fallbacks.addCPUSkinningFallback(0, mesh);
  95963. }
  95964. //Attributes
  95965. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95966. if (defines.NORMAL) {
  95967. attribs.push(BABYLON.VertexBuffer.NormalKind);
  95968. }
  95969. if (defines.UV1) {
  95970. attribs.push(BABYLON.VertexBuffer.UVKind);
  95971. }
  95972. if (defines.UV2) {
  95973. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95974. }
  95975. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  95976. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  95977. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  95978. "vFogInfos", "vFogColor", "pointSize",
  95979. "vClipPlane", "mBones",
  95980. "vPrimaryColor", "vPrimaryColorShadow",
  95981. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  95982. "shadowLevel", "alpha",
  95983. "vBackgroundCenter", "vReflectionControl",
  95984. "vDiffuseInfos", "diffuseMatrix",
  95985. ];
  95986. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  95987. var uniformBuffers = ["Material", "Scene"];
  95988. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  95989. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  95990. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  95991. uniformsNames: uniforms,
  95992. uniformBuffersNames: uniformBuffers,
  95993. samplers: samplers,
  95994. defines: defines,
  95995. maxSimultaneousLights: this._maxSimultaneousLights
  95996. });
  95997. var onCompiled = function (effect) {
  95998. if (_this.onCompiled) {
  95999. _this.onCompiled(effect);
  96000. }
  96001. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96002. };
  96003. var join = defines.toString();
  96004. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96005. attributes: attribs,
  96006. uniformsNames: uniforms,
  96007. uniformBuffersNames: uniformBuffers,
  96008. samplers: samplers,
  96009. defines: join,
  96010. fallbacks: fallbacks,
  96011. onCompiled: onCompiled,
  96012. onError: this.onError,
  96013. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96014. }, engine), defines);
  96015. this.buildUniformLayout();
  96016. }
  96017. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96018. return false;
  96019. }
  96020. defines._renderId = scene.getRenderId();
  96021. this._wasPreviouslyReady = true;
  96022. return true;
  96023. };
  96024. /**
  96025. * Compute the primary color according to the chosen perceptual color.
  96026. */
  96027. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96028. if (!this.__perceptualColor) {
  96029. return;
  96030. }
  96031. this._primaryColor.copyFrom(this.__perceptualColor);
  96032. // Revert gamma space.
  96033. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96034. // Revert image processing configuration.
  96035. if (this._imageProcessingConfiguration) {
  96036. // Revert Exposure.
  96037. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96038. }
  96039. this._computePrimaryColors();
  96040. };
  96041. /**
  96042. * Compute the highlights and shadow colors according to their chosen levels.
  96043. */
  96044. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96045. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96046. return;
  96047. }
  96048. // Find the highlight color based on the configuration.
  96049. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96050. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96051. // Find the shadow color based on the configuration.
  96052. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96053. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96054. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96055. };
  96056. /**
  96057. * Build the uniform buffer used in the material.
  96058. */
  96059. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96060. // Order is important !
  96061. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96062. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96063. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96064. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96065. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96066. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96067. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96068. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96069. this._uniformBuffer.addUniform("pointSize", 1);
  96070. this._uniformBuffer.addUniform("shadowLevel", 1);
  96071. this._uniformBuffer.addUniform("alpha", 1);
  96072. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96073. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96074. this._uniformBuffer.create();
  96075. };
  96076. /**
  96077. * Unbind the material.
  96078. */
  96079. BackgroundMaterial.prototype.unbind = function () {
  96080. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96081. this._uniformBuffer.setTexture("diffuseSampler", null);
  96082. }
  96083. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96084. this._uniformBuffer.setTexture("reflectionSampler", null);
  96085. }
  96086. _super.prototype.unbind.call(this);
  96087. };
  96088. /**
  96089. * Bind only the world matrix to the material.
  96090. * @param world The world matrix to bind.
  96091. */
  96092. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96093. this._activeEffect.setMatrix("world", world);
  96094. };
  96095. /**
  96096. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96097. * @param world The world matrix to bind.
  96098. * @param subMesh The submesh to bind for.
  96099. */
  96100. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96101. var scene = this.getScene();
  96102. var defines = subMesh._materialDefines;
  96103. if (!defines) {
  96104. return;
  96105. }
  96106. var effect = subMesh.effect;
  96107. if (!effect) {
  96108. return;
  96109. }
  96110. this._activeEffect = effect;
  96111. // Matrices
  96112. this.bindOnlyWorldMatrix(world);
  96113. // Bones
  96114. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96115. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96116. if (mustRebind) {
  96117. this._uniformBuffer.bindToEffect(effect, "Material");
  96118. this.bindViewProjection(effect);
  96119. var reflectionTexture = this._reflectionTexture;
  96120. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96121. // Texture uniforms
  96122. if (scene.texturesEnabled) {
  96123. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96124. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96125. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96126. }
  96127. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96128. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96129. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96130. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96131. }
  96132. }
  96133. if (this.shadowLevel > 0) {
  96134. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96135. }
  96136. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96137. // Point size
  96138. if (this.pointsCloud) {
  96139. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96140. }
  96141. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96142. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96143. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96144. }
  96145. else {
  96146. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96147. }
  96148. }
  96149. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96150. // Textures
  96151. if (scene.texturesEnabled) {
  96152. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96153. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96154. }
  96155. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96156. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96157. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96158. }
  96159. else if (!defines.REFLECTIONBLUR) {
  96160. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96161. }
  96162. else {
  96163. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96164. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96165. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96166. }
  96167. if (defines.REFLECTIONFRESNEL) {
  96168. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96169. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96170. }
  96171. }
  96172. }
  96173. // Clip plane
  96174. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96175. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96176. }
  96177. if (mustRebind || !this.isFrozen) {
  96178. if (scene.lightsEnabled) {
  96179. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96180. }
  96181. // View
  96182. this.bindView(effect);
  96183. // Fog
  96184. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96185. // image processing
  96186. this._imageProcessingConfiguration.bind(this._activeEffect);
  96187. }
  96188. this._uniformBuffer.update();
  96189. this._afterBind(mesh);
  96190. };
  96191. /**
  96192. * Dispose the material.
  96193. * @param forceDisposeEffect Force disposal of the associated effect.
  96194. * @param forceDisposeTextures Force disposal of the associated textures.
  96195. */
  96196. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96197. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96198. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96199. if (forceDisposeTextures) {
  96200. if (this.diffuseTexture) {
  96201. this.diffuseTexture.dispose();
  96202. }
  96203. if (this.reflectionTexture) {
  96204. this.reflectionTexture.dispose();
  96205. }
  96206. }
  96207. this._renderTargets.dispose();
  96208. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96209. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96210. }
  96211. _super.prototype.dispose.call(this, forceDisposeEffect);
  96212. };
  96213. /**
  96214. * Clones the material.
  96215. * @param name The cloned name.
  96216. * @returns The cloned material.
  96217. */
  96218. BackgroundMaterial.prototype.clone = function (name) {
  96219. var _this = this;
  96220. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96221. };
  96222. /**
  96223. * Serializes the current material to its JSON representation.
  96224. * @returns The JSON representation.
  96225. */
  96226. BackgroundMaterial.prototype.serialize = function () {
  96227. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96228. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96229. return serializationObject;
  96230. };
  96231. /**
  96232. * Gets the class name of the material
  96233. * @returns "BackgroundMaterial"
  96234. */
  96235. BackgroundMaterial.prototype.getClassName = function () {
  96236. return "BackgroundMaterial";
  96237. };
  96238. /**
  96239. * Parse a JSON input to create back a background material.
  96240. * @param source The JSON data to parse
  96241. * @param scene The scene to create the parsed material in
  96242. * @param rootUrl The root url of the assets the material depends upon
  96243. * @returns the instantiated BackgroundMaterial.
  96244. */
  96245. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96246. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96247. };
  96248. /**
  96249. * Standard reflectance value at parallel view angle.
  96250. */
  96251. BackgroundMaterial.StandardReflectance0 = 0.05;
  96252. /**
  96253. * Standard reflectance value at grazing angle.
  96254. */
  96255. BackgroundMaterial.StandardReflectance90 = 0.5;
  96256. __decorate([
  96257. BABYLON.serializeAsColor3()
  96258. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96259. __decorate([
  96260. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96261. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96262. __decorate([
  96263. BABYLON.serializeAsColor3()
  96264. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96265. __decorate([
  96266. BABYLON.serialize()
  96267. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96268. __decorate([
  96269. BABYLON.serialize()
  96270. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96271. __decorate([
  96272. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96273. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96274. __decorate([
  96275. BABYLON.serializeAsTexture()
  96276. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96277. __decorate([
  96278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96279. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96280. __decorate([
  96281. BABYLON.serialize()
  96282. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96283. __decorate([
  96284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96285. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96286. __decorate([
  96287. BABYLON.serializeAsTexture()
  96288. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96289. __decorate([
  96290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96291. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96292. __decorate([
  96293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96294. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96295. __decorate([
  96296. BABYLON.serialize()
  96297. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96298. __decorate([
  96299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96300. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96301. __decorate([
  96302. BABYLON.serializeAsVector3()
  96303. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96304. __decorate([
  96305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96306. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96307. __decorate([
  96308. BABYLON.serialize()
  96309. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96310. __decorate([
  96311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96312. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96313. __decorate([
  96314. BABYLON.serialize()
  96315. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96316. __decorate([
  96317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96318. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96319. __decorate([
  96320. BABYLON.serialize()
  96321. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96322. __decorate([
  96323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96324. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96325. __decorate([
  96326. BABYLON.serialize()
  96327. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96328. __decorate([
  96329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96330. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96331. __decorate([
  96332. BABYLON.serialize()
  96333. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96334. __decorate([
  96335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96336. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96337. __decorate([
  96338. BABYLON.serialize()
  96339. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96340. __decorate([
  96341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96342. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96343. __decorate([
  96344. BABYLON.serialize()
  96345. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96346. __decorate([
  96347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96348. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96349. __decorate([
  96350. BABYLON.serialize()
  96351. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96352. __decorate([
  96353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96354. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96355. __decorate([
  96356. BABYLON.serialize()
  96357. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96358. __decorate([
  96359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96360. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96361. __decorate([
  96362. BABYLON.serializeAsImageProcessingConfiguration()
  96363. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96364. return BackgroundMaterial;
  96365. }(BABYLON.PushMaterial));
  96366. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96367. })(BABYLON || (BABYLON = {}));
  96368. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96369. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96370. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96371. s = arguments[i];
  96372. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96373. t[p] = s[p];
  96374. }
  96375. return t;
  96376. };
  96377. var BABYLON;
  96378. (function (BABYLON) {
  96379. /**
  96380. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96381. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96382. * It also helps with the default setup of your imageProcessing configuration.
  96383. */
  96384. var EnvironmentHelper = /** @class */ (function () {
  96385. /**
  96386. * constructor
  96387. * @param options
  96388. * @param scene The scene to add the material to
  96389. */
  96390. function EnvironmentHelper(options, scene) {
  96391. var _this = this;
  96392. this._errorHandler = function (message, exception) {
  96393. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96394. };
  96395. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96396. this._scene = scene;
  96397. this.onErrorObservable = new BABYLON.Observable();
  96398. this._setupBackground();
  96399. this._setupImageProcessing();
  96400. }
  96401. /**
  96402. * Creates the default options for the helper.
  96403. */
  96404. EnvironmentHelper._getDefaultOptions = function () {
  96405. return {
  96406. createGround: true,
  96407. groundSize: 15,
  96408. groundTexture: this._groundTextureCDNUrl,
  96409. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96410. groundOpacity: 0.9,
  96411. enableGroundShadow: true,
  96412. groundShadowLevel: 0.5,
  96413. enableGroundMirror: false,
  96414. groundMirrorSizeRatio: 0.3,
  96415. groundMirrorBlurKernel: 64,
  96416. groundMirrorAmount: 1,
  96417. groundMirrorFresnelWeight: 1,
  96418. groundMirrorFallOffDistance: 0,
  96419. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  96420. groundYBias: 0.00001,
  96421. createSkybox: true,
  96422. skyboxSize: 20,
  96423. skyboxTexture: this._skyboxTextureCDNUrl,
  96424. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96425. backgroundYRotation: 0,
  96426. sizeAuto: true,
  96427. rootPosition: BABYLON.Vector3.Zero(),
  96428. setupImageProcessing: true,
  96429. environmentTexture: this._environmentTextureCDNUrl,
  96430. cameraExposure: 0.8,
  96431. cameraContrast: 1.2,
  96432. toneMappingEnabled: true,
  96433. };
  96434. };
  96435. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  96436. /**
  96437. * Gets the root mesh created by the helper.
  96438. */
  96439. get: function () {
  96440. return this._rootMesh;
  96441. },
  96442. enumerable: true,
  96443. configurable: true
  96444. });
  96445. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  96446. /**
  96447. * Gets the skybox created by the helper.
  96448. */
  96449. get: function () {
  96450. return this._skybox;
  96451. },
  96452. enumerable: true,
  96453. configurable: true
  96454. });
  96455. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  96456. /**
  96457. * Gets the skybox texture created by the helper.
  96458. */
  96459. get: function () {
  96460. return this._skyboxTexture;
  96461. },
  96462. enumerable: true,
  96463. configurable: true
  96464. });
  96465. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  96466. /**
  96467. * Gets the skybox material created by the helper.
  96468. */
  96469. get: function () {
  96470. return this._skyboxMaterial;
  96471. },
  96472. enumerable: true,
  96473. configurable: true
  96474. });
  96475. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  96476. /**
  96477. * Gets the ground mesh created by the helper.
  96478. */
  96479. get: function () {
  96480. return this._ground;
  96481. },
  96482. enumerable: true,
  96483. configurable: true
  96484. });
  96485. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  96486. /**
  96487. * Gets the ground texture created by the helper.
  96488. */
  96489. get: function () {
  96490. return this._groundTexture;
  96491. },
  96492. enumerable: true,
  96493. configurable: true
  96494. });
  96495. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  96496. /**
  96497. * Gets the ground mirror created by the helper.
  96498. */
  96499. get: function () {
  96500. return this._groundMirror;
  96501. },
  96502. enumerable: true,
  96503. configurable: true
  96504. });
  96505. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  96506. /**
  96507. * Gets the ground mirror render list to helps pushing the meshes
  96508. * you wish in the ground reflection.
  96509. */
  96510. get: function () {
  96511. if (this._groundMirror) {
  96512. return this._groundMirror.renderList;
  96513. }
  96514. return null;
  96515. },
  96516. enumerable: true,
  96517. configurable: true
  96518. });
  96519. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  96520. /**
  96521. * Gets the ground material created by the helper.
  96522. */
  96523. get: function () {
  96524. return this._groundMaterial;
  96525. },
  96526. enumerable: true,
  96527. configurable: true
  96528. });
  96529. /**
  96530. * Updates the background according to the new options
  96531. * @param options
  96532. */
  96533. EnvironmentHelper.prototype.updateOptions = function (options) {
  96534. var newOptions = __assign({}, this._options, options);
  96535. if (this._ground && !newOptions.createGround) {
  96536. this._ground.dispose();
  96537. this._ground = null;
  96538. }
  96539. if (this._groundMaterial && !newOptions.createGround) {
  96540. this._groundMaterial.dispose();
  96541. this._groundMaterial = null;
  96542. }
  96543. if (this._groundTexture) {
  96544. if (this._options.groundTexture != newOptions.groundTexture) {
  96545. this._groundTexture.dispose();
  96546. this._groundTexture = null;
  96547. }
  96548. }
  96549. if (this._skybox && !newOptions.createSkybox) {
  96550. this._skybox.dispose();
  96551. this._skybox = null;
  96552. }
  96553. if (this._skyboxMaterial && !newOptions.createSkybox) {
  96554. this._skyboxMaterial.dispose();
  96555. this._skyboxMaterial = null;
  96556. }
  96557. if (this._skyboxTexture) {
  96558. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  96559. this._skyboxTexture.dispose();
  96560. this._skyboxTexture = null;
  96561. }
  96562. }
  96563. if (this._groundMirror && !newOptions.enableGroundMirror) {
  96564. this._groundMirror.dispose();
  96565. this._groundMirror = null;
  96566. }
  96567. if (this._scene.environmentTexture) {
  96568. if (this._options.environmentTexture != newOptions.environmentTexture) {
  96569. this._scene.environmentTexture.dispose();
  96570. }
  96571. }
  96572. this._options = newOptions;
  96573. this._setupBackground();
  96574. this._setupImageProcessing();
  96575. };
  96576. /**
  96577. * Sets the primary color of all the available elements.
  96578. * @param color the main color to affect to the ground and the background
  96579. */
  96580. EnvironmentHelper.prototype.setMainColor = function (color) {
  96581. if (this.groundMaterial) {
  96582. this.groundMaterial.primaryColor = color;
  96583. }
  96584. if (this.skyboxMaterial) {
  96585. this.skyboxMaterial.primaryColor = color;
  96586. }
  96587. if (this.groundMirror) {
  96588. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  96589. }
  96590. };
  96591. /**
  96592. * Setup the image processing according to the specified options.
  96593. */
  96594. EnvironmentHelper.prototype._setupImageProcessing = function () {
  96595. if (this._options.setupImageProcessing) {
  96596. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  96597. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  96598. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  96599. this._setupEnvironmentTexture();
  96600. }
  96601. };
  96602. /**
  96603. * Setup the environment texture according to the specified options.
  96604. */
  96605. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  96606. if (this._scene.environmentTexture) {
  96607. return;
  96608. }
  96609. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  96610. this._scene.environmentTexture = this._options.environmentTexture;
  96611. return;
  96612. }
  96613. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  96614. this._scene.environmentTexture = environmentTexture;
  96615. };
  96616. /**
  96617. * Setup the background according to the specified options.
  96618. */
  96619. EnvironmentHelper.prototype._setupBackground = function () {
  96620. if (!this._rootMesh) {
  96621. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  96622. }
  96623. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  96624. var sceneSize = this._getSceneSize();
  96625. if (this._options.createGround) {
  96626. this._setupGround(sceneSize);
  96627. this._setupGroundMaterial();
  96628. this._setupGroundDiffuseTexture();
  96629. if (this._options.enableGroundMirror) {
  96630. this._setupGroundMirrorTexture(sceneSize);
  96631. }
  96632. this._setupMirrorInGroundMaterial();
  96633. }
  96634. if (this._options.createSkybox) {
  96635. this._setupSkybox(sceneSize);
  96636. this._setupSkyboxMaterial();
  96637. this._setupSkyboxReflectionTexture();
  96638. }
  96639. this._rootMesh.position.x = sceneSize.rootPosition.x;
  96640. this._rootMesh.position.z = sceneSize.rootPosition.z;
  96641. this._rootMesh.position.y = sceneSize.rootPosition.y;
  96642. };
  96643. /**
  96644. * Get the scene sizes according to the setup.
  96645. */
  96646. EnvironmentHelper.prototype._getSceneSize = function () {
  96647. var _this = this;
  96648. var groundSize = this._options.groundSize;
  96649. var skyboxSize = this._options.skyboxSize;
  96650. var rootPosition = this._options.rootPosition;
  96651. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  96652. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96653. }
  96654. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  96655. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  96656. });
  96657. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  96658. if (this._options.sizeAuto) {
  96659. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  96660. this._scene.activeCamera.upperRadiusLimit) {
  96661. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  96662. skyboxSize = groundSize;
  96663. }
  96664. var sceneDiagonalLenght = sceneDiagonal.length();
  96665. if (sceneDiagonalLenght > groundSize) {
  96666. groundSize = sceneDiagonalLenght * 2;
  96667. skyboxSize = groundSize;
  96668. }
  96669. // 10 % bigger.
  96670. groundSize *= 1.1;
  96671. skyboxSize *= 1.5;
  96672. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  96673. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  96674. }
  96675. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96676. };
  96677. /**
  96678. * Setup the ground according to the specified options.
  96679. */
  96680. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  96681. var _this = this;
  96682. if (!this._ground) {
  96683. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  96684. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  96685. this._ground.parent = this._rootMesh;
  96686. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  96687. }
  96688. this._ground.receiveShadows = this._options.enableGroundShadow;
  96689. };
  96690. /**
  96691. * Setup the ground material according to the specified options.
  96692. */
  96693. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  96694. if (!this._groundMaterial) {
  96695. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  96696. }
  96697. this._groundMaterial.alpha = this._options.groundOpacity;
  96698. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  96699. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  96700. this._groundMaterial.primaryColor = this._options.groundColor;
  96701. this._groundMaterial.useRGBColor = false;
  96702. this._groundMaterial.enableNoise = true;
  96703. if (this._ground) {
  96704. this._ground.material = this._groundMaterial;
  96705. }
  96706. };
  96707. /**
  96708. * Setup the ground diffuse texture according to the specified options.
  96709. */
  96710. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  96711. if (!this._groundMaterial) {
  96712. return;
  96713. }
  96714. if (this._groundTexture) {
  96715. return;
  96716. }
  96717. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  96718. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  96719. return;
  96720. }
  96721. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96722. diffuseTexture.gammaSpace = false;
  96723. diffuseTexture.hasAlpha = true;
  96724. this._groundMaterial.diffuseTexture = diffuseTexture;
  96725. };
  96726. /**
  96727. * Setup the ground mirror texture according to the specified options.
  96728. */
  96729. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  96730. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96731. if (!this._groundMirror) {
  96732. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  96733. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  96734. this._groundMirror.anisotropicFilteringLevel = 1;
  96735. this._groundMirror.wrapU = wrapping;
  96736. this._groundMirror.wrapV = wrapping;
  96737. this._groundMirror.gammaSpace = false;
  96738. if (this._groundMirror.renderList) {
  96739. for (var i = 0; i < this._scene.meshes.length; i++) {
  96740. var mesh = this._scene.meshes[i];
  96741. if (mesh !== this._ground &&
  96742. mesh !== this._skybox &&
  96743. mesh !== this._rootMesh) {
  96744. this._groundMirror.renderList.push(mesh);
  96745. }
  96746. }
  96747. }
  96748. }
  96749. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  96750. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  96751. };
  96752. /**
  96753. * Setup the ground to receive the mirror texture.
  96754. */
  96755. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  96756. if (this._groundMaterial) {
  96757. this._groundMaterial.reflectionTexture = this._groundMirror;
  96758. this._groundMaterial.reflectionFresnel = true;
  96759. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  96760. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  96761. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  96762. }
  96763. };
  96764. /**
  96765. * Setup the skybox according to the specified options.
  96766. */
  96767. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  96768. var _this = this;
  96769. if (!this._skybox) {
  96770. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  96771. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  96772. }
  96773. this._skybox.parent = this._rootMesh;
  96774. };
  96775. /**
  96776. * Setup the skybox material according to the specified options.
  96777. */
  96778. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  96779. if (!this._skybox) {
  96780. return;
  96781. }
  96782. if (!this._skyboxMaterial) {
  96783. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  96784. }
  96785. this._skyboxMaterial.useRGBColor = false;
  96786. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  96787. this._skyboxMaterial.enableNoise = true;
  96788. this._skybox.material = this._skyboxMaterial;
  96789. };
  96790. /**
  96791. * Setup the skybox reflection texture according to the specified options.
  96792. */
  96793. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  96794. if (!this._skyboxMaterial) {
  96795. return;
  96796. }
  96797. if (this._skyboxTexture) {
  96798. return;
  96799. }
  96800. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  96801. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  96802. return;
  96803. }
  96804. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96805. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  96806. this._skyboxTexture.gammaSpace = false;
  96807. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  96808. };
  96809. /**
  96810. * Dispose all the elements created by the Helper.
  96811. */
  96812. EnvironmentHelper.prototype.dispose = function () {
  96813. if (this._groundMaterial) {
  96814. this._groundMaterial.dispose(true, true);
  96815. }
  96816. if (this._skyboxMaterial) {
  96817. this._skyboxMaterial.dispose(true, true);
  96818. }
  96819. this._rootMesh.dispose(false);
  96820. };
  96821. /**
  96822. * Default ground texture URL.
  96823. */
  96824. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  96825. /**
  96826. * Default skybox texture URL.
  96827. */
  96828. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  96829. /**
  96830. * Default environment texture URL.
  96831. */
  96832. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  96833. return EnvironmentHelper;
  96834. }());
  96835. BABYLON.EnvironmentHelper = EnvironmentHelper;
  96836. })(BABYLON || (BABYLON = {}));
  96837. //# sourceMappingURL=babylon.environmentHelper.js.map
  96838. var BABYLON;
  96839. (function (BABYLON) {
  96840. /**
  96841. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  96842. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  96843. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  96844. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  96845. */
  96846. var VideoDome = /** @class */ (function (_super) {
  96847. __extends(VideoDome, _super);
  96848. /**
  96849. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  96850. * @param name Element's name, child elements will append suffixes for their own names.
  96851. * @param urlsOrVideo
  96852. * @param options An object containing optional or exposed sub element properties:
  96853. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  96854. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  96855. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  96856. * @param options **loop=true** Automatically loop video on end.
  96857. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  96858. */
  96859. function VideoDome(name, urlsOrVideo, options, scene) {
  96860. var _this = _super.call(this, name, scene) || this;
  96861. // set defaults and manage values
  96862. name = name || "videoDome";
  96863. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  96864. options.clickToPlay = Boolean(options.clickToPlay);
  96865. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  96866. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  96867. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  96868. // create
  96869. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  96870. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  96871. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  96872. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  96873. flat: false,
  96874. radius: options.size,
  96875. subdivisions: options.resolution,
  96876. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  96877. }, scene);
  96878. // configure material
  96879. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  96880. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  96881. material.reflectionTexture = _this._videoTexture;
  96882. material.useEquirectangularFOV = true;
  96883. material.fovMultiplier = 1.0;
  96884. // configure mesh
  96885. _this._mesh.material = material;
  96886. _this._mesh.parent = _this;
  96887. // optional configuration
  96888. if (options.clickToPlay) {
  96889. scene.onPointerUp = function () {
  96890. _this._videoTexture.video.play();
  96891. };
  96892. }
  96893. return _this;
  96894. }
  96895. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  96896. /**
  96897. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96898. * Also see the options.resolution property.
  96899. */
  96900. get: function () {
  96901. return this._material.fovMultiplier;
  96902. },
  96903. set: function (value) {
  96904. this._material.fovMultiplier = value;
  96905. },
  96906. enumerable: true,
  96907. configurable: true
  96908. });
  96909. /**
  96910. * Releases resources associated with this node.
  96911. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  96912. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  96913. */
  96914. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  96915. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  96916. this._videoTexture.dispose();
  96917. this._mesh.dispose();
  96918. this._material.dispose();
  96919. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  96920. };
  96921. return VideoDome;
  96922. }(BABYLON.Node));
  96923. BABYLON.VideoDome = VideoDome;
  96924. })(BABYLON || (BABYLON = {}));
  96925. //# sourceMappingURL=babylon.videoDome.js.map
  96926. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(GEOMETRYAA)\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#ifdef GEOMETRYAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  96927. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 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,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};