babylon.no-module.max.js 4.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. "use strict";
  4. var BABYLON;
  5. (function (BABYLON) {
  6. /**
  7. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  8. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  9. */
  10. var EffectFallbacks = /** @class */ (function () {
  11. function EffectFallbacks() {
  12. this._defines = {};
  13. this._currentRank = 32;
  14. this._maxRank = -1;
  15. }
  16. /**
  17. * Removes the fallback from the bound mesh.
  18. */
  19. EffectFallbacks.prototype.unBindMesh = function () {
  20. this._mesh = null;
  21. };
  22. /**
  23. * Adds a fallback on the specified property.
  24. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  25. * @param define The name of the define in the shader
  26. */
  27. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28. if (!this._defines[rank]) {
  29. if (rank < this._currentRank) {
  30. this._currentRank = rank;
  31. }
  32. if (rank > this._maxRank) {
  33. this._maxRank = rank;
  34. }
  35. this._defines[rank] = new Array();
  36. }
  37. this._defines[rank].push(define);
  38. };
  39. /**
  40. * Sets the mesh to use CPU skinning when needing to fallback.
  41. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  42. * @param mesh The mesh to use the fallbacks.
  43. */
  44. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  45. this._mesh = mesh;
  46. if (rank < this._currentRank) {
  47. this._currentRank = rank;
  48. }
  49. if (rank > this._maxRank) {
  50. this._maxRank = rank;
  51. }
  52. };
  53. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. get: function () {
  58. return this._currentRank <= this._maxRank;
  59. },
  60. enumerable: true,
  61. configurable: true
  62. });
  63. /**
  64. * Removes the defines that shoould be removed when falling back.
  65. * @param currentDefines defines the current define statements for the shader.
  66. * @param effect defines the current effect we try to compile
  67. * @returns The resulting defines with defines of the current rank removed.
  68. */
  69. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  70. // First we try to switch to CPU skinning
  71. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  72. this._mesh.computeBonesUsingShaders = false;
  73. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. this._uniformBuffersNames = {};
  163. this._isReady = false;
  164. this._compilationError = "";
  165. this.name = baseName;
  166. if (attributesNamesOrOptions.attributes) {
  167. var options = attributesNamesOrOptions;
  168. this._engine = uniformsNamesOrEngine;
  169. this._attributesNames = options.attributes;
  170. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  171. this._samplers = options.samplers.slice();
  172. this.defines = options.defines;
  173. this.onError = options.onError;
  174. this.onCompiled = options.onCompiled;
  175. this._fallbacks = options.fallbacks;
  176. this._indexParameters = options.indexParameters;
  177. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  178. if (options.uniformBuffersNames) {
  179. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  180. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  181. }
  182. }
  183. }
  184. else {
  185. this._engine = engine;
  186. this.defines = defines;
  187. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  188. this._samplers = samplers ? samplers.slice() : [];
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. var vertexSource;
  197. var fragmentSource;
  198. if (baseName.vertexElement) {
  199. vertexSource = document.getElementById(baseName.vertexElement);
  200. if (!vertexSource) {
  201. vertexSource = baseName.vertexElement;
  202. }
  203. }
  204. else {
  205. vertexSource = baseName.vertex || baseName;
  206. }
  207. if (baseName.fragmentElement) {
  208. fragmentSource = document.getElementById(baseName.fragmentElement);
  209. if (!fragmentSource) {
  210. fragmentSource = baseName.fragmentElement;
  211. }
  212. }
  213. else {
  214. fragmentSource = baseName.fragment || baseName;
  215. }
  216. this._loadVertexShader(vertexSource, function (vertexCode) {
  217. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  218. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  219. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  220. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  221. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  222. if (baseName) {
  223. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  224. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  225. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  226. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  227. }
  228. else {
  229. _this._vertexSourceCode = migratedVertexCode;
  230. _this._fragmentSourceCode = migratedFragmentCode;
  231. }
  232. _this._prepareEffect();
  233. });
  234. });
  235. });
  236. });
  237. });
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShader = function (vertex, callback) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. callback(vertexCode);
  352. return;
  353. }
  354. }
  355. // Base64 encoded ?
  356. if (vertex.substr(0, 7) === "base64:") {
  357. var vertexBinary = window.atob(vertex.substr(7));
  358. callback(vertexBinary);
  359. return;
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  364. return;
  365. }
  366. var vertexShaderUrl;
  367. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  368. vertexShaderUrl = vertex;
  369. }
  370. else {
  371. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  372. }
  373. // Vertex shader
  374. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  375. };
  376. /** @ignore */
  377. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  378. if (BABYLON.Tools.IsWindowObjectExist()) {
  379. // DOM element ?
  380. if (fragment instanceof HTMLElement) {
  381. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  382. callback(fragmentCode);
  383. return;
  384. }
  385. }
  386. // Base64 encoded ?
  387. if (fragment.substr(0, 7) === "base64:") {
  388. var fragmentBinary = window.atob(fragment.substr(7));
  389. callback(fragmentBinary);
  390. return;
  391. }
  392. // Is in local store ?
  393. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  394. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  395. return;
  396. }
  397. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  398. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  399. return;
  400. }
  401. var fragmentShaderUrl;
  402. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  403. fragmentShaderUrl = fragment;
  404. }
  405. else {
  406. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  407. }
  408. // Fragment shader
  409. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  410. };
  411. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  412. // Rebuild shaders source code
  413. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  414. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  415. vertexCode = prefix + vertexCode;
  416. fragmentCode = prefix + fragmentCode;
  417. // Number lines of shaders source code
  418. var i = 2;
  419. var regex = /\n/gm;
  420. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  421. i = 2;
  422. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. // Dump shaders name and formatted source code
  424. if (this.name.vertexElement) {
  425. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  426. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  427. }
  428. else if (this.name.vertex) {
  429. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  430. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  431. }
  432. else {
  433. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  434. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  435. }
  436. };
  437. ;
  438. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  439. var preparedSourceCode = this._processPrecision(sourceCode);
  440. if (this._engine.webGLVersion == 1) {
  441. callback(preparedSourceCode);
  442. return;
  443. }
  444. // Already converted
  445. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  446. callback(preparedSourceCode.replace("#version 300 es", ""));
  447. return;
  448. }
  449. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  450. // Remove extensions
  451. // #extension GL_OES_standard_derivatives : enable
  452. // #extension GL_EXT_shader_texture_lod : enable
  453. // #extension GL_EXT_frag_depth : enable
  454. // #extension GL_EXT_draw_buffers : require
  455. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  456. var result = preparedSourceCode.replace(regex, "");
  457. // Migrate to GLSL v300
  458. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  459. result = result.replace(/attribute[ \t]/g, "in ");
  460. result = result.replace(/[ \t]attribute/g, " in");
  461. if (isFragment) {
  462. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  464. result = result.replace(/texture2D\s*\(/g, "texture(");
  465. result = result.replace(/textureCube\s*\(/g, "texture(");
  466. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  467. result = result.replace(/gl_FragColor/g, "glFragColor");
  468. result = result.replace(/gl_FragData/g, "glFragData");
  469. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  470. }
  471. callback(result);
  472. };
  473. Effect.prototype._processIncludes = function (sourceCode, callback) {
  474. var _this = this;
  475. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  476. var match = regex.exec(sourceCode);
  477. var returnValue = new String(sourceCode);
  478. while (match != null) {
  479. var includeFile = match[1];
  480. // Uniform declaration
  481. if (includeFile.indexOf("__decl__") !== -1) {
  482. includeFile = includeFile.replace(/__decl__/, "");
  483. if (this._engine.supportsUniformBuffers) {
  484. includeFile = includeFile.replace(/Vertex/, "Ubo");
  485. includeFile = includeFile.replace(/Fragment/, "Ubo");
  486. }
  487. includeFile = includeFile + "Declaration";
  488. }
  489. if (Effect.IncludesShadersStore[includeFile]) {
  490. // Substitution
  491. var includeContent = Effect.IncludesShadersStore[includeFile];
  492. if (match[2]) {
  493. var splits = match[3].split(",");
  494. for (var index = 0; index < splits.length; index += 2) {
  495. var source = new RegExp(splits[index], "g");
  496. var dest = splits[index + 1];
  497. includeContent = includeContent.replace(source, dest);
  498. }
  499. }
  500. if (match[4]) {
  501. var indexString = match[5];
  502. if (indexString.indexOf("..") !== -1) {
  503. var indexSplits = indexString.split("..");
  504. var minIndex = parseInt(indexSplits[0]);
  505. var maxIndex = parseInt(indexSplits[1]);
  506. var sourceIncludeContent = includeContent.slice(0);
  507. includeContent = "";
  508. if (isNaN(maxIndex)) {
  509. maxIndex = this._indexParameters[indexSplits[1]];
  510. }
  511. for (var i = minIndex; i < maxIndex; i++) {
  512. if (!this._engine.supportsUniformBuffers) {
  513. // Ubo replacement
  514. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  515. return p1 + "{X}";
  516. });
  517. }
  518. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  519. }
  520. }
  521. else {
  522. if (!this._engine.supportsUniformBuffers) {
  523. // Ubo replacement
  524. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  525. return p1 + "{X}";
  526. });
  527. }
  528. includeContent = includeContent.replace(/\{X\}/g, indexString);
  529. }
  530. }
  531. // Replace
  532. returnValue = returnValue.replace(match[0], includeContent);
  533. }
  534. else {
  535. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  536. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  537. Effect.IncludesShadersStore[includeFile] = fileContent;
  538. _this._processIncludes(returnValue, callback);
  539. });
  540. return;
  541. }
  542. match = regex.exec(sourceCode);
  543. }
  544. callback(returnValue);
  545. };
  546. Effect.prototype._processPrecision = function (source) {
  547. if (source.indexOf("precision highp float") === -1) {
  548. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  549. source = "precision mediump float;\n" + source;
  550. }
  551. else {
  552. source = "precision highp float;\n" + source;
  553. }
  554. }
  555. else {
  556. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  557. source = source.replace("precision highp float", "precision mediump float");
  558. }
  559. }
  560. return source;
  561. };
  562. /**
  563. * Recompiles the webGL program
  564. * @param vertexSourceCode The source code for the vertex shader.
  565. * @param fragmentSourceCode The source code for the fragment shader.
  566. * @param onCompiled Callback called when completed.
  567. * @param onError Callback called on error.
  568. */
  569. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  570. var _this = this;
  571. this._isReady = false;
  572. this._vertexSourceCodeOverride = vertexSourceCode;
  573. this._fragmentSourceCodeOverride = fragmentSourceCode;
  574. this.onError = function (effect, error) {
  575. if (onError) {
  576. onError(error);
  577. }
  578. };
  579. this.onCompiled = function () {
  580. var scenes = _this.getEngine().scenes;
  581. for (var i = 0; i < scenes.length; i++) {
  582. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  583. }
  584. if (onCompiled) {
  585. onCompiled(_this._program);
  586. }
  587. };
  588. this._fallbacks = null;
  589. this._prepareEffect();
  590. };
  591. /**
  592. * Gets the uniform locations of the the specified variable names
  593. * @param names THe names of the variables to lookup.
  594. * @returns Array of locations in the same order as variable names.
  595. */
  596. Effect.prototype.getSpecificUniformLocations = function (names) {
  597. var engine = this._engine;
  598. return engine.getUniforms(this._program, names);
  599. };
  600. /**
  601. * Prepares the effect
  602. */
  603. Effect.prototype._prepareEffect = function () {
  604. var attributesNames = this._attributesNames;
  605. var defines = this.defines;
  606. var fallbacks = this._fallbacks;
  607. this._valueCache = {};
  608. var previousProgram = this._program;
  609. try {
  610. var engine = this._engine;
  611. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  612. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  613. }
  614. else {
  615. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  616. }
  617. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  618. if (engine.supportsUniformBuffers) {
  619. for (var name in this._uniformBuffersNames) {
  620. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  621. }
  622. }
  623. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  624. this._attributes = engine.getAttributes(this._program, attributesNames);
  625. var index;
  626. for (index = 0; index < this._samplers.length; index++) {
  627. var sampler = this.getUniform(this._samplers[index]);
  628. if (sampler == null) {
  629. this._samplers.splice(index, 1);
  630. index--;
  631. }
  632. }
  633. engine.bindSamplers(this);
  634. this._compilationError = "";
  635. this._isReady = true;
  636. if (this.onCompiled) {
  637. this.onCompiled(this);
  638. }
  639. this.onCompileObservable.notifyObservers(this);
  640. this.onCompileObservable.clear();
  641. // Unbind mesh reference in fallbacks
  642. if (this._fallbacks) {
  643. this._fallbacks.unBindMesh();
  644. }
  645. if (previousProgram) {
  646. this.getEngine()._deleteProgram(previousProgram);
  647. }
  648. }
  649. catch (e) {
  650. this._compilationError = e.message;
  651. // Let's go through fallbacks then
  652. BABYLON.Tools.Error("Unable to compile effect:");
  653. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  654. return " " + uniform;
  655. }));
  656. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  657. return " " + attribute;
  658. }));
  659. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  660. BABYLON.Tools.Error("Error: " + this._compilationError);
  661. if (previousProgram) {
  662. this._program = previousProgram;
  663. this._isReady = true;
  664. if (this.onError) {
  665. this.onError(this, this._compilationError);
  666. }
  667. this.onErrorObservable.notifyObservers(this);
  668. }
  669. if (fallbacks && fallbacks.isMoreFallbacks) {
  670. BABYLON.Tools.Error("Trying next fallback.");
  671. this.defines = fallbacks.reduce(this.defines, this);
  672. this._prepareEffect();
  673. }
  674. else {
  675. if (this.onError) {
  676. this.onError(this, this._compilationError);
  677. }
  678. this.onErrorObservable.notifyObservers(this);
  679. this.onErrorObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. }
  685. }
  686. };
  687. Object.defineProperty(Effect.prototype, "isSupported", {
  688. /**
  689. * Checks if the effect is supported. (Must be called after compilation)
  690. */
  691. get: function () {
  692. return this._compilationError === "";
  693. },
  694. enumerable: true,
  695. configurable: true
  696. });
  697. /**
  698. * Binds a texture to the engine to be used as output of the shader.
  699. * @param channel Name of the output variable.
  700. * @param texture Texture to bind.
  701. */
  702. Effect.prototype._bindTexture = function (channel, texture) {
  703. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  704. };
  705. /**
  706. * Sets a texture on the engine to be used in the shader.
  707. * @param channel Name of the sampler variable.
  708. * @param texture Texture to set.
  709. */
  710. Effect.prototype.setTexture = function (channel, texture) {
  711. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  712. };
  713. /**
  714. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  715. * @param channel Name of the sampler variable.
  716. * @param texture Texture to set.
  717. */
  718. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  719. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  720. };
  721. /**
  722. * Sets an array of textures on the engine to be used in the shader.
  723. * @param channel Name of the variable.
  724. * @param textures Textures to set.
  725. */
  726. Effect.prototype.setTextureArray = function (channel, textures) {
  727. if (this._samplers.indexOf(channel + "Ex") === -1) {
  728. var initialPos = this._samplers.indexOf(channel);
  729. for (var index = 1; index < textures.length; index++) {
  730. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  731. }
  732. }
  733. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  734. };
  735. /**
  736. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  737. * @param channel Name of the sampler variable.
  738. * @param postProcess Post process to get the input texture from.
  739. */
  740. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  741. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  742. };
  743. /**
  744. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  745. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  746. * @param channel Name of the sampler variable.
  747. * @param postProcess Post process to get the output texture from.
  748. */
  749. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  750. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  751. };
  752. /** @ignore */
  753. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  754. var cache = this._valueCache[uniformName];
  755. var flag = matrix.updateFlag;
  756. if (cache !== undefined && cache === flag) {
  757. return false;
  758. }
  759. this._valueCache[uniformName] = flag;
  760. return true;
  761. };
  762. /** @ignore */
  763. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  764. var cache = this._valueCache[uniformName];
  765. if (!cache) {
  766. cache = [x, y];
  767. this._valueCache[uniformName] = cache;
  768. return true;
  769. }
  770. var changed = false;
  771. if (cache[0] !== x) {
  772. cache[0] = x;
  773. changed = true;
  774. }
  775. if (cache[1] !== y) {
  776. cache[1] = y;
  777. changed = true;
  778. }
  779. return changed;
  780. };
  781. /** @ignore */
  782. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  783. var cache = this._valueCache[uniformName];
  784. if (!cache) {
  785. cache = [x, y, z];
  786. this._valueCache[uniformName] = cache;
  787. return true;
  788. }
  789. var changed = false;
  790. if (cache[0] !== x) {
  791. cache[0] = x;
  792. changed = true;
  793. }
  794. if (cache[1] !== y) {
  795. cache[1] = y;
  796. changed = true;
  797. }
  798. if (cache[2] !== z) {
  799. cache[2] = z;
  800. changed = true;
  801. }
  802. return changed;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y, z, w];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. if (cache[2] !== z) {
  822. cache[2] = z;
  823. changed = true;
  824. }
  825. if (cache[3] !== w) {
  826. cache[3] = w;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /**
  832. * Binds a buffer to a uniform.
  833. * @param buffer Buffer to bind.
  834. * @param name Name of the uniform variable to bind to.
  835. */
  836. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  837. var bufferName = this._uniformBuffersNames[name];
  838. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  839. return;
  840. }
  841. Effect._baseCache[bufferName] = buffer;
  842. this._engine.bindUniformBufferBase(buffer, bufferName);
  843. };
  844. /**
  845. * Binds block to a uniform.
  846. * @param blockName Name of the block to bind.
  847. * @param index Index to bind.
  848. */
  849. Effect.prototype.bindUniformBlock = function (blockName, index) {
  850. this._engine.bindUniformBlock(this._program, blockName, index);
  851. };
  852. /**
  853. * Sets an interger value on a uniform variable.
  854. * @param uniformName Name of the variable.
  855. * @param value Value to be set.
  856. * @returns this effect.
  857. */
  858. Effect.prototype.setInt = function (uniformName, value) {
  859. var cache = this._valueCache[uniformName];
  860. if (cache !== undefined && cache === value)
  861. return this;
  862. this._valueCache[uniformName] = value;
  863. this._engine.setInt(this.getUniform(uniformName), value);
  864. return this;
  865. };
  866. /**
  867. * Sets an int array on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param array array to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setIntArray = function (uniformName, array) {
  873. this._valueCache[uniformName] = null;
  874. this._engine.setIntArray(this.getUniform(uniformName), array);
  875. return this;
  876. };
  877. /**
  878. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  879. * @param uniformName Name of the variable.
  880. * @param array array to be set.
  881. * @returns this effect.
  882. */
  883. Effect.prototype.setIntArray2 = function (uniformName, array) {
  884. this._valueCache[uniformName] = null;
  885. this._engine.setIntArray2(this.getUniform(uniformName), array);
  886. return this;
  887. };
  888. /**
  889. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray3 = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray3(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray4 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray4(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * Sets an float array on a uniform variable.
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setFloatArray = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setFloatArray(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * Sets an array on a uniform variable.
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setArray = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setArray(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setArray2 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setArray2(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray3 = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray3(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray4 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray4(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * Sets matrices on a uniform variable.
  1000. * @param uniformName Name of the variable.
  1001. * @param matrices matrices to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1005. if (!matrices) {
  1006. return this;
  1007. }
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrix on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrix matrix to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1019. if (this._cacheMatrix(uniformName, matrix)) {
  1020. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1021. }
  1022. return this;
  1023. };
  1024. /**
  1025. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1026. * @param uniformName Name of the variable.
  1027. * @param matrix matrix to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1033. return this;
  1034. };
  1035. /**
  1036. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1037. * @param uniformName Name of the variable.
  1038. * @param matrix matrix to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1044. return this;
  1045. };
  1046. /**
  1047. * Sets a float on a uniform variable.
  1048. * @param uniformName Name of the variable.
  1049. * @param value value to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setFloat = function (uniformName, value) {
  1053. var cache = this._valueCache[uniformName];
  1054. if (cache !== undefined && cache === value)
  1055. return this;
  1056. this._valueCache[uniformName] = value;
  1057. this._engine.setFloat(this.getUniform(uniformName), value);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a boolean on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param bool value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setBool = function (uniformName, bool) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === bool)
  1069. return this;
  1070. this._valueCache[uniformName] = bool;
  1071. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a Vector2 on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param vector2 vector2 to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1081. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1082. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1083. }
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a float2 on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param x First float in float2.
  1090. * @param y Second float in float2.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1094. if (this._cacheFloat2(uniformName, x, y)) {
  1095. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1096. }
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets a Vector3 on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param vector3 Value to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1106. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1107. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1108. }
  1109. return this;
  1110. };
  1111. /**
  1112. * Sets a float3 on a uniform variable.
  1113. * @param uniformName Name of the variable.
  1114. * @param x First float in float3.
  1115. * @param y Second float in float3.
  1116. * @param z Third float in float3.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1120. if (this._cacheFloat3(uniformName, x, y, z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector4 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector4 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1132. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1133. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float4 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float4.
  1141. * @param y Second float in float4.
  1142. * @param z Third float in float4.
  1143. * @param w Fourth float in float4.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1147. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1148. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Color3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param color3 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setColor3 = function (uniformName, color3) {
  1159. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1160. this._engine.setColor3(this.getUniform(uniformName), color3);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a Color4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param color3 Value to be set.
  1168. * @param alpha Alpha value to be set.
  1169. * @returns this effect.
  1170. */
  1171. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1172. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1173. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1174. }
  1175. return this;
  1176. };
  1177. /**
  1178. * Sets a Color4 on a uniform variable
  1179. * @param uniformName defines the name of the variable
  1180. * @param color4 defines the value to be set
  1181. * @returns this effect.
  1182. */
  1183. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1184. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1185. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1186. }
  1187. return this;
  1188. };
  1189. /**
  1190. * Resets the cache of effects.
  1191. */
  1192. Effect.ResetCache = function () {
  1193. Effect._baseCache = {};
  1194. };
  1195. Effect._uniqueIdSeed = 0;
  1196. Effect._baseCache = {};
  1197. /**
  1198. * Store of each shader (The can be looked up using effect.key)
  1199. */
  1200. Effect.ShadersStore = {};
  1201. /**
  1202. * Store of each included file for a shader (The can be looked up using effect.key)
  1203. */
  1204. Effect.IncludesShadersStore = {};
  1205. return Effect;
  1206. }());
  1207. BABYLON.Effect = Effect;
  1208. })(BABYLON || (BABYLON = {}));
  1209. //# sourceMappingURL=babylon.effect.js.map
  1210. "use strict";
  1211. //# sourceMappingURL=babylon.types.js.map
  1212. "use strict";
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. "use strict";
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var PointerEventTypes = /** @class */ (function () {
  1265. function PointerEventTypes() {
  1266. }
  1267. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1268. get: function () {
  1269. return PointerEventTypes._POINTERDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1275. get: function () {
  1276. return PointerEventTypes._POINTERUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1282. get: function () {
  1283. return PointerEventTypes._POINTERMOVE;
  1284. },
  1285. enumerable: true,
  1286. configurable: true
  1287. });
  1288. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1289. get: function () {
  1290. return PointerEventTypes._POINTERWHEEL;
  1291. },
  1292. enumerable: true,
  1293. configurable: true
  1294. });
  1295. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1296. get: function () {
  1297. return PointerEventTypes._POINTERPICK;
  1298. },
  1299. enumerable: true,
  1300. configurable: true
  1301. });
  1302. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1303. get: function () {
  1304. return PointerEventTypes._POINTERTAP;
  1305. },
  1306. enumerable: true,
  1307. configurable: true
  1308. });
  1309. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1310. get: function () {
  1311. return PointerEventTypes._POINTERDOUBLETAP;
  1312. },
  1313. enumerable: true,
  1314. configurable: true
  1315. });
  1316. PointerEventTypes._POINTERDOWN = 0x01;
  1317. PointerEventTypes._POINTERUP = 0x02;
  1318. PointerEventTypes._POINTERMOVE = 0x04;
  1319. PointerEventTypes._POINTERWHEEL = 0x08;
  1320. PointerEventTypes._POINTERPICK = 0x10;
  1321. PointerEventTypes._POINTERTAP = 0x20;
  1322. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1323. return PointerEventTypes;
  1324. }());
  1325. BABYLON.PointerEventTypes = PointerEventTypes;
  1326. var PointerInfoBase = /** @class */ (function () {
  1327. function PointerInfoBase(type, event) {
  1328. this.type = type;
  1329. this.event = event;
  1330. }
  1331. return PointerInfoBase;
  1332. }());
  1333. BABYLON.PointerInfoBase = PointerInfoBase;
  1334. /**
  1335. * This class is used to store pointer related info for the onPrePointerObservable event.
  1336. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1337. */
  1338. var PointerInfoPre = /** @class */ (function (_super) {
  1339. __extends(PointerInfoPre, _super);
  1340. function PointerInfoPre(type, event, localX, localY) {
  1341. var _this = _super.call(this, type, event) || this;
  1342. _this.skipOnPointerObservable = false;
  1343. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1344. return _this;
  1345. }
  1346. return PointerInfoPre;
  1347. }(PointerInfoBase));
  1348. BABYLON.PointerInfoPre = PointerInfoPre;
  1349. /**
  1350. * This type contains all the data related to a pointer event in Babylon.js.
  1351. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1352. */
  1353. var PointerInfo = /** @class */ (function (_super) {
  1354. __extends(PointerInfo, _super);
  1355. function PointerInfo(type, event, pickInfo) {
  1356. var _this = _super.call(this, type, event) || this;
  1357. _this.pickInfo = pickInfo;
  1358. return _this;
  1359. }
  1360. return PointerInfo;
  1361. }(PointerInfoBase));
  1362. BABYLON.PointerInfo = PointerInfo;
  1363. })(BABYLON || (BABYLON = {}));
  1364. //# sourceMappingURL=babylon.pointerEvents.js.map
  1365. "use strict";
  1366. var BABYLON;
  1367. (function (BABYLON) {
  1368. BABYLON.ToGammaSpace = 1 / 2.2;
  1369. BABYLON.ToLinearSpace = 2.2;
  1370. BABYLON.Epsilon = 0.001;
  1371. /**
  1372. * Class used to hold a RBG color
  1373. */
  1374. var Color3 = /** @class */ (function () {
  1375. /**
  1376. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1377. * @param r defines the red component (between 0 and 1, default is 0)
  1378. * @param g defines the green component (between 0 and 1, default is 0)
  1379. * @param b defines the blue component (between 0 and 1, default is 0)
  1380. */
  1381. function Color3(
  1382. /**
  1383. * Defines the red component (between 0 and 1, default is 0)
  1384. */
  1385. r,
  1386. /**
  1387. * Defines the green component (between 0 and 1, default is 0)
  1388. */
  1389. g,
  1390. /**
  1391. * Defines the blue component (between 0 and 1, default is 0)
  1392. */
  1393. b) {
  1394. if (r === void 0) { r = 0; }
  1395. if (g === void 0) { g = 0; }
  1396. if (b === void 0) { b = 0; }
  1397. this.r = r;
  1398. this.g = g;
  1399. this.b = b;
  1400. }
  1401. /**
  1402. * Creates a string with the Color3 current values
  1403. * @returns the string representation of the Color3 object
  1404. */
  1405. Color3.prototype.toString = function () {
  1406. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1407. };
  1408. /**
  1409. * Returns the string "Color3"
  1410. * @returns "Color3"
  1411. */
  1412. Color3.prototype.getClassName = function () {
  1413. return "Color3";
  1414. };
  1415. /**
  1416. * Compute the Color3 hash code
  1417. * @returns an unique number that can be used to hash Color3 objects
  1418. */
  1419. Color3.prototype.getHashCode = function () {
  1420. var hash = this.r || 0;
  1421. hash = (hash * 397) ^ (this.g || 0);
  1422. hash = (hash * 397) ^ (this.b || 0);
  1423. return hash;
  1424. };
  1425. // Operators
  1426. /**
  1427. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1428. * @param array defines the array where to store the r,g,b components
  1429. * @param index defines an optional index in the target array to define where to start storing values
  1430. * @returns the current Color3 object
  1431. */
  1432. Color3.prototype.toArray = function (array, index) {
  1433. if (index === undefined) {
  1434. index = 0;
  1435. }
  1436. array[index] = this.r;
  1437. array[index + 1] = this.g;
  1438. array[index + 2] = this.b;
  1439. return this;
  1440. };
  1441. /**
  1442. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1443. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1444. * @returns a new {BABYLON.Color4} object
  1445. */
  1446. Color3.prototype.toColor4 = function (alpha) {
  1447. if (alpha === void 0) { alpha = 1; }
  1448. return new Color4(this.r, this.g, this.b, alpha);
  1449. };
  1450. /**
  1451. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1452. * @returns the new array
  1453. */
  1454. Color3.prototype.asArray = function () {
  1455. var result = new Array();
  1456. this.toArray(result, 0);
  1457. return result;
  1458. };
  1459. /**
  1460. * Returns the luminance value
  1461. * @returns a float value
  1462. */
  1463. Color3.prototype.toLuminance = function () {
  1464. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1465. };
  1466. /**
  1467. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1468. * @param otherColor defines the second operand
  1469. * @returns the new Color3 object
  1470. */
  1471. Color3.prototype.multiply = function (otherColor) {
  1472. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1473. };
  1474. /**
  1475. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1476. * @param otherColor defines the second operand
  1477. * @param result defines the Color3 object where to store the result
  1478. * @returns the current Color3
  1479. */
  1480. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1481. result.r = this.r * otherColor.r;
  1482. result.g = this.g * otherColor.g;
  1483. result.b = this.b * otherColor.b;
  1484. return this;
  1485. };
  1486. /**
  1487. * Determines equality between Color3 objects
  1488. * @param otherColor defines the second operand
  1489. * @returns true if the rgb values are equal to the passed ones
  1490. */
  1491. Color3.prototype.equals = function (otherColor) {
  1492. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1493. };
  1494. /**
  1495. * Determines equality between the current Color3 object and a set of r,b,g values
  1496. * @param r defines the red component to check
  1497. * @param g defines the green component to check
  1498. * @param b defines the blue component to check
  1499. * @returns true if the rgb values are equal to the passed ones
  1500. */
  1501. Color3.prototype.equalsFloats = function (r, g, b) {
  1502. return this.r === r && this.g === g && this.b === b;
  1503. };
  1504. /**
  1505. * Multiplies in place each rgb value by scale
  1506. * @param scale defines the scaling factor
  1507. * @returns the updated Color3
  1508. */
  1509. Color3.prototype.scale = function (scale) {
  1510. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1511. };
  1512. /**
  1513. * Multiplies the rgb values by scale and stores the result into "result"
  1514. * @param scale defines the scaling factor
  1515. * @param result defines the Color3 object where to store the result
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.scaleToRef = function (scale, result) {
  1519. result.r = this.r * scale;
  1520. result.g = this.g * scale;
  1521. result.b = this.b * scale;
  1522. return this;
  1523. };
  1524. /**
  1525. * Scale the current Color3 values by a factor and add the result to a given Color3
  1526. * @param scale defines the scale factor
  1527. * @param result defines color to store the result into
  1528. * @returns the unmodified current Color3
  1529. */
  1530. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1531. result.r += this.r * scale;
  1532. result.g += this.g * scale;
  1533. result.b += this.b * scale;
  1534. return this;
  1535. };
  1536. /**
  1537. * Clamps the rgb values by the min and max values and stores the result into "result"
  1538. * @param min defines minimum clamping value (default is 0)
  1539. * @param max defines maximum clamping value (default is 1)
  1540. * @param result defines color to store the result into
  1541. * @returns the original Color3
  1542. */
  1543. Color3.prototype.clampToRef = function (min, max, result) {
  1544. if (min === void 0) { min = 0; }
  1545. if (max === void 0) { max = 1; }
  1546. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1547. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1548. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1549. return this;
  1550. };
  1551. /**
  1552. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1553. * @param otherColor defines the second operand
  1554. * @returns the new Color3
  1555. */
  1556. Color3.prototype.add = function (otherColor) {
  1557. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1558. };
  1559. /**
  1560. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1561. * @param otherColor defines the second operand
  1562. * @param result defines Color3 object to store the result into
  1563. * @returns the unmodified current Color3
  1564. */
  1565. Color3.prototype.addToRef = function (otherColor, result) {
  1566. result.r = this.r + otherColor.r;
  1567. result.g = this.g + otherColor.g;
  1568. result.b = this.b + otherColor.b;
  1569. return this;
  1570. };
  1571. /**
  1572. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3
  1575. */
  1576. Color3.prototype.subtract = function (otherColor) {
  1577. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1578. };
  1579. /**
  1580. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines Color3 object to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.subtractToRef = function (otherColor, result) {
  1586. result.r = this.r - otherColor.r;
  1587. result.g = this.g - otherColor.g;
  1588. result.b = this.b - otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Copy the current object
  1593. * @returns a new Color3 copied the current one
  1594. */
  1595. Color3.prototype.clone = function () {
  1596. return new Color3(this.r, this.g, this.b);
  1597. };
  1598. /**
  1599. * Copies the rgb values from the source in the current Color3
  1600. * @param source defines the source Color3 object
  1601. * @returns the updated Color3 object
  1602. */
  1603. Color3.prototype.copyFrom = function (source) {
  1604. this.r = source.r;
  1605. this.g = source.g;
  1606. this.b = source.b;
  1607. return this;
  1608. };
  1609. /**
  1610. * Updates the Color3 rgb values from the passed floats
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @returns the current Color3 object
  1615. */
  1616. Color3.prototype.copyFromFloats = function (r, g, b) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. return this;
  1621. };
  1622. /**
  1623. * Updates the Color3 rgb values from the passed floats
  1624. * @param r defines the red component to read from
  1625. * @param g defines the green component to read from
  1626. * @param b defines the blue component to read from
  1627. * @returns the current Color3 object
  1628. */
  1629. Color3.prototype.set = function (r, g, b) {
  1630. return this.copyFromFloats(r, g, b);
  1631. };
  1632. /**
  1633. * Compute the Color3 hexadecimal code as a string
  1634. * @returns a string containing the hexadecimal representation of the Color3 object
  1635. */
  1636. Color3.prototype.toHexString = function () {
  1637. var intR = (this.r * 255) | 0;
  1638. var intG = (this.g * 255) | 0;
  1639. var intB = (this.b * 255) | 0;
  1640. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1641. };
  1642. /**
  1643. * Computes a new Color3 converted from the current one to linear space
  1644. * @returns a new Color3 object
  1645. */
  1646. Color3.prototype.toLinearSpace = function () {
  1647. var convertedColor = new Color3();
  1648. this.toLinearSpaceToRef(convertedColor);
  1649. return convertedColor;
  1650. };
  1651. /**
  1652. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1653. * @param convertedColor defines the Color3 object where to store the linear space version
  1654. * @returns the unmodified Color3
  1655. */
  1656. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1657. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1658. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1659. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1660. return this;
  1661. };
  1662. /**
  1663. * Computes a new Color3 converted from the current one to gamma space
  1664. * @returns a new Color3 object
  1665. */
  1666. Color3.prototype.toGammaSpace = function () {
  1667. var convertedColor = new Color3();
  1668. this.toGammaSpaceToRef(convertedColor);
  1669. return convertedColor;
  1670. };
  1671. /**
  1672. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1673. * @param convertedColor defines the Color3 object where to store the gamma space version
  1674. * @returns the unmodified Color3
  1675. */
  1676. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1677. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1678. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1679. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1680. return this;
  1681. };
  1682. // Statics
  1683. /**
  1684. * Creates a new Color3 from the string containing valid hexadecimal values
  1685. * @param hex defines a string containing valid hexadecimal values
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.FromHexString = function (hex) {
  1689. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1690. return new Color3(0, 0, 0);
  1691. }
  1692. var r = parseInt(hex.substring(1, 3), 16);
  1693. var g = parseInt(hex.substring(3, 5), 16);
  1694. var b = parseInt(hex.substring(5, 7), 16);
  1695. return Color3.FromInts(r, g, b);
  1696. };
  1697. /**
  1698. * Creates a new Vector3 from the starting index of the passed array
  1699. * @param array defines the source array
  1700. * @param offset defines an offset in the source array
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.FromArray = function (array, offset) {
  1704. if (offset === void 0) { offset = 0; }
  1705. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1706. };
  1707. /**
  1708. * Creates a new Color3 from integer values (< 256)
  1709. * @param r defines the red component to read from (value between 0 and 255)
  1710. * @param g defines the green component to read from (value between 0 and 255)
  1711. * @param b defines the blue component to read from (value between 0 and 255)
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.FromInts = function (r, g, b) {
  1715. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1716. };
  1717. /**
  1718. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1719. * @param start defines the start Color3 value
  1720. * @param end defines the end Color3 value
  1721. * @param amount defines the gradient value between start and end
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Lerp = function (start, end, amount) {
  1725. var r = start.r + ((end.r - start.r) * amount);
  1726. var g = start.g + ((end.g - start.g) * amount);
  1727. var b = start.b + ((end.b - start.b) * amount);
  1728. return new Color3(r, g, b);
  1729. };
  1730. /**
  1731. * Returns a Color3 value containing a red color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Red = function () { return new Color3(1, 0, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a green color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Green = function () { return new Color3(0, 1, 0); };
  1740. /**
  1741. * Returns a Color3 value containing a blue color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1745. /**
  1746. * Returns a Color3 value containing a black color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Black = function () { return new Color3(0, 0, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a white color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.White = function () { return new Color3(1, 1, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a purple color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1760. /**
  1761. * Returns a Color3 value containing a magenta color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a yellow color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a gray color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1775. /**
  1776. * Returns a Color3 value containing a teal color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1780. /**
  1781. * Returns a Color3 value containing a random color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1785. return Color3;
  1786. }());
  1787. BABYLON.Color3 = Color3;
  1788. /**
  1789. * Class used to hold a RBGA color
  1790. */
  1791. var Color4 = /** @class */ (function () {
  1792. /**
  1793. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1794. * @param r defines the red component (between 0 and 1, default is 0)
  1795. * @param g defines the green component (between 0 and 1, default is 0)
  1796. * @param b defines the blue component (between 0 and 1, default is 0)
  1797. * @param a defines the alpha component (between 0 and 1, default is 1)
  1798. */
  1799. function Color4(
  1800. /**
  1801. * Defines the red component (between 0 and 1, default is 0)
  1802. */
  1803. r,
  1804. /**
  1805. * Defines the green component (between 0 and 1, default is 0)
  1806. */
  1807. g,
  1808. /**
  1809. * Defines the blue component (between 0 and 1, default is 0)
  1810. */
  1811. b,
  1812. /**
  1813. * Defines the alpha component (between 0 and 1, default is 1)
  1814. */
  1815. a) {
  1816. if (r === void 0) { r = 0; }
  1817. if (g === void 0) { g = 0; }
  1818. if (b === void 0) { b = 0; }
  1819. if (a === void 0) { a = 1; }
  1820. this.r = r;
  1821. this.g = g;
  1822. this.b = b;
  1823. this.a = a;
  1824. }
  1825. // Operators
  1826. /**
  1827. * Adds in place the passed Color4 values to the current Color4 object
  1828. * @param right defines the second operand
  1829. * @returns the current updated Color4 object
  1830. */
  1831. Color4.prototype.addInPlace = function (right) {
  1832. this.r += right.r;
  1833. this.g += right.g;
  1834. this.b += right.b;
  1835. this.a += right.a;
  1836. return this;
  1837. };
  1838. /**
  1839. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1840. * @returns the new array
  1841. */
  1842. Color4.prototype.asArray = function () {
  1843. var result = new Array();
  1844. this.toArray(result, 0);
  1845. return result;
  1846. };
  1847. /**
  1848. * Stores from the starting index in the passed array the Color4 successive values
  1849. * @param array defines the array where to store the r,g,b components
  1850. * @param index defines an optional index in the target array to define where to start storing values
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.toArray = function (array, index) {
  1854. if (index === undefined) {
  1855. index = 0;
  1856. }
  1857. array[index] = this.r;
  1858. array[index + 1] = this.g;
  1859. array[index + 2] = this.b;
  1860. array[index + 3] = this.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.add = function (right) {
  1869. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1870. };
  1871. /**
  1872. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1873. * @param right defines the second operand
  1874. * @returns a new Color4 object
  1875. */
  1876. Color4.prototype.subtract = function (right) {
  1877. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1878. };
  1879. /**
  1880. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1881. * @param right defines the second operand
  1882. * @param result defines the Color4 object where to store the result
  1883. * @returns the current Color4 object
  1884. */
  1885. Color4.prototype.subtractToRef = function (right, result) {
  1886. result.r = this.r - right.r;
  1887. result.g = this.g - right.g;
  1888. result.b = this.b - right.b;
  1889. result.a = this.a - right.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 with the current Color4 values multiplied by scale
  1894. * @param scale defines the scaling factor to apply
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.scale = function (scale) {
  1898. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1899. };
  1900. /**
  1901. * Multiplies the current Color4 values by scale and stores the result in "result"
  1902. * @param scale defines the scaling factor to apply
  1903. * @param result defines the Color4 object where to store the result
  1904. * @returns the current unmodified Color4
  1905. */
  1906. Color4.prototype.scaleToRef = function (scale, result) {
  1907. result.r = this.r * scale;
  1908. result.g = this.g * scale;
  1909. result.b = this.b * scale;
  1910. result.a = this.a * scale;
  1911. return this;
  1912. };
  1913. /**
  1914. * Scale the current Color4 values by a factor and add the result to a given Color4
  1915. * @param scale defines the scale factor
  1916. * @param result defines the Color4 object where to store the result
  1917. * @returns the unmodified current Color4
  1918. */
  1919. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1920. result.r += this.r * scale;
  1921. result.g += this.g * scale;
  1922. result.b += this.b * scale;
  1923. result.a += this.a * scale;
  1924. return this;
  1925. };
  1926. /**
  1927. * Clamps the rgb values by the min and max values and stores the result into "result"
  1928. * @param min defines minimum clamping value (default is 0)
  1929. * @param max defines maximum clamping value (default is 1)
  1930. * @param result defines color to store the result into.
  1931. * @returns the cuurent Color4
  1932. */
  1933. Color4.prototype.clampToRef = function (min, max, result) {
  1934. if (min === void 0) { min = 0; }
  1935. if (max === void 0) { max = 1; }
  1936. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1937. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1938. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1939. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1940. return this;
  1941. };
  1942. /**
  1943. * Multipy an Color4 value by another and return a new Color4 object
  1944. * @param color defines the Color4 value to multiply by
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.multiply = function (color) {
  1948. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1949. };
  1950. /**
  1951. * Multipy a Color4 value by another and push the result in a reference value
  1952. * @param color defines the Color4 value to multiply by
  1953. * @param result defines the Color4 to fill the result in
  1954. * @returns the result Color4
  1955. */
  1956. Color4.prototype.multiplyToRef = function (color, result) {
  1957. result.r = this.r * color.r;
  1958. result.g = this.g * color.g;
  1959. result.b = this.b * color.b;
  1960. result.a = this.a * color.a;
  1961. return result;
  1962. };
  1963. /**
  1964. * Creates a string with the Color4 current values
  1965. * @returns the string representation of the Color4 object
  1966. */
  1967. Color4.prototype.toString = function () {
  1968. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1969. };
  1970. /**
  1971. * Returns the string "Color4"
  1972. * @returns "Color4"
  1973. */
  1974. Color4.prototype.getClassName = function () {
  1975. return "Color4";
  1976. };
  1977. /**
  1978. * Compute the Color4 hash code
  1979. * @returns an unique number that can be used to hash Color4 objects
  1980. */
  1981. Color4.prototype.getHashCode = function () {
  1982. var hash = this.r || 0;
  1983. hash = (hash * 397) ^ (this.g || 0);
  1984. hash = (hash * 397) ^ (this.b || 0);
  1985. hash = (hash * 397) ^ (this.a || 0);
  1986. return hash;
  1987. };
  1988. /**
  1989. * Creates a new Color4 copied from the current one
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.clone = function () {
  1993. return new Color4(this.r, this.g, this.b, this.a);
  1994. };
  1995. /**
  1996. * Copies the passed Color4 values into the current one
  1997. * @param source defines the source Color4 object
  1998. * @returns the current updated Color4 object
  1999. */
  2000. Color4.prototype.copyFrom = function (source) {
  2001. this.r = source.r;
  2002. this.g = source.g;
  2003. this.b = source.b;
  2004. this.a = source.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Copies the passed float values into the current one
  2009. * @param r defines the red component to read from
  2010. * @param g defines the green component to read from
  2011. * @param b defines the blue component to read from
  2012. * @param a defines the alpha component to read from
  2013. * @returns the current updated Color4 object
  2014. */
  2015. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2016. this.r = r;
  2017. this.g = g;
  2018. this.b = b;
  2019. this.a = a;
  2020. return this;
  2021. };
  2022. /**
  2023. * Copies the passed float values into the current one
  2024. * @param r defines the red component to read from
  2025. * @param g defines the green component to read from
  2026. * @param b defines the blue component to read from
  2027. * @param a defines the alpha component to read from
  2028. * @returns the current updated Color4 object
  2029. */
  2030. Color4.prototype.set = function (r, g, b, a) {
  2031. return this.copyFromFloats(r, g, b, a);
  2032. };
  2033. /**
  2034. * Compute the Color4 hexadecimal code as a string
  2035. * @returns a string containing the hexadecimal representation of the Color4 object
  2036. */
  2037. Color4.prototype.toHexString = function () {
  2038. var intR = (this.r * 255) | 0;
  2039. var intG = (this.g * 255) | 0;
  2040. var intB = (this.b * 255) | 0;
  2041. var intA = (this.a * 255) | 0;
  2042. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to linear space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toLinearSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toLinearSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the linear space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. /**
  2066. * Computes a new Color4 converted from the current one to gamma space
  2067. * @returns a new Color4 object
  2068. */
  2069. Color4.prototype.toGammaSpace = function () {
  2070. var convertedColor = new Color4();
  2071. this.toGammaSpaceToRef(convertedColor);
  2072. return convertedColor;
  2073. };
  2074. /**
  2075. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2076. * @param convertedColor defines the Color4 object where to store the gamma space version
  2077. * @returns the unmodified Color4
  2078. */
  2079. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2080. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2081. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2082. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2083. convertedColor.a = this.a;
  2084. return this;
  2085. };
  2086. // Statics
  2087. /**
  2088. * Creates a new Color4 from the string containing valid hexadecimal values
  2089. * @param hex defines a string containing valid hexadecimal values
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.FromHexString = function (hex) {
  2093. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2094. return new Color4(0.0, 0.0, 0.0, 0.0);
  2095. }
  2096. var r = parseInt(hex.substring(1, 3), 16);
  2097. var g = parseInt(hex.substring(3, 5), 16);
  2098. var b = parseInt(hex.substring(5, 7), 16);
  2099. var a = parseInt(hex.substring(7, 9), 16);
  2100. return Color4.FromInts(r, g, b, a);
  2101. };
  2102. /**
  2103. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2104. * @param left defines the start value
  2105. * @param right defines the end value
  2106. * @param amount defines the gradient factor
  2107. * @returns a new Color4 object
  2108. */
  2109. Color4.Lerp = function (left, right, amount) {
  2110. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2111. Color4.LerpToRef(left, right, amount, result);
  2112. return result;
  2113. };
  2114. /**
  2115. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2116. * @param left defines the start value
  2117. * @param right defines the end value
  2118. * @param amount defines the gradient factor
  2119. * @param result defines the Color4 object where to store data
  2120. */
  2121. Color4.LerpToRef = function (left, right, amount, result) {
  2122. result.r = left.r + (right.r - left.r) * amount;
  2123. result.g = left.g + (right.g - left.g) * amount;
  2124. result.b = left.b + (right.b - left.b) * amount;
  2125. result.a = left.a + (right.a - left.a) * amount;
  2126. };
  2127. /**
  2128. * Creates a new Color4 from the starting index element of the passed array
  2129. * @param array defines the source array to read from
  2130. * @param offset defines the offset in the source array
  2131. * @returns a new Color4 object
  2132. */
  2133. Color4.FromArray = function (array, offset) {
  2134. if (offset === void 0) { offset = 0; }
  2135. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2136. };
  2137. /**
  2138. * Creates a new Color3 from integer values (< 256)
  2139. * @param r defines the red component to read from (value between 0 and 255)
  2140. * @param g defines the green component to read from (value between 0 and 255)
  2141. * @param b defines the blue component to read from (value between 0 and 255)
  2142. * @param a defines the alpha component to read from (value between 0 and 255)
  2143. * @returns a new Color3 object
  2144. */
  2145. Color4.FromInts = function (r, g, b, a) {
  2146. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2147. };
  2148. /**
  2149. * Check the content of a given array and convert it to an array containing RGBA data
  2150. * If the original array was already containing count * 4 values then it is returned directly
  2151. * @param colors defines the array to check
  2152. * @param count defines the number of RGBA data to expect
  2153. * @returns an array containing count * 4 values (RGBA)
  2154. */
  2155. Color4.CheckColors4 = function (colors, count) {
  2156. // Check if color3 was used
  2157. if (colors.length === count * 3) {
  2158. var colors4 = [];
  2159. for (var index = 0; index < colors.length; index += 3) {
  2160. var newIndex = (index / 3) * 4;
  2161. colors4[newIndex] = colors[index];
  2162. colors4[newIndex + 1] = colors[index + 1];
  2163. colors4[newIndex + 2] = colors[index + 2];
  2164. colors4[newIndex + 3] = 1.0;
  2165. }
  2166. return colors4;
  2167. }
  2168. return colors;
  2169. };
  2170. return Color4;
  2171. }());
  2172. BABYLON.Color4 = Color4;
  2173. var Vector2 = /** @class */ (function () {
  2174. /**
  2175. * Creates a new Vector2 from the passed x and y coordinates.
  2176. */
  2177. function Vector2(x, y) {
  2178. this.x = x;
  2179. this.y = y;
  2180. }
  2181. /**
  2182. * Returns a string with the Vector2 coordinates.
  2183. */
  2184. Vector2.prototype.toString = function () {
  2185. return "{X: " + this.x + " Y:" + this.y + "}";
  2186. };
  2187. /**
  2188. * Returns the string "Vector2"
  2189. */
  2190. Vector2.prototype.getClassName = function () {
  2191. return "Vector2";
  2192. };
  2193. /**
  2194. * Returns the Vector2 hash code as a number.
  2195. */
  2196. Vector2.prototype.getHashCode = function () {
  2197. var hash = this.x || 0;
  2198. hash = (hash * 397) ^ (this.y || 0);
  2199. return hash;
  2200. };
  2201. // Operators
  2202. /**
  2203. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2204. * Returns the Vector2.
  2205. */
  2206. Vector2.prototype.toArray = function (array, index) {
  2207. if (index === void 0) { index = 0; }
  2208. array[index] = this.x;
  2209. array[index + 1] = this.y;
  2210. return this;
  2211. };
  2212. /**
  2213. * Returns a new array with 2 elements : the Vector2 coordinates.
  2214. */
  2215. Vector2.prototype.asArray = function () {
  2216. var result = new Array();
  2217. this.toArray(result, 0);
  2218. return result;
  2219. };
  2220. /**
  2221. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2222. * Returns the updated Vector2.
  2223. */
  2224. Vector2.prototype.copyFrom = function (source) {
  2225. this.x = source.x;
  2226. this.y = source.y;
  2227. return this;
  2228. };
  2229. /**
  2230. * Sets the Vector2 coordinates with the passed floats.
  2231. * Returns the updated Vector2.
  2232. */
  2233. Vector2.prototype.copyFromFloats = function (x, y) {
  2234. this.x = x;
  2235. this.y = y;
  2236. return this;
  2237. };
  2238. /**
  2239. * Sets the Vector2 coordinates with the passed floats.
  2240. * Returns the updated Vector2.
  2241. */
  2242. Vector2.prototype.set = function (x, y) {
  2243. return this.copyFromFloats(x, y);
  2244. };
  2245. /**
  2246. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2247. */
  2248. Vector2.prototype.add = function (otherVector) {
  2249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2250. };
  2251. /**
  2252. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2253. * Returns the Vector2.
  2254. */
  2255. Vector2.prototype.addToRef = function (otherVector, result) {
  2256. result.x = this.x + otherVector.x;
  2257. result.y = this.y + otherVector.y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.addInPlace = function (otherVector) {
  2265. this.x += otherVector.x;
  2266. this.y += otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2271. */
  2272. Vector2.prototype.addVector3 = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2277. */
  2278. Vector2.prototype.subtract = function (otherVector) {
  2279. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2280. };
  2281. /**
  2282. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2283. * Returns the Vector2.
  2284. */
  2285. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2286. result.x = this.x - otherVector.x;
  2287. result.y = this.y - otherVector.y;
  2288. return this;
  2289. };
  2290. /**
  2291. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2292. * Returns the updated Vector2.
  2293. */
  2294. Vector2.prototype.subtractInPlace = function (otherVector) {
  2295. this.x -= otherVector.x;
  2296. this.y -= otherVector.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2304. this.x *= otherVector.x;
  2305. this.y *= otherVector.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2310. */
  2311. Vector2.prototype.multiply = function (otherVector) {
  2312. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2313. };
  2314. /**
  2315. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2319. result.x = this.x * otherVector.x;
  2320. result.y = this.y * otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2325. */
  2326. Vector2.prototype.multiplyByFloats = function (x, y) {
  2327. return new Vector2(this.x * x, this.y * y);
  2328. };
  2329. /**
  2330. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2331. */
  2332. Vector2.prototype.divide = function (otherVector) {
  2333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2337. * Returns the Vector2.
  2338. */
  2339. Vector2.prototype.divideToRef = function (otherVector, result) {
  2340. result.x = this.x / otherVector.x;
  2341. result.y = this.y / otherVector.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Divides the current Vector3 coordinates by the passed ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector2.prototype.divideInPlace = function (otherVector) {
  2349. return this.divideToRef(otherVector, this);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 with current Vector2 negated coordinates.
  2353. */
  2354. Vector2.prototype.negate = function () {
  2355. return new Vector2(-this.x, -this.y);
  2356. };
  2357. /**
  2358. * Multiply the Vector2 coordinates by scale.
  2359. * Returns the updated Vector2.
  2360. */
  2361. Vector2.prototype.scaleInPlace = function (scale) {
  2362. this.x *= scale;
  2363. this.y *= scale;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2368. */
  2369. Vector2.prototype.scale = function (scale) {
  2370. var result = new Vector2(0, 0);
  2371. this.scaleToRef(scale, result);
  2372. return result;
  2373. };
  2374. /**
  2375. * Scale the current Vector2 values by a factor to a given Vector2
  2376. * @param scale defines the scale factor
  2377. * @param result defines the Vector2 object where to store the result
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.scaleToRef = function (scale, result) {
  2381. result.x = this.x * scale;
  2382. result.y = this.y * scale;
  2383. return this;
  2384. };
  2385. /**
  2386. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2387. * @param scale defines the scale factor
  2388. * @param result defines the Vector2 object where to store the result
  2389. * @returns the unmodified current Vector2
  2390. */
  2391. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2392. result.x += this.x * scale;
  2393. result.y += this.y * scale;
  2394. return this;
  2395. };
  2396. /**
  2397. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2398. */
  2399. Vector2.prototype.equals = function (otherVector) {
  2400. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2401. };
  2402. /**
  2403. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2404. */
  2405. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2406. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2407. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2408. };
  2409. // Properties
  2410. /**
  2411. * Returns the vector length (float).
  2412. */
  2413. Vector2.prototype.length = function () {
  2414. return Math.sqrt(this.x * this.x + this.y * this.y);
  2415. };
  2416. /**
  2417. * Returns the vector squared length (float);
  2418. */
  2419. Vector2.prototype.lengthSquared = function () {
  2420. return (this.x * this.x + this.y * this.y);
  2421. };
  2422. // Methods
  2423. /**
  2424. * Normalize the vector.
  2425. * Returns the updated Vector2.
  2426. */
  2427. Vector2.prototype.normalize = function () {
  2428. var len = this.length();
  2429. if (len === 0)
  2430. return this;
  2431. var num = 1.0 / len;
  2432. this.x *= num;
  2433. this.y *= num;
  2434. return this;
  2435. };
  2436. /**
  2437. * Returns a new Vector2 copied from the Vector2.
  2438. */
  2439. Vector2.prototype.clone = function () {
  2440. return new Vector2(this.x, this.y);
  2441. };
  2442. // Statics
  2443. /**
  2444. * Returns a new Vector2(0, 0)
  2445. */
  2446. Vector2.Zero = function () {
  2447. return new Vector2(0, 0);
  2448. };
  2449. /**
  2450. * Returns a new Vector2(1, 1)
  2451. */
  2452. Vector2.One = function () {
  2453. return new Vector2(1, 1);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 set from the passed index element of the passed array.
  2457. */
  2458. Vector2.FromArray = function (array, offset) {
  2459. if (offset === void 0) { offset = 0; }
  2460. return new Vector2(array[offset], array[offset + 1]);
  2461. };
  2462. /**
  2463. * Sets "result" from the passed index element of the passed array.
  2464. */
  2465. Vector2.FromArrayToRef = function (array, offset, result) {
  2466. result.x = array[offset];
  2467. result.y = array[offset + 1];
  2468. };
  2469. /**
  2470. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2471. */
  2472. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2473. var squared = amount * amount;
  2474. var cubed = amount * squared;
  2475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2481. return new Vector2(x, y);
  2482. };
  2483. /**
  2484. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2485. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2486. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2487. */
  2488. Vector2.Clamp = function (value, min, max) {
  2489. var x = value.x;
  2490. x = (x > max.x) ? max.x : x;
  2491. x = (x < min.x) ? min.x : x;
  2492. var y = value.y;
  2493. y = (y > max.y) ? max.y : y;
  2494. y = (y < min.y) ? min.y : y;
  2495. return new Vector2(x, y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2499. */
  2500. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2501. var squared = amount * amount;
  2502. var cubed = amount * squared;
  2503. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2504. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2505. var part3 = (cubed - (2.0 * squared)) + amount;
  2506. var part4 = cubed - squared;
  2507. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2508. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2509. return new Vector2(x, y);
  2510. };
  2511. /**
  2512. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2513. */
  2514. Vector2.Lerp = function (start, end, amount) {
  2515. var x = start.x + ((end.x - start.x) * amount);
  2516. var y = start.y + ((end.y - start.y) * amount);
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns the dot product (float) of the vector "left" and the vector "right".
  2521. */
  2522. Vector2.Dot = function (left, right) {
  2523. return left.x * right.x + left.y * right.y;
  2524. };
  2525. /**
  2526. * Returns a new Vector2 equal to the normalized passed vector.
  2527. */
  2528. Vector2.Normalize = function (vector) {
  2529. var newVector = vector.clone();
  2530. newVector.normalize();
  2531. return newVector;
  2532. };
  2533. /**
  2534. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2535. */
  2536. Vector2.Minimize = function (left, right) {
  2537. var x = (left.x < right.x) ? left.x : right.x;
  2538. var y = (left.y < right.y) ? left.y : right.y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2543. */
  2544. Vector2.Maximize = function (left, right) {
  2545. var x = (left.x > right.x) ? left.x : right.x;
  2546. var y = (left.y > right.y) ? left.y : right.y;
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2551. */
  2552. Vector2.Transform = function (vector, transformation) {
  2553. var r = Vector2.Zero();
  2554. Vector2.TransformToRef(vector, transformation, r);
  2555. return r;
  2556. };
  2557. /**
  2558. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2559. */
  2560. Vector2.TransformToRef = function (vector, transformation, result) {
  2561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2563. result.x = x;
  2564. result.y = y;
  2565. };
  2566. /**
  2567. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2568. */
  2569. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2570. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2571. var sign = a < 0 ? -1 : 1;
  2572. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2573. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2574. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2575. };
  2576. /**
  2577. * Returns the distance (float) between the vectors "value1" and "value2".
  2578. */
  2579. Vector2.Distance = function (value1, value2) {
  2580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2581. };
  2582. /**
  2583. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2584. */
  2585. Vector2.DistanceSquared = function (value1, value2) {
  2586. var x = value1.x - value2.x;
  2587. var y = value1.y - value2.y;
  2588. return (x * x) + (y * y);
  2589. };
  2590. /**
  2591. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2592. */
  2593. Vector2.Center = function (value1, value2) {
  2594. var center = value1.add(value2);
  2595. center.scaleInPlace(0.5);
  2596. return center;
  2597. };
  2598. /**
  2599. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2600. */
  2601. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2602. var l2 = Vector2.DistanceSquared(segA, segB);
  2603. if (l2 === 0.0) {
  2604. return Vector2.Distance(p, segA);
  2605. }
  2606. var v = segB.subtract(segA);
  2607. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2608. var proj = segA.add(v.multiplyByFloats(t, t));
  2609. return Vector2.Distance(p, proj);
  2610. };
  2611. return Vector2;
  2612. }());
  2613. BABYLON.Vector2 = Vector2;
  2614. /**
  2615. * Classed used to store (x,y,z) vector representation
  2616. * A Vector3 is the main object used in 3D geometry
  2617. * It can represent etiher the coordinates of a point the space, either a direction
  2618. * Reminder: Babylon.js uses a left handed forward facing system
  2619. */
  2620. var Vector3 = /** @class */ (function () {
  2621. /**
  2622. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2623. * @param x defines the first coordinates (on X axis)
  2624. * @param y defines the second coordinates (on Y axis)
  2625. * @param z defines the third coordinates (on Z axis)
  2626. */
  2627. function Vector3(
  2628. /**
  2629. * Defines the first coordinates (on X axis)
  2630. */
  2631. x,
  2632. /**
  2633. * Defines the second coordinates (on Y axis)
  2634. */
  2635. y,
  2636. /**
  2637. * Defines the third coordinates (on Z axis)
  2638. */
  2639. z) {
  2640. this.x = x;
  2641. this.y = y;
  2642. this.z = z;
  2643. }
  2644. /**
  2645. * Creates a string representation of the Vector3
  2646. * @returns a string with the Vector3 coordinates.
  2647. */
  2648. Vector3.prototype.toString = function () {
  2649. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2650. };
  2651. /**
  2652. * Gets the class name
  2653. * @returns the string "Vector3"
  2654. */
  2655. Vector3.prototype.getClassName = function () {
  2656. return "Vector3";
  2657. };
  2658. /**
  2659. * Creates the Vector3 hash code
  2660. * @returns a number which tends to be unique between Vector3 instances
  2661. */
  2662. Vector3.prototype.getHashCode = function () {
  2663. var hash = this.x || 0;
  2664. hash = (hash * 397) ^ (this.y || 0);
  2665. hash = (hash * 397) ^ (this.z || 0);
  2666. return hash;
  2667. };
  2668. // Operators
  2669. /**
  2670. * Creates an array containing three elements : the coordinates of the Vector3
  2671. * @returns a new array of numbers
  2672. */
  2673. Vector3.prototype.asArray = function () {
  2674. var result = [];
  2675. this.toArray(result, 0);
  2676. return result;
  2677. };
  2678. /**
  2679. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2680. * @param array defines the destination array
  2681. * @param index defines the offset in the destination array
  2682. * @returns the current Vector3
  2683. */
  2684. Vector3.prototype.toArray = function (array, index) {
  2685. if (index === void 0) { index = 0; }
  2686. array[index] = this.x;
  2687. array[index + 1] = this.y;
  2688. array[index + 2] = this.z;
  2689. return this;
  2690. };
  2691. /**
  2692. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2693. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2694. */
  2695. Vector3.prototype.toQuaternion = function () {
  2696. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2697. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2698. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2699. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2700. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2701. var cosy = Math.cos(this.y * 0.5);
  2702. var siny = Math.sin(this.y * 0.5);
  2703. result.x = coszMinusx * siny;
  2704. result.y = -sinzMinusx * siny;
  2705. result.z = sinxPlusz * cosy;
  2706. result.w = cosxPlusz * cosy;
  2707. return result;
  2708. };
  2709. /**
  2710. * Adds the passed vector to the current Vector3
  2711. * @param otherVector defines the second operand
  2712. * @returns the current updated Vector3
  2713. */
  2714. Vector3.prototype.addInPlace = function (otherVector) {
  2715. this.x += otherVector.x;
  2716. this.y += otherVector.y;
  2717. this.z += otherVector.z;
  2718. return this;
  2719. };
  2720. /**
  2721. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2722. * @param otherVector defines the second operand
  2723. * @returns the resulting Vector3
  2724. */
  2725. Vector3.prototype.add = function (otherVector) {
  2726. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2727. };
  2728. /**
  2729. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2730. * @param otherVector defines the second operand
  2731. * @param result defines the Vector3 object where to store the result
  2732. * @returns the current Vector3
  2733. */
  2734. Vector3.prototype.addToRef = function (otherVector, result) {
  2735. result.x = this.x + otherVector.x;
  2736. result.y = this.y + otherVector.y;
  2737. result.z = this.z + otherVector.z;
  2738. return this;
  2739. };
  2740. /**
  2741. * Subtract the passed vector from the current Vector3
  2742. * @param otherVector defines the second operand
  2743. * @returns the current updated Vector3
  2744. */
  2745. Vector3.prototype.subtractInPlace = function (otherVector) {
  2746. this.x -= otherVector.x;
  2747. this.y -= otherVector.y;
  2748. this.z -= otherVector.z;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2753. * @param otherVector defines the second operand
  2754. * @returns the resulting Vector3
  2755. */
  2756. Vector3.prototype.subtract = function (otherVector) {
  2757. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2758. };
  2759. /**
  2760. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2761. * @param otherVector defines the second operand
  2762. * @param result defines the Vector3 object where to store the result
  2763. * @returns the current Vector3
  2764. */
  2765. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2766. result.x = this.x - otherVector.x;
  2767. result.y = this.y - otherVector.y;
  2768. result.z = this.z - otherVector.z;
  2769. return this;
  2770. };
  2771. /**
  2772. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2773. * @param x defines the x coordinate of the operand
  2774. * @param y defines the y coordinate of the operand
  2775. * @param z defines the z coordinate of the operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2779. return new Vector3(this.x - x, this.y - y, this.z - z);
  2780. };
  2781. /**
  2782. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @param result defines the Vector3 object where to store the result
  2787. * @returns the current Vector3
  2788. */
  2789. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2790. result.x = this.x - x;
  2791. result.y = this.y - y;
  2792. result.z = this.z - z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2797. * @returns a new Vector3
  2798. */
  2799. Vector3.prototype.negate = function () {
  2800. return new Vector3(-this.x, -this.y, -this.z);
  2801. };
  2802. /**
  2803. * Multiplies the Vector3 coordinates by the float "scale"
  2804. * @param scale defines the multiplier factor
  2805. * @returns the current updated Vector3
  2806. */
  2807. Vector3.prototype.scaleInPlace = function (scale) {
  2808. this.x *= scale;
  2809. this.y *= scale;
  2810. this.z *= scale;
  2811. return this;
  2812. };
  2813. /**
  2814. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2815. * @param scale defines the multiplier factor
  2816. * @returns a new Vector3
  2817. */
  2818. Vector3.prototype.scale = function (scale) {
  2819. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2820. };
  2821. /**
  2822. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2823. * @param scale defines the multiplier factor
  2824. * @param result defines the Vector3 object where to store the result
  2825. * @returns the current Vector3
  2826. */
  2827. Vector3.prototype.scaleToRef = function (scale, result) {
  2828. result.x = this.x * scale;
  2829. result.y = this.y * scale;
  2830. result.z = this.z * scale;
  2831. return this;
  2832. };
  2833. /**
  2834. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2835. * @param scale defines the scale factor
  2836. * @param result defines the Vector3 object where to store the result
  2837. * @returns the unmodified current Vector3
  2838. */
  2839. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2840. result.x += this.x * scale;
  2841. result.y += this.y * scale;
  2842. result.z += this.z * scale;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2847. * @param otherVector defines the second operand
  2848. * @returns true if both vectors are equals
  2849. */
  2850. Vector3.prototype.equals = function (otherVector) {
  2851. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2852. };
  2853. /**
  2854. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2855. * @param otherVector defines the second operand
  2856. * @param epsilon defines the minimal distance to define values as equals
  2857. * @returns true if both vectors are distant less than epsilon
  2858. */
  2859. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2860. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2861. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2862. };
  2863. /**
  2864. * Returns true if the current Vector3 coordinates equals the passed floats
  2865. * @param x defines the x coordinate of the operand
  2866. * @param y defines the y coordinate of the operand
  2867. * @param z defines the z coordinate of the operand
  2868. * @returns true if both vectors are equals
  2869. */
  2870. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2871. return this.x === x && this.y === y && this.z === z;
  2872. };
  2873. /**
  2874. * Multiplies the current Vector3 coordinates by the passed ones
  2875. * @param otherVector defines the second operand
  2876. * @returns the current updated Vector3
  2877. */
  2878. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2879. this.x *= otherVector.x;
  2880. this.y *= otherVector.y;
  2881. this.z *= otherVector.z;
  2882. return this;
  2883. };
  2884. /**
  2885. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2886. * @param otherVector defines the second operand
  2887. * @returns the new Vector3
  2888. */
  2889. Vector3.prototype.multiply = function (otherVector) {
  2890. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2891. };
  2892. /**
  2893. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2894. * @param otherVector defines the second operand
  2895. * @param result defines the Vector3 object where to store the result
  2896. * @returns the current Vector3
  2897. */
  2898. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2899. result.x = this.x * otherVector.x;
  2900. result.y = this.y * otherVector.y;
  2901. result.z = this.z * otherVector.z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2906. * @param x defines the x coordinate of the operand
  2907. * @param y defines the y coordinate of the operand
  2908. * @param z defines the z coordinate of the operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2912. return new Vector3(this.x * x, this.y * y, this.z * z);
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2916. * @param otherVector defines the second operand
  2917. * @returns the new Vector3
  2918. */
  2919. Vector3.prototype.divide = function (otherVector) {
  2920. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2921. };
  2922. /**
  2923. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2924. * @param otherVector defines the second operand
  2925. * @param result defines the Vector3 object where to store the result
  2926. * @returns the current Vector3
  2927. */
  2928. Vector3.prototype.divideToRef = function (otherVector, result) {
  2929. result.x = this.x / otherVector.x;
  2930. result.y = this.y / otherVector.y;
  2931. result.z = this.z / otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.divideInPlace = function (otherVector) {
  2940. return this.divideToRef(otherVector, this);
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.minimizeInPlace = function (other) {
  2948. if (other.x < this.x)
  2949. this.x = other.x;
  2950. if (other.y < this.y)
  2951. this.y = other.y;
  2952. if (other.z < this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2958. * @param other defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.maximizeInPlace = function (other) {
  2962. if (other.x > this.x)
  2963. this.x = other.x;
  2964. if (other.y > this.y)
  2965. this.y = other.y;
  2966. if (other.z > this.z)
  2967. this.z = other.z;
  2968. return this;
  2969. };
  2970. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2971. /**
  2972. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2973. */
  2974. get: function () {
  2975. var absX = Math.abs(this.x);
  2976. var absY = Math.abs(this.y);
  2977. if (absX !== absY) {
  2978. return true;
  2979. }
  2980. var absZ = Math.abs(this.z);
  2981. if (absX !== absZ) {
  2982. return true;
  2983. }
  2984. if (absY !== absZ) {
  2985. return true;
  2986. }
  2987. return false;
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. // Properties
  2993. /**
  2994. * Gets the length of the Vector3
  2995. * @returns the length of the Vecto3
  2996. */
  2997. Vector3.prototype.length = function () {
  2998. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2999. };
  3000. /**
  3001. * Gets the squared length of the Vector3
  3002. * @returns squared length of the Vector3
  3003. */
  3004. Vector3.prototype.lengthSquared = function () {
  3005. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3006. };
  3007. /**
  3008. * Normalize the current Vector3.
  3009. * Please note that this is an in place operation.
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.normalize = function () {
  3013. var len = this.length();
  3014. if (len === 0 || len === 1.0)
  3015. return this;
  3016. var num = 1.0 / len;
  3017. this.x *= num;
  3018. this.y *= num;
  3019. this.z *= num;
  3020. return this;
  3021. };
  3022. /**
  3023. * Normalize the current Vector3 to a new vector
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.normalizeToNew = function () {
  3027. var normalized = new Vector3(0, 0, 0);
  3028. this.normalizeToRef(normalized);
  3029. return normalized;
  3030. };
  3031. /**
  3032. * Normalize the current Vector3 to the reference
  3033. * @param reference define the Vector3 to update
  3034. * @returns the updated Vector3
  3035. */
  3036. Vector3.prototype.normalizeToRef = function (reference) {
  3037. var len = this.length();
  3038. if (len === 0 || len === 1.0) {
  3039. reference.set(this.x, this.y, this.z);
  3040. return reference;
  3041. }
  3042. var scale = 1.0 / len;
  3043. this.scaleToRef(scale, reference);
  3044. return reference;
  3045. };
  3046. /**
  3047. * Creates a new Vector3 copied from the current Vector3
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.clone = function () {
  3051. return new Vector3(this.x, this.y, this.z);
  3052. };
  3053. /**
  3054. * Copies the passed vector coordinates to the current Vector3 ones
  3055. * @param source defines the source Vector3
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.copyFrom = function (source) {
  3059. this.x = source.x;
  3060. this.y = source.y;
  3061. this.z = source.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Copies the passed floats to the current Vector3 coordinates
  3066. * @param x defines the x coordinate of the operand
  3067. * @param y defines the y coordinate of the operand
  3068. * @param z defines the z coordinate of the operand
  3069. * @returns the current updated Vector3
  3070. */
  3071. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3072. this.x = x;
  3073. this.y = y;
  3074. this.z = z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Copies the passed floats to the current Vector3 coordinates
  3079. * @param x defines the x coordinate of the operand
  3080. * @param y defines the y coordinate of the operand
  3081. * @param z defines the z coordinate of the operand
  3082. * @returns the current updated Vector3
  3083. */
  3084. Vector3.prototype.set = function (x, y, z) {
  3085. return this.copyFromFloats(x, y, z);
  3086. };
  3087. // Statics
  3088. /**
  3089. * Get the clip factor between two vectors
  3090. * @param vector0 defines the first operand
  3091. * @param vector1 defines the second operand
  3092. * @param axis defines the axis to use
  3093. * @param size defines the size along the axis
  3094. * @returns the clip factor
  3095. */
  3096. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3097. var d0 = Vector3.Dot(vector0, axis) - size;
  3098. var d1 = Vector3.Dot(vector1, axis) - size;
  3099. var s = d0 / (d0 - d1);
  3100. return s;
  3101. };
  3102. /**
  3103. * Get angle between two vectors
  3104. * @param vector0 angle between vector0 and vector1
  3105. * @param vector1 angle between vector0 and vector1
  3106. * @param normal direction of the normal
  3107. * @return the angle between vector0 and vector1
  3108. */
  3109. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3110. var v0 = vector0.clone().normalize();
  3111. var v1 = vector1.clone().normalize();
  3112. var dot = Vector3.Dot(v0, v1);
  3113. var n = Vector3.Cross(v0, v1);
  3114. if (Vector3.Dot(n, normal) > 0) {
  3115. return Math.acos(dot);
  3116. }
  3117. return -Math.acos(dot);
  3118. };
  3119. /**
  3120. * Returns a new Vector3 set from the index "offset" of the passed array
  3121. * @param array defines the source array
  3122. * @param offset defines the offset in the source array
  3123. * @returns the new Vector3
  3124. */
  3125. Vector3.FromArray = function (array, offset) {
  3126. if (!offset) {
  3127. offset = 0;
  3128. }
  3129. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3133. * This function is deprecated. Use FromArray instead
  3134. * @param array defines the source array
  3135. * @param offset defines the offset in the source array
  3136. * @returns the new Vector3
  3137. */
  3138. Vector3.FromFloatArray = function (array, offset) {
  3139. return Vector3.FromArray(array, offset);
  3140. };
  3141. /**
  3142. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @param result defines the Vector3 where to store the result
  3146. */
  3147. Vector3.FromArrayToRef = function (array, offset, result) {
  3148. result.x = array[offset];
  3149. result.y = array[offset + 1];
  3150. result.z = array[offset + 2];
  3151. };
  3152. /**
  3153. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3154. * This function is deprecated. Use FromArrayToRef instead.
  3155. * @param array defines the source array
  3156. * @param offset defines the offset in the source array
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3160. return Vector3.FromArrayToRef(array, offset, result);
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" with the passed floats.
  3164. * @param x defines the x coordinate of the source
  3165. * @param y defines the y coordinate of the source
  3166. * @param z defines the z coordinate of the source
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3170. result.x = x;
  3171. result.y = y;
  3172. result.z = z;
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3176. * @returns a new empty Vector3
  3177. */
  3178. Vector3.Zero = function () {
  3179. return new Vector3(0.0, 0.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3183. * @returns a new unit Vector3
  3184. */
  3185. Vector3.One = function () {
  3186. return new Vector3(1.0, 1.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3190. * @returns a new up Vector3
  3191. */
  3192. Vector3.Up = function () {
  3193. return new Vector3(0.0, 1.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3197. * @returns a new forward Vector3
  3198. */
  3199. Vector3.Forward = function () {
  3200. return new Vector3(0.0, 0.0, 1.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3204. * @returns a new right Vector3
  3205. */
  3206. Vector3.Right = function () {
  3207. return new Vector3(1.0, 0.0, 0.0);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3211. * @returns a new left Vector3
  3212. */
  3213. Vector3.Left = function () {
  3214. return new Vector3(-1.0, 0.0, 0.0);
  3215. };
  3216. /**
  3217. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3218. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3219. * @param vector defines the Vector3 to transform
  3220. * @param transformation defines the transformation matrix
  3221. * @returns the transformed Vector3
  3222. */
  3223. Vector3.TransformCoordinates = function (vector, transformation) {
  3224. var result = Vector3.Zero();
  3225. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3226. return result;
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3230. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3231. * @param vector defines the Vector3 to transform
  3232. * @param transformation defines the transformation matrix
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3236. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3237. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3238. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3239. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3240. result.x = x / w;
  3241. result.y = y / w;
  3242. result.z = z / w;
  3243. };
  3244. /**
  3245. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3246. * This method computes tranformed coordinates only, not transformed direction vectors
  3247. * @param x define the x coordinate of the source vector
  3248. * @param y define the y coordinate of the source vector
  3249. * @param z define the z coordinate of the source vector
  3250. * @param transformation defines the transformation matrix
  3251. * @param result defines the Vector3 where to store the result
  3252. */
  3253. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3254. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3255. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3256. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3257. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3258. result.x = rx / rw;
  3259. result.y = ry / rw;
  3260. result.z = rz / rw;
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3264. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3265. * @param vector defines the Vector3 to transform
  3266. * @param transformation defines the transformation matrix
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.TransformNormal = function (vector, transformation) {
  3270. var result = Vector3.Zero();
  3271. Vector3.TransformNormalToRef(vector, transformation, result);
  3272. return result;
  3273. };
  3274. /**
  3275. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3276. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3277. * @param vector defines the Vector3 to transform
  3278. * @param transformation defines the transformation matrix
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3282. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3283. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3284. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3285. result.x = x;
  3286. result.y = y;
  3287. result.z = z;
  3288. };
  3289. /**
  3290. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param x define the x coordinate of the source vector
  3293. * @param y define the y coordinate of the source vector
  3294. * @param z define the z coordinate of the source vector
  3295. * @param transformation defines the transformation matrix
  3296. * @param result defines the Vector3 where to store the result
  3297. */
  3298. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3299. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3300. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3301. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3305. * @param value1 defines the first control point
  3306. * @param value2 defines the second control point
  3307. * @param value3 defines the third control point
  3308. * @param value4 defines the fourth control point
  3309. * @param amount defines the amount on the spline to use
  3310. * @returns the new Vector3
  3311. */
  3312. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3313. var squared = amount * amount;
  3314. var cubed = amount * squared;
  3315. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3316. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3317. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3318. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3319. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3320. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3321. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3322. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3323. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3324. return new Vector3(x, y, z);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3328. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3329. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3330. * @param value defines the current value
  3331. * @param min defines the lower range value
  3332. * @param max defines the upper range value
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.Clamp = function (value, min, max) {
  3336. var x = value.x;
  3337. x = (x > max.x) ? max.x : x;
  3338. x = (x < min.x) ? min.x : x;
  3339. var y = value.y;
  3340. y = (y > max.y) ? max.y : y;
  3341. y = (y < min.y) ? min.y : y;
  3342. var z = value.z;
  3343. z = (z > max.z) ? max.z : z;
  3344. z = (z < min.z) ? min.z : z;
  3345. return new Vector3(x, y, z);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3349. * @param value1 defines the first control point
  3350. * @param tangent1 defines the first tangent vector
  3351. * @param value2 defines the second control point
  3352. * @param tangent2 defines the second tangent vector
  3353. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3361. var part3 = (cubed - (2.0 * squared)) + amount;
  3362. var part4 = cubed - squared;
  3363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3365. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3366. return new Vector3(x, y, z);
  3367. };
  3368. /**
  3369. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3370. * @param start defines the start value
  3371. * @param end defines the end value
  3372. * @param amount max defines amount between both (between 0 and 1)
  3373. * @returns the new Vector3
  3374. */
  3375. Vector3.Lerp = function (start, end, amount) {
  3376. var result = new Vector3(0, 0, 0);
  3377. Vector3.LerpToRef(start, end, amount, result);
  3378. return result;
  3379. };
  3380. /**
  3381. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3382. * @param start defines the start value
  3383. * @param end defines the end value
  3384. * @param amount max defines amount between both (between 0 and 1)
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.LerpToRef = function (start, end, amount, result) {
  3388. result.x = start.x + ((end.x - start.x) * amount);
  3389. result.y = start.y + ((end.y - start.y) * amount);
  3390. result.z = start.z + ((end.z - start.z) * amount);
  3391. };
  3392. /**
  3393. * Returns the dot product (float) between the vectors "left" and "right"
  3394. * @param left defines the left operand
  3395. * @param right defines the right operand
  3396. * @returns the dot product
  3397. */
  3398. Vector3.Dot = function (left, right) {
  3399. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3403. * The cross product is then orthogonal to both "left" and "right"
  3404. * @param left defines the left operand
  3405. * @param right defines the right operand
  3406. * @returns the cross product
  3407. */
  3408. Vector3.Cross = function (left, right) {
  3409. var result = Vector3.Zero();
  3410. Vector3.CrossToRef(left, right, result);
  3411. return result;
  3412. };
  3413. /**
  3414. * Sets the passed vector "result" with the cross product of "left" and "right"
  3415. * The cross product is then orthogonal to both "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @param result defines the Vector3 where to store the result
  3419. */
  3420. Vector3.CrossToRef = function (left, right, result) {
  3421. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3422. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3423. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3424. result.copyFrom(MathTmp.Vector3[0]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 as the normalization of the passed vector
  3428. * @param vector defines the Vector3 to normalize
  3429. * @returns the new Vector3
  3430. */
  3431. Vector3.Normalize = function (vector) {
  3432. var result = Vector3.Zero();
  3433. Vector3.NormalizeToRef(vector, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the normalization of the passed first vector
  3438. * @param vector defines the Vector3 to normalize
  3439. * @param result defines the Vector3 where to store the result
  3440. */
  3441. Vector3.NormalizeToRef = function (vector, result) {
  3442. result.copyFrom(vector);
  3443. result.normalize();
  3444. };
  3445. /**
  3446. * Project a Vector3 onto screen space
  3447. * @param vector defines the Vector3 to project
  3448. * @param world defines the world matrix to use
  3449. * @param transform defines the transform (view x projection) matrix to use
  3450. * @param viewport defines the screen viewport to use
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Project = function (vector, world, transform, viewport) {
  3454. var cw = viewport.width;
  3455. var ch = viewport.height;
  3456. var cx = viewport.x;
  3457. var cy = viewport.y;
  3458. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3459. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(transform, matrix);
  3462. matrix.multiplyToRef(viewportMatrix, matrix);
  3463. return Vector3.TransformCoordinates(vector, matrix);
  3464. };
  3465. /**
  3466. * Unproject from screen space to object space
  3467. * @param source defines the screen space Vector3 to use
  3468. * @param viewportWidth defines the current width of the viewport
  3469. * @param viewportHeight defines the current height of the viewport
  3470. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3475. var matrix = MathTmp.Matrix[0];
  3476. world.multiplyToRef(transform, matrix);
  3477. matrix.invert();
  3478. source.x = source.x / viewportWidth * 2 - 1;
  3479. source.y = -(source.y / viewportHeight * 2 - 1);
  3480. var vector = Vector3.TransformCoordinates(source, matrix);
  3481. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3482. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3483. vector = vector.scale(1.0 / num);
  3484. }
  3485. return vector;
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param view defines the view matrix to use
  3494. * @param projection defines the projection matrix to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3498. var result = Vector3.Zero();
  3499. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Unproject from screen space to object space
  3504. * @param source defines the screen space Vector3 to use
  3505. * @param viewportWidth defines the current width of the viewport
  3506. * @param viewportHeight defines the current height of the viewport
  3507. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3508. * @param view defines the view matrix to use
  3509. * @param projection defines the projection matrix to use
  3510. * @param result defines the Vector3 where to store the result
  3511. */
  3512. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3513. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3514. };
  3515. /**
  3516. * Unproject from screen space to object space
  3517. * @param sourceX defines the screen space x coordinate to use
  3518. * @param sourceY defines the screen space y coordinate to use
  3519. * @param sourceZ defines the screen space z coordinate to use
  3520. * @param viewportWidth defines the current width of the viewport
  3521. * @param viewportHeight defines the current height of the viewport
  3522. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3523. * @param view defines the view matrix to use
  3524. * @param projection defines the projection matrix to use
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3528. var matrix = MathTmp.Matrix[0];
  3529. world.multiplyToRef(view, matrix);
  3530. matrix.multiplyToRef(projection, matrix);
  3531. matrix.invert();
  3532. var screenSource = MathTmp.Vector3[0];
  3533. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3534. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3535. screenSource.z = 2 * sourceZ - 1.0;
  3536. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3537. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3538. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3539. result.scaleInPlace(1.0 / num);
  3540. }
  3541. };
  3542. /**
  3543. * Gets the minimal coordinate values between two Vector3
  3544. * @param left defines the first operand
  3545. * @param right defines the second operand
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Minimize = function (left, right) {
  3549. var min = left.clone();
  3550. min.minimizeInPlace(right);
  3551. return min;
  3552. };
  3553. /**
  3554. * Gets the maximal coordinate values between two Vector3
  3555. * @param left defines the first operand
  3556. * @param right defines the second operand
  3557. * @returns the new Vector3
  3558. */
  3559. Vector3.Maximize = function (left, right) {
  3560. var max = left.clone();
  3561. max.maximizeInPlace(right);
  3562. return max;
  3563. };
  3564. /**
  3565. * Returns the distance between the vectors "value1" and "value2"
  3566. * @param value1 defines the first operand
  3567. * @param value2 defines the second operand
  3568. * @returns the distance
  3569. */
  3570. Vector3.Distance = function (value1, value2) {
  3571. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3572. };
  3573. /**
  3574. * Returns the squared distance between the vectors "value1" and "value2"
  3575. * @param value1 defines the first operand
  3576. * @param value2 defines the second operand
  3577. * @returns the squared distance
  3578. */
  3579. Vector3.DistanceSquared = function (value1, value2) {
  3580. var x = value1.x - value2.x;
  3581. var y = value1.y - value2.y;
  3582. var z = value1.z - value2.z;
  3583. return (x * x) + (y * y) + (z * z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located at the center between "value1" and "value2"
  3587. * @param value1 defines the first operand
  3588. * @param value2 defines the second operand
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Center = function (value1, value2) {
  3592. var center = value1.add(value2);
  3593. center.scaleInPlace(0.5);
  3594. return center;
  3595. };
  3596. /**
  3597. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3598. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3599. * to something in order to rotate it from its local system to the given target system
  3600. * Note: axis1, axis2 and axis3 are normalized during this operation
  3601. * @param axis1 defines the first axis
  3602. * @param axis2 defines the second axis
  3603. * @param axis3 defines the third axis
  3604. * @returns a new Vector3
  3605. */
  3606. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3607. var rotation = Vector3.Zero();
  3608. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3609. return rotation;
  3610. };
  3611. /**
  3612. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3613. * @param axis1 defines the first axis
  3614. * @param axis2 defines the second axis
  3615. * @param axis3 defines the third axis
  3616. * @param ref defines the Vector3 where to store the result
  3617. */
  3618. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3619. var quat = MathTmp.Quaternion[0];
  3620. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3621. quat.toEulerAnglesToRef(ref);
  3622. };
  3623. return Vector3;
  3624. }());
  3625. BABYLON.Vector3 = Vector3;
  3626. //Vector4 class created for EulerAngle class conversion to Quaternion
  3627. var Vector4 = /** @class */ (function () {
  3628. /**
  3629. * Creates a Vector4 object from the passed floats.
  3630. */
  3631. function Vector4(x, y, z, w) {
  3632. this.x = x;
  3633. this.y = y;
  3634. this.z = z;
  3635. this.w = w;
  3636. }
  3637. /**
  3638. * Returns the string with the Vector4 coordinates.
  3639. */
  3640. Vector4.prototype.toString = function () {
  3641. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3642. };
  3643. /**
  3644. * Returns the string "Vector4".
  3645. */
  3646. Vector4.prototype.getClassName = function () {
  3647. return "Vector4";
  3648. };
  3649. /**
  3650. * Returns the Vector4 hash code.
  3651. */
  3652. Vector4.prototype.getHashCode = function () {
  3653. var hash = this.x || 0;
  3654. hash = (hash * 397) ^ (this.y || 0);
  3655. hash = (hash * 397) ^ (this.z || 0);
  3656. hash = (hash * 397) ^ (this.w || 0);
  3657. return hash;
  3658. };
  3659. // Operators
  3660. /**
  3661. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.asArray = function () {
  3664. var result = new Array();
  3665. this.toArray(result, 0);
  3666. return result;
  3667. };
  3668. /**
  3669. * Populates the passed array from the passed index with the Vector4 coordinates.
  3670. * Returns the Vector4.
  3671. */
  3672. Vector4.prototype.toArray = function (array, index) {
  3673. if (index === undefined) {
  3674. index = 0;
  3675. }
  3676. array[index] = this.x;
  3677. array[index + 1] = this.y;
  3678. array[index + 2] = this.z;
  3679. array[index + 3] = this.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Adds the passed vector to the current Vector4.
  3684. * Returns the updated Vector4.
  3685. */
  3686. Vector4.prototype.addInPlace = function (otherVector) {
  3687. this.x += otherVector.x;
  3688. this.y += otherVector.y;
  3689. this.z += otherVector.z;
  3690. this.w += otherVector.w;
  3691. return this;
  3692. };
  3693. /**
  3694. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3695. */
  3696. Vector4.prototype.add = function (otherVector) {
  3697. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3698. };
  3699. /**
  3700. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3701. * Returns the current Vector4.
  3702. */
  3703. Vector4.prototype.addToRef = function (otherVector, result) {
  3704. result.x = this.x + otherVector.x;
  3705. result.y = this.y + otherVector.y;
  3706. result.z = this.z + otherVector.z;
  3707. result.w = this.w + otherVector.w;
  3708. return this;
  3709. };
  3710. /**
  3711. * Subtract in place the passed vector from the current Vector4.
  3712. * Returns the updated Vector4.
  3713. */
  3714. Vector4.prototype.subtractInPlace = function (otherVector) {
  3715. this.x -= otherVector.x;
  3716. this.y -= otherVector.y;
  3717. this.z -= otherVector.z;
  3718. this.w -= otherVector.w;
  3719. return this;
  3720. };
  3721. /**
  3722. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3723. */
  3724. Vector4.prototype.subtract = function (otherVector) {
  3725. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3726. };
  3727. /**
  3728. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3729. * Returns the current Vector4.
  3730. */
  3731. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3732. result.x = this.x - otherVector.x;
  3733. result.y = this.y - otherVector.y;
  3734. result.z = this.z - otherVector.z;
  3735. result.w = this.w - otherVector.w;
  3736. return this;
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3742. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3743. };
  3744. /**
  3745. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3749. result.x = this.x - x;
  3750. result.y = this.y - y;
  3751. result.z = this.z - z;
  3752. result.w = this.w - w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3757. */
  3758. Vector4.prototype.negate = function () {
  3759. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3760. };
  3761. /**
  3762. * Multiplies the current Vector4 coordinates by scale (float).
  3763. * Returns the updated Vector4.
  3764. */
  3765. Vector4.prototype.scaleInPlace = function (scale) {
  3766. this.x *= scale;
  3767. this.y *= scale;
  3768. this.z *= scale;
  3769. this.w *= scale;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3774. */
  3775. Vector4.prototype.scale = function (scale) {
  3776. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3777. };
  3778. /**
  3779. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3780. * Returns the current Vector4.
  3781. */
  3782. Vector4.prototype.scaleToRef = function (scale, result) {
  3783. result.x = this.x * scale;
  3784. result.y = this.y * scale;
  3785. result.z = this.z * scale;
  3786. result.w = this.w * scale;
  3787. return this;
  3788. };
  3789. /**
  3790. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3791. * @param scale defines the scale factor
  3792. * @param result defines the Vector4 object where to store the result
  3793. * @returns the unmodified current Vector4
  3794. */
  3795. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3796. result.x += this.x * scale;
  3797. result.y += this.y * scale;
  3798. result.z += this.z * scale;
  3799. result.w += this.w * scale;
  3800. return this;
  3801. };
  3802. /**
  3803. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3804. */
  3805. Vector4.prototype.equals = function (otherVector) {
  3806. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3807. };
  3808. /**
  3809. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3810. */
  3811. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3812. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3813. return otherVector
  3814. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3815. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3816. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3817. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3818. };
  3819. /**
  3820. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3821. */
  3822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3823. return this.x === x && this.y === y && this.z === z && this.w === w;
  3824. };
  3825. /**
  3826. * Multiplies in place the current Vector4 by the passed one.
  3827. * Returns the updated Vector4.
  3828. */
  3829. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3830. this.x *= otherVector.x;
  3831. this.y *= otherVector.y;
  3832. this.z *= otherVector.z;
  3833. this.w *= otherVector.w;
  3834. return this;
  3835. };
  3836. /**
  3837. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3838. */
  3839. Vector4.prototype.multiply = function (otherVector) {
  3840. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3841. };
  3842. /**
  3843. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3844. * Returns the current Vector4.
  3845. */
  3846. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3847. result.x = this.x * otherVector.x;
  3848. result.y = this.y * otherVector.y;
  3849. result.z = this.z * otherVector.z;
  3850. result.w = this.w * otherVector.w;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3857. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3861. */
  3862. Vector4.prototype.divide = function (otherVector) {
  3863. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3864. };
  3865. /**
  3866. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.divideToRef = function (otherVector, result) {
  3870. result.x = this.x / otherVector.x;
  3871. result.y = this.y / otherVector.y;
  3872. result.z = this.z / otherVector.z;
  3873. result.w = this.w / otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Divides the current Vector3 coordinates by the passed ones.
  3878. * @returns the updated Vector3.
  3879. */
  3880. Vector4.prototype.divideInPlace = function (otherVector) {
  3881. return this.divideToRef(otherVector, this);
  3882. };
  3883. /**
  3884. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3885. * @param other defines the second operand
  3886. * @returns the current updated Vector4
  3887. */
  3888. Vector4.prototype.minimizeInPlace = function (other) {
  3889. if (other.x < this.x)
  3890. this.x = other.x;
  3891. if (other.y < this.y)
  3892. this.y = other.y;
  3893. if (other.z < this.z)
  3894. this.z = other.z;
  3895. if (other.w < this.w)
  3896. this.w = other.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3901. * @param other defines the second operand
  3902. * @returns the current updated Vector4
  3903. */
  3904. Vector4.prototype.maximizeInPlace = function (other) {
  3905. if (other.x > this.x)
  3906. this.x = other.x;
  3907. if (other.y > this.y)
  3908. this.y = other.y;
  3909. if (other.z > this.z)
  3910. this.z = other.z;
  3911. if (other.w > this.w)
  3912. this.w = other.w;
  3913. return this;
  3914. };
  3915. // Properties
  3916. /**
  3917. * Returns the Vector4 length (float).
  3918. */
  3919. Vector4.prototype.length = function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. };
  3922. /**
  3923. * Returns the Vector4 squared length (float).
  3924. */
  3925. Vector4.prototype.lengthSquared = function () {
  3926. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3927. };
  3928. // Methods
  3929. /**
  3930. * Normalizes in place the Vector4.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.normalize = function () {
  3934. var len = this.length();
  3935. if (len === 0)
  3936. return this;
  3937. var num = 1.0 / len;
  3938. this.x *= num;
  3939. this.y *= num;
  3940. this.z *= num;
  3941. this.w *= num;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3946. */
  3947. Vector4.prototype.toVector3 = function () {
  3948. return new Vector3(this.x, this.y, this.z);
  3949. };
  3950. /**
  3951. * Returns a new Vector4 copied from the current one.
  3952. */
  3953. Vector4.prototype.clone = function () {
  3954. return new Vector4(this.x, this.y, this.z, this.w);
  3955. };
  3956. /**
  3957. * Updates the current Vector4 with the passed one coordinates.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.copyFrom = function (source) {
  3961. this.x = source.x;
  3962. this.y = source.y;
  3963. this.z = source.z;
  3964. this.w = source.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Updates the current Vector4 coordinates with the passed floats.
  3969. * Returns the updated Vector4.
  3970. */
  3971. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3972. this.x = x;
  3973. this.y = y;
  3974. this.z = z;
  3975. this.w = w;
  3976. return this;
  3977. };
  3978. /**
  3979. * Updates the current Vector4 coordinates with the passed floats.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.set = function (x, y, z, w) {
  3983. return this.copyFromFloats(x, y, z, w);
  3984. };
  3985. // Statics
  3986. /**
  3987. * Returns a new Vector4 set from the starting index of the passed array.
  3988. */
  3989. Vector4.FromArray = function (array, offset) {
  3990. if (!offset) {
  3991. offset = 0;
  3992. }
  3993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3994. };
  3995. /**
  3996. * Updates the passed vector "result" from the starting index of the passed array.
  3997. */
  3998. Vector4.FromArrayToRef = function (array, offset, result) {
  3999. result.x = array[offset];
  4000. result.y = array[offset + 1];
  4001. result.z = array[offset + 2];
  4002. result.w = array[offset + 3];
  4003. };
  4004. /**
  4005. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4006. */
  4007. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4008. Vector4.FromArrayToRef(array, offset, result);
  4009. };
  4010. /**
  4011. * Updates the passed vector "result" coordinates from the passed floats.
  4012. */
  4013. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4014. result.x = x;
  4015. result.y = y;
  4016. result.z = z;
  4017. result.w = w;
  4018. };
  4019. /**
  4020. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4021. */
  4022. Vector4.Zero = function () {
  4023. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4027. */
  4028. Vector4.One = function () {
  4029. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4030. };
  4031. /**
  4032. * Returns a new normalized Vector4 from the passed one.
  4033. */
  4034. Vector4.Normalize = function (vector) {
  4035. var result = Vector4.Zero();
  4036. Vector4.NormalizeToRef(vector, result);
  4037. return result;
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the normalization of the passed one.
  4041. */
  4042. Vector4.NormalizeToRef = function (vector, result) {
  4043. result.copyFrom(vector);
  4044. result.normalize();
  4045. };
  4046. Vector4.Minimize = function (left, right) {
  4047. var min = left.clone();
  4048. min.minimizeInPlace(right);
  4049. return min;
  4050. };
  4051. Vector4.Maximize = function (left, right) {
  4052. var max = left.clone();
  4053. max.maximizeInPlace(right);
  4054. return max;
  4055. };
  4056. /**
  4057. * Returns the distance (float) between the vectors "value1" and "value2".
  4058. */
  4059. Vector4.Distance = function (value1, value2) {
  4060. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4061. };
  4062. /**
  4063. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4064. */
  4065. Vector4.DistanceSquared = function (value1, value2) {
  4066. var x = value1.x - value2.x;
  4067. var y = value1.y - value2.y;
  4068. var z = value1.z - value2.z;
  4069. var w = value1.w - value2.w;
  4070. return (x * x) + (y * y) + (z * z) + (w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4074. */
  4075. Vector4.Center = function (value1, value2) {
  4076. var center = value1.add(value2);
  4077. center.scaleInPlace(0.5);
  4078. return center;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4082. * This methods computes transformed normalized direction vectors only.
  4083. */
  4084. Vector4.TransformNormal = function (vector, transformation) {
  4085. var result = Vector4.Zero();
  4086. Vector4.TransformNormalToRef(vector, transformation, result);
  4087. return result;
  4088. };
  4089. /**
  4090. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4091. * This methods computes transformed normalized direction vectors only.
  4092. */
  4093. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4094. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4095. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4096. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4097. result.x = x;
  4098. result.y = y;
  4099. result.z = z;
  4100. result.w = vector.w;
  4101. };
  4102. /**
  4103. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4107. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4108. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4109. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4110. result.w = w;
  4111. };
  4112. return Vector4;
  4113. }());
  4114. BABYLON.Vector4 = Vector4;
  4115. var Size = /** @class */ (function () {
  4116. /**
  4117. * Creates a Size object from the passed width and height (floats).
  4118. */
  4119. function Size(width, height) {
  4120. this.width = width;
  4121. this.height = height;
  4122. }
  4123. // Returns a string with the Size width and height.
  4124. Size.prototype.toString = function () {
  4125. return "{W: " + this.width + ", H: " + this.height + "}";
  4126. };
  4127. /**
  4128. * Returns the string "Size"
  4129. */
  4130. Size.prototype.getClassName = function () {
  4131. return "Size";
  4132. };
  4133. /**
  4134. * Returns the Size hash code.
  4135. */
  4136. Size.prototype.getHashCode = function () {
  4137. var hash = this.width || 0;
  4138. hash = (hash * 397) ^ (this.height || 0);
  4139. return hash;
  4140. };
  4141. /**
  4142. * Updates the current size from the passed one.
  4143. * Returns the updated Size.
  4144. */
  4145. Size.prototype.copyFrom = function (src) {
  4146. this.width = src.width;
  4147. this.height = src.height;
  4148. };
  4149. /**
  4150. * Updates in place the current Size from the passed floats.
  4151. * Returns the updated Size.
  4152. */
  4153. Size.prototype.copyFromFloats = function (width, height) {
  4154. this.width = width;
  4155. this.height = height;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates in place the current Size from the passed floats.
  4160. * Returns the updated Size.
  4161. */
  4162. Size.prototype.set = function (width, height) {
  4163. return this.copyFromFloats(width, height);
  4164. };
  4165. /**
  4166. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4167. */
  4168. Size.prototype.multiplyByFloats = function (w, h) {
  4169. return new Size(this.width * w, this.height * h);
  4170. };
  4171. /**
  4172. * Returns a new Size copied from the passed one.
  4173. */
  4174. Size.prototype.clone = function () {
  4175. return new Size(this.width, this.height);
  4176. };
  4177. /**
  4178. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4179. */
  4180. Size.prototype.equals = function (other) {
  4181. if (!other) {
  4182. return false;
  4183. }
  4184. return (this.width === other.width) && (this.height === other.height);
  4185. };
  4186. Object.defineProperty(Size.prototype, "surface", {
  4187. /**
  4188. * Returns the surface of the Size : width * height (float).
  4189. */
  4190. get: function () {
  4191. return this.width * this.height;
  4192. },
  4193. enumerable: true,
  4194. configurable: true
  4195. });
  4196. /**
  4197. * Returns a new Size set to (0.0, 0.0)
  4198. */
  4199. Size.Zero = function () {
  4200. return new Size(0.0, 0.0);
  4201. };
  4202. /**
  4203. * Returns a new Size set as the addition result of the current Size and the passed one.
  4204. */
  4205. Size.prototype.add = function (otherSize) {
  4206. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4207. return r;
  4208. };
  4209. /**
  4210. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4211. */
  4212. Size.prototype.subtract = function (otherSize) {
  4213. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4214. return r;
  4215. };
  4216. /**
  4217. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4218. */
  4219. Size.Lerp = function (start, end, amount) {
  4220. var w = start.width + ((end.width - start.width) * amount);
  4221. var h = start.height + ((end.height - start.height) * amount);
  4222. return new Size(w, h);
  4223. };
  4224. return Size;
  4225. }());
  4226. BABYLON.Size = Size;
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the passed floats.
  4230. */
  4231. function Quaternion(x, y, z, w) {
  4232. if (x === void 0) { x = 0.0; }
  4233. if (y === void 0) { y = 0.0; }
  4234. if (z === void 0) { z = 0.0; }
  4235. if (w === void 0) { w = 1.0; }
  4236. this.x = x;
  4237. this.y = y;
  4238. this.z = z;
  4239. this.w = w;
  4240. }
  4241. /**
  4242. * Returns a string with the Quaternion coordinates.
  4243. */
  4244. Quaternion.prototype.toString = function () {
  4245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4246. };
  4247. /**
  4248. * Returns the string "Quaternion".
  4249. */
  4250. Quaternion.prototype.getClassName = function () {
  4251. return "Quaternion";
  4252. };
  4253. /**
  4254. * Returns the Quaternion hash code.
  4255. */
  4256. Quaternion.prototype.getHashCode = function () {
  4257. var hash = this.x || 0;
  4258. hash = (hash * 397) ^ (this.y || 0);
  4259. hash = (hash * 397) ^ (this.z || 0);
  4260. hash = (hash * 397) ^ (this.w || 0);
  4261. return hash;
  4262. };
  4263. /**
  4264. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.asArray = function () {
  4267. return [this.x, this.y, this.z, this.w];
  4268. };
  4269. /**
  4270. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4271. */
  4272. Quaternion.prototype.equals = function (otherQuaternion) {
  4273. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4274. };
  4275. /**
  4276. * Returns a new Quaternion copied from the current one.
  4277. */
  4278. Quaternion.prototype.clone = function () {
  4279. return new Quaternion(this.x, this.y, this.z, this.w);
  4280. };
  4281. /**
  4282. * Updates the current Quaternion from the passed one coordinates.
  4283. * Returns the updated Quaterion.
  4284. */
  4285. Quaternion.prototype.copyFrom = function (other) {
  4286. this.x = other.x;
  4287. this.y = other.y;
  4288. this.z = other.z;
  4289. this.w = other.w;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates the current Quaternion from the passed float coordinates.
  4294. * Returns the updated Quaterion.
  4295. */
  4296. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4297. this.x = x;
  4298. this.y = y;
  4299. this.z = z;
  4300. this.w = w;
  4301. return this;
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed float coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.set = function (x, y, z, w) {
  4308. return this.copyFromFloats(x, y, z, w);
  4309. };
  4310. /**
  4311. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4312. */
  4313. Quaternion.prototype.add = function (other) {
  4314. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4315. };
  4316. /**
  4317. * Add a quaternion to the current one
  4318. * @param other defines the quaternion to add
  4319. * @returns the current quaternion
  4320. */
  4321. Quaternion.prototype.addInPlace = function (other) {
  4322. this.x += other.x;
  4323. this.y += other.y;
  4324. this.z += other.z;
  4325. this.w += other.w;
  4326. return this;
  4327. };
  4328. /**
  4329. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4330. */
  4331. Quaternion.prototype.subtract = function (other) {
  4332. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4333. };
  4334. /**
  4335. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4336. */
  4337. Quaternion.prototype.scale = function (value) {
  4338. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4339. };
  4340. /**
  4341. * Scale the current Quaternion values by a factor to a given Quaternion
  4342. * @param scale defines the scale factor
  4343. * @param result defines the Quaternion object where to store the result
  4344. * @returns the unmodified current Quaternion
  4345. */
  4346. Quaternion.prototype.scaleToRef = function (scale, result) {
  4347. result.x = this.x * scale;
  4348. result.y = this.y * scale;
  4349. result.z = this.z * scale;
  4350. result.w = this.w * scale;
  4351. return this;
  4352. };
  4353. /**
  4354. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4355. * @param scale defines the scale factor
  4356. * @param result defines the Quaternion object where to store the result
  4357. * @returns the unmodified current Quaternion
  4358. */
  4359. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4360. result.x += this.x * scale;
  4361. result.y += this.y * scale;
  4362. result.z += this.z * scale;
  4363. result.w += this.w * scale;
  4364. return this;
  4365. };
  4366. /**
  4367. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4368. */
  4369. Quaternion.prototype.multiply = function (q1) {
  4370. var result = new Quaternion(0, 0, 0, 1.0);
  4371. this.multiplyToRef(q1, result);
  4372. return result;
  4373. };
  4374. /**
  4375. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4376. * Returns the current Quaternion.
  4377. */
  4378. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4379. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4380. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4381. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4382. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4383. result.copyFromFloats(x, y, z, w);
  4384. return this;
  4385. };
  4386. /**
  4387. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4388. * Returns the updated Quaternion.
  4389. */
  4390. Quaternion.prototype.multiplyInPlace = function (q1) {
  4391. this.multiplyToRef(q1, this);
  4392. return this;
  4393. };
  4394. /**
  4395. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4396. * Returns the current Quaternion.
  4397. */
  4398. Quaternion.prototype.conjugateToRef = function (ref) {
  4399. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4400. return this;
  4401. };
  4402. /**
  4403. * Conjugates in place the current Quaternion.
  4404. * Returns the updated Quaternion.
  4405. */
  4406. Quaternion.prototype.conjugateInPlace = function () {
  4407. this.x *= -1;
  4408. this.y *= -1;
  4409. this.z *= -1;
  4410. return this;
  4411. };
  4412. /**
  4413. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4414. */
  4415. Quaternion.prototype.conjugate = function () {
  4416. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4417. return result;
  4418. };
  4419. /**
  4420. * Returns the Quaternion length (float).
  4421. */
  4422. Quaternion.prototype.length = function () {
  4423. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4424. };
  4425. /**
  4426. * Normalize in place the current Quaternion.
  4427. * Returns the updated Quaternion.
  4428. */
  4429. Quaternion.prototype.normalize = function () {
  4430. var length = 1.0 / this.length();
  4431. this.x *= length;
  4432. this.y *= length;
  4433. this.z *= length;
  4434. this.w *= length;
  4435. return this;
  4436. };
  4437. /**
  4438. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4439. * @param order is a reserved parameter and is ignore for now
  4440. * @returns the new Vector3
  4441. */
  4442. Quaternion.prototype.toEulerAngles = function (order) {
  4443. if (order === void 0) { order = "YZX"; }
  4444. var result = Vector3.Zero();
  4445. this.toEulerAnglesToRef(result, order);
  4446. return result;
  4447. };
  4448. /**
  4449. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4450. * @param result defines the vector which will be filled with the Euler angles
  4451. * @param order is a reserved parameter and is ignore for now
  4452. * @returns the current Quaternion
  4453. */
  4454. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4455. if (order === void 0) { order = "YZX"; }
  4456. var qz = this.z;
  4457. var qx = this.x;
  4458. var qy = this.y;
  4459. var qw = this.w;
  4460. var sqw = qw * qw;
  4461. var sqz = qz * qz;
  4462. var sqx = qx * qx;
  4463. var sqy = qy * qy;
  4464. var zAxisY = qy * qz - qx * qw;
  4465. var limit = .4999999;
  4466. if (zAxisY < -limit) {
  4467. result.y = 2 * Math.atan2(qy, qw);
  4468. result.x = Math.PI / 2;
  4469. result.z = 0;
  4470. }
  4471. else if (zAxisY > limit) {
  4472. result.y = 2 * Math.atan2(qy, qw);
  4473. result.x = -Math.PI / 2;
  4474. result.z = 0;
  4475. }
  4476. else {
  4477. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4478. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4479. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4480. }
  4481. return this;
  4482. };
  4483. /**
  4484. * Updates the passed rotation matrix with the current Quaternion values.
  4485. * Returns the current Quaternion.
  4486. */
  4487. Quaternion.prototype.toRotationMatrix = function (result) {
  4488. var xx = this.x * this.x;
  4489. var yy = this.y * this.y;
  4490. var zz = this.z * this.z;
  4491. var xy = this.x * this.y;
  4492. var zw = this.z * this.w;
  4493. var zx = this.z * this.x;
  4494. var yw = this.y * this.w;
  4495. var yz = this.y * this.z;
  4496. var xw = this.x * this.w;
  4497. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4498. result.m[1] = 2.0 * (xy + zw);
  4499. result.m[2] = 2.0 * (zx - yw);
  4500. result.m[3] = 0;
  4501. result.m[4] = 2.0 * (xy - zw);
  4502. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4503. result.m[6] = 2.0 * (yz + xw);
  4504. result.m[7] = 0;
  4505. result.m[8] = 2.0 * (zx + yw);
  4506. result.m[9] = 2.0 * (yz - xw);
  4507. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4508. result.m[11] = 0;
  4509. result.m[12] = 0;
  4510. result.m[13] = 0;
  4511. result.m[14] = 0;
  4512. result.m[15] = 1.0;
  4513. result._markAsUpdated();
  4514. return this;
  4515. };
  4516. /**
  4517. * Updates the current Quaternion from the passed rotation matrix values.
  4518. * Returns the updated Quaternion.
  4519. */
  4520. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4521. Quaternion.FromRotationMatrixToRef(matrix, this);
  4522. return this;
  4523. };
  4524. // Statics
  4525. /**
  4526. * Returns a new Quaternion set from the passed rotation matrix values.
  4527. */
  4528. Quaternion.FromRotationMatrix = function (matrix) {
  4529. var result = new Quaternion();
  4530. Quaternion.FromRotationMatrixToRef(matrix, result);
  4531. return result;
  4532. };
  4533. /**
  4534. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4535. */
  4536. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4537. var data = matrix.m;
  4538. var m11 = data[0], m12 = data[4], m13 = data[8];
  4539. var m21 = data[1], m22 = data[5], m23 = data[9];
  4540. var m31 = data[2], m32 = data[6], m33 = data[10];
  4541. var trace = m11 + m22 + m33;
  4542. var s;
  4543. if (trace > 0) {
  4544. s = 0.5 / Math.sqrt(trace + 1.0);
  4545. result.w = 0.25 / s;
  4546. result.x = (m32 - m23) * s;
  4547. result.y = (m13 - m31) * s;
  4548. result.z = (m21 - m12) * s;
  4549. }
  4550. else if (m11 > m22 && m11 > m33) {
  4551. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4552. result.w = (m32 - m23) / s;
  4553. result.x = 0.25 * s;
  4554. result.y = (m12 + m21) / s;
  4555. result.z = (m13 + m31) / s;
  4556. }
  4557. else if (m22 > m33) {
  4558. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4559. result.w = (m13 - m31) / s;
  4560. result.x = (m12 + m21) / s;
  4561. result.y = 0.25 * s;
  4562. result.z = (m23 + m32) / s;
  4563. }
  4564. else {
  4565. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4566. result.w = (m21 - m12) / s;
  4567. result.x = (m13 + m31) / s;
  4568. result.y = (m23 + m32) / s;
  4569. result.z = 0.25 * s;
  4570. }
  4571. };
  4572. /**
  4573. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4574. */
  4575. Quaternion.Zero = function () {
  4576. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4577. };
  4578. /**
  4579. * Returns a new Quaternion as the inverted current Quaternion.
  4580. */
  4581. Quaternion.Inverse = function (q) {
  4582. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4583. };
  4584. /**
  4585. * Returns the identity Quaternion.
  4586. */
  4587. Quaternion.Identity = function () {
  4588. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4589. };
  4590. Quaternion.IsIdentity = function (quaternion) {
  4591. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4592. };
  4593. /**
  4594. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4595. */
  4596. Quaternion.RotationAxis = function (axis, angle) {
  4597. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4598. };
  4599. /**
  4600. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4601. */
  4602. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4603. var sin = Math.sin(angle / 2);
  4604. axis.normalize();
  4605. result.w = Math.cos(angle / 2);
  4606. result.x = axis.x * sin;
  4607. result.y = axis.y * sin;
  4608. result.z = axis.z * sin;
  4609. return result;
  4610. };
  4611. /**
  4612. * Retuns a new Quaternion set from the starting index of the passed array.
  4613. */
  4614. Quaternion.FromArray = function (array, offset) {
  4615. if (!offset) {
  4616. offset = 0;
  4617. }
  4618. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4619. };
  4620. /**
  4621. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4622. */
  4623. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4624. var q = new Quaternion();
  4625. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4626. return q;
  4627. };
  4628. /**
  4629. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4630. */
  4631. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4632. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4633. var halfRoll = roll * 0.5;
  4634. var halfPitch = pitch * 0.5;
  4635. var halfYaw = yaw * 0.5;
  4636. var sinRoll = Math.sin(halfRoll);
  4637. var cosRoll = Math.cos(halfRoll);
  4638. var sinPitch = Math.sin(halfPitch);
  4639. var cosPitch = Math.cos(halfPitch);
  4640. var sinYaw = Math.sin(halfYaw);
  4641. var cosYaw = Math.cos(halfYaw);
  4642. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4643. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4644. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4645. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4646. };
  4647. /**
  4648. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4649. */
  4650. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4651. var result = new Quaternion();
  4652. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4653. return result;
  4654. };
  4655. /**
  4656. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4657. */
  4658. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4659. // Produces a quaternion from Euler angles in the z-x-z orientation
  4660. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4661. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4662. var halfBeta = beta * 0.5;
  4663. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4664. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4665. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4666. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4667. };
  4668. /**
  4669. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4670. * cf to Vector3.RotationFromAxis() documentation.
  4671. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4672. */
  4673. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4674. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4675. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4676. return quat;
  4677. };
  4678. /**
  4679. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4680. * cf to Vector3.RotationFromAxis() documentation.
  4681. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4682. */
  4683. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4684. var rotMat = MathTmp.Matrix[0];
  4685. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4686. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4687. };
  4688. Quaternion.Slerp = function (left, right, amount) {
  4689. var result = Quaternion.Identity();
  4690. Quaternion.SlerpToRef(left, right, amount, result);
  4691. return result;
  4692. };
  4693. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4694. var num2;
  4695. var num3;
  4696. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4697. var flag = false;
  4698. if (num4 < 0) {
  4699. flag = true;
  4700. num4 = -num4;
  4701. }
  4702. if (num4 > 0.999999) {
  4703. num3 = 1 - amount;
  4704. num2 = flag ? -amount : amount;
  4705. }
  4706. else {
  4707. var num5 = Math.acos(num4);
  4708. var num6 = (1.0 / Math.sin(num5));
  4709. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4710. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4711. }
  4712. result.x = (num3 * left.x) + (num2 * right.x);
  4713. result.y = (num3 * left.y) + (num2 * right.y);
  4714. result.z = (num3 * left.z) + (num2 * right.z);
  4715. result.w = (num3 * left.w) + (num2 * right.w);
  4716. };
  4717. /**
  4718. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4719. */
  4720. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4721. var squared = amount * amount;
  4722. var cubed = amount * squared;
  4723. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4724. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4725. var part3 = (cubed - (2.0 * squared)) + amount;
  4726. var part4 = cubed - squared;
  4727. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4728. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4729. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4730. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4731. return new Quaternion(x, y, z, w);
  4732. };
  4733. return Quaternion;
  4734. }());
  4735. BABYLON.Quaternion = Quaternion;
  4736. /**
  4737. * Class used to store matrix data (4x4)
  4738. */
  4739. var Matrix = /** @class */ (function () {
  4740. /**
  4741. * Creates an empty matrix (filled with zeros)
  4742. */
  4743. function Matrix() {
  4744. this._isIdentity = false;
  4745. this._isIdentityDirty = true;
  4746. /**
  4747. * Gets or sets the internal data of the matrix
  4748. */
  4749. this.m = new Float32Array(16);
  4750. this._markAsUpdated();
  4751. }
  4752. /** @ignore */
  4753. Matrix.prototype._markAsUpdated = function () {
  4754. this.updateFlag = Matrix._updateFlagSeed++;
  4755. this._isIdentityDirty = true;
  4756. };
  4757. // Properties
  4758. /**
  4759. * Check if the current matrix is indentity
  4760. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4761. * @returns true is the matrix is the identity matrix
  4762. */
  4763. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4764. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4765. if (this._isIdentityDirty) {
  4766. this._isIdentityDirty = false;
  4767. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4768. this._isIdentity = false;
  4769. }
  4770. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4771. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4772. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4773. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4774. this._isIdentity = false;
  4775. }
  4776. else {
  4777. this._isIdentity = true;
  4778. }
  4779. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4780. this._isIdentity = false;
  4781. }
  4782. }
  4783. return this._isIdentity;
  4784. };
  4785. /**
  4786. * Gets the determinant of the matrix
  4787. * @returns the matrix determinant
  4788. */
  4789. Matrix.prototype.determinant = function () {
  4790. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4791. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4792. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4793. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4794. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4795. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4796. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4797. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4798. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4799. };
  4800. // Methods
  4801. /**
  4802. * Returns the matrix as a Float32Array
  4803. * @returns the matrix underlying array
  4804. */
  4805. Matrix.prototype.toArray = function () {
  4806. return this.m;
  4807. };
  4808. /**
  4809. * Returns the matrix as a Float32Array
  4810. * @returns the matrix underlying array.
  4811. */
  4812. Matrix.prototype.asArray = function () {
  4813. return this.toArray();
  4814. };
  4815. /**
  4816. * Inverts the current matrix in place
  4817. * @returns the current inverted matrix
  4818. */
  4819. Matrix.prototype.invert = function () {
  4820. this.invertToRef(this);
  4821. return this;
  4822. };
  4823. /**
  4824. * Sets all the matrix elements to zero
  4825. * @returns the current matrix
  4826. */
  4827. Matrix.prototype.reset = function () {
  4828. for (var index = 0; index < 16; index++) {
  4829. this.m[index] = 0.0;
  4830. }
  4831. this._markAsUpdated();
  4832. return this;
  4833. };
  4834. /**
  4835. * Adds the current matrix with a second one
  4836. * @param other defines the matrix to add
  4837. * @returns a new matrix as the addition of the current matrix and the passed one
  4838. */
  4839. Matrix.prototype.add = function (other) {
  4840. var result = new Matrix();
  4841. this.addToRef(other, result);
  4842. return result;
  4843. };
  4844. /**
  4845. * Sets the passed matrix "result" to the addition of the current matrix and the passed one
  4846. * @param other defines the matrix to add
  4847. * @param result defines the target matrix
  4848. * @returns the current matrix
  4849. */
  4850. Matrix.prototype.addToRef = function (other, result) {
  4851. for (var index = 0; index < 16; index++) {
  4852. result.m[index] = this.m[index] + other.m[index];
  4853. }
  4854. result._markAsUpdated();
  4855. return this;
  4856. };
  4857. /**
  4858. * Adds in place the passed matrix to the current matrix
  4859. * @param other defines the second operand
  4860. * @returns the current updated matrix
  4861. */
  4862. Matrix.prototype.addToSelf = function (other) {
  4863. for (var index = 0; index < 16; index++) {
  4864. this.m[index] += other.m[index];
  4865. }
  4866. this._markAsUpdated();
  4867. return this;
  4868. };
  4869. /**
  4870. * Sets the passed matrix to the current inverted Matrix
  4871. * @param other defines the target matrix
  4872. * @returns the unmodified current matrix
  4873. */
  4874. Matrix.prototype.invertToRef = function (other) {
  4875. var l1 = this.m[0];
  4876. var l2 = this.m[1];
  4877. var l3 = this.m[2];
  4878. var l4 = this.m[3];
  4879. var l5 = this.m[4];
  4880. var l6 = this.m[5];
  4881. var l7 = this.m[6];
  4882. var l8 = this.m[7];
  4883. var l9 = this.m[8];
  4884. var l10 = this.m[9];
  4885. var l11 = this.m[10];
  4886. var l12 = this.m[11];
  4887. var l13 = this.m[12];
  4888. var l14 = this.m[13];
  4889. var l15 = this.m[14];
  4890. var l16 = this.m[15];
  4891. var l17 = (l11 * l16) - (l12 * l15);
  4892. var l18 = (l10 * l16) - (l12 * l14);
  4893. var l19 = (l10 * l15) - (l11 * l14);
  4894. var l20 = (l9 * l16) - (l12 * l13);
  4895. var l21 = (l9 * l15) - (l11 * l13);
  4896. var l22 = (l9 * l14) - (l10 * l13);
  4897. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4898. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4899. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4900. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4901. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4902. var l28 = (l7 * l16) - (l8 * l15);
  4903. var l29 = (l6 * l16) - (l8 * l14);
  4904. var l30 = (l6 * l15) - (l7 * l14);
  4905. var l31 = (l5 * l16) - (l8 * l13);
  4906. var l32 = (l5 * l15) - (l7 * l13);
  4907. var l33 = (l5 * l14) - (l6 * l13);
  4908. var l34 = (l7 * l12) - (l8 * l11);
  4909. var l35 = (l6 * l12) - (l8 * l10);
  4910. var l36 = (l6 * l11) - (l7 * l10);
  4911. var l37 = (l5 * l12) - (l8 * l9);
  4912. var l38 = (l5 * l11) - (l7 * l9);
  4913. var l39 = (l5 * l10) - (l6 * l9);
  4914. other.m[0] = l23 * l27;
  4915. other.m[4] = l24 * l27;
  4916. other.m[8] = l25 * l27;
  4917. other.m[12] = l26 * l27;
  4918. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4919. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4920. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4921. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4922. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4923. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4924. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4925. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4926. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4927. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4928. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4929. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4930. other._markAsUpdated();
  4931. return this;
  4932. };
  4933. /**
  4934. * Inserts the translation vector (using 3 floats) in the current matrix
  4935. * @param x defines the 1st component of the translation
  4936. * @param y defines the 2nd component of the translation
  4937. * @param z defines the 3rd component of the translation
  4938. * @returns the current updated matrix
  4939. */
  4940. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4941. this.m[12] = x;
  4942. this.m[13] = y;
  4943. this.m[14] = z;
  4944. this._markAsUpdated();
  4945. return this;
  4946. };
  4947. /**
  4948. * Inserts the translation vector in the current matrix
  4949. * @param vector3 defines the translation to insert
  4950. * @returns the current updated matrix
  4951. */
  4952. Matrix.prototype.setTranslation = function (vector3) {
  4953. this.m[12] = vector3.x;
  4954. this.m[13] = vector3.y;
  4955. this.m[14] = vector3.z;
  4956. this._markAsUpdated();
  4957. return this;
  4958. };
  4959. /**
  4960. * Gets the translation value of the current matrix
  4961. * @returns a new Vector3 as the extracted translation from the matrix
  4962. */
  4963. Matrix.prototype.getTranslation = function () {
  4964. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4965. };
  4966. /**
  4967. * Fill a Vector3 with the extracted translation from the matrix
  4968. * @param result defines the Vector3 where to store the translation
  4969. * @returns the current matrix
  4970. */
  4971. Matrix.prototype.getTranslationToRef = function (result) {
  4972. result.x = this.m[12];
  4973. result.y = this.m[13];
  4974. result.z = this.m[14];
  4975. return this;
  4976. };
  4977. /**
  4978. * Remove rotation and scaling part from the matrix
  4979. * @returns the updated matrix
  4980. */
  4981. Matrix.prototype.removeRotationAndScaling = function () {
  4982. this.setRowFromFloats(0, 1, 0, 0, 0);
  4983. this.setRowFromFloats(1, 0, 1, 0, 0);
  4984. this.setRowFromFloats(2, 0, 0, 1, 0);
  4985. return this;
  4986. };
  4987. /**
  4988. * Multiply two matrices
  4989. * @param other defines the second operand
  4990. * @returns a new matrix set with the multiplication result of the current Matrix and the passed one
  4991. */
  4992. Matrix.prototype.multiply = function (other) {
  4993. var result = new Matrix();
  4994. this.multiplyToRef(other, result);
  4995. return result;
  4996. };
  4997. /**
  4998. * Copy the current matrix from the passed one
  4999. * @param other defines the source matrix
  5000. * @returns the current updated matrix
  5001. */
  5002. Matrix.prototype.copyFrom = function (other) {
  5003. for (var index = 0; index < 16; index++) {
  5004. this.m[index] = other.m[index];
  5005. }
  5006. this._markAsUpdated();
  5007. return this;
  5008. };
  5009. /**
  5010. * Populates the passed array from the starting index with the current matrix values
  5011. * @param array defines the target array
  5012. * @param offset defines the offset in the target array where to start storing values
  5013. * @returns the current matrix
  5014. */
  5015. Matrix.prototype.copyToArray = function (array, offset) {
  5016. if (offset === void 0) { offset = 0; }
  5017. for (var index = 0; index < 16; index++) {
  5018. array[offset + index] = this.m[index];
  5019. }
  5020. return this;
  5021. };
  5022. /**
  5023. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one
  5024. * @param other defines the second operand
  5025. * @param result defines the matrix where to store the multiplication
  5026. * @returns the current matrix
  5027. */
  5028. Matrix.prototype.multiplyToRef = function (other, result) {
  5029. this.multiplyToArray(other, result.m, 0);
  5030. result._markAsUpdated();
  5031. return this;
  5032. };
  5033. /**
  5034. * Sets the Float32Array "result" from the passed index "offset" with the multiplication of the current matrix and the passed one
  5035. * @param other defines the second operand
  5036. * @param result defines the array where to store the multiplication
  5037. * @param offset defines the offset in the target array where to start storing values
  5038. * @returns the current matrix
  5039. */
  5040. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5041. var tm0 = this.m[0];
  5042. var tm1 = this.m[1];
  5043. var tm2 = this.m[2];
  5044. var tm3 = this.m[3];
  5045. var tm4 = this.m[4];
  5046. var tm5 = this.m[5];
  5047. var tm6 = this.m[6];
  5048. var tm7 = this.m[7];
  5049. var tm8 = this.m[8];
  5050. var tm9 = this.m[9];
  5051. var tm10 = this.m[10];
  5052. var tm11 = this.m[11];
  5053. var tm12 = this.m[12];
  5054. var tm13 = this.m[13];
  5055. var tm14 = this.m[14];
  5056. var tm15 = this.m[15];
  5057. var om0 = other.m[0];
  5058. var om1 = other.m[1];
  5059. var om2 = other.m[2];
  5060. var om3 = other.m[3];
  5061. var om4 = other.m[4];
  5062. var om5 = other.m[5];
  5063. var om6 = other.m[6];
  5064. var om7 = other.m[7];
  5065. var om8 = other.m[8];
  5066. var om9 = other.m[9];
  5067. var om10 = other.m[10];
  5068. var om11 = other.m[11];
  5069. var om12 = other.m[12];
  5070. var om13 = other.m[13];
  5071. var om14 = other.m[14];
  5072. var om15 = other.m[15];
  5073. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5074. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5075. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5076. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5077. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5078. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5079. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5080. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5081. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5082. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5083. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5084. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5085. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5086. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5087. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5088. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5089. return this;
  5090. };
  5091. /**
  5092. * Check equality between this matrix and a second one
  5093. * @param value defines the second matrix to compare
  5094. * @returns true is the current matrix and the passed one values are strictly equal
  5095. */
  5096. Matrix.prototype.equals = function (value) {
  5097. return value &&
  5098. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5099. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5100. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5101. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5102. };
  5103. /**
  5104. * Clone the current matrix
  5105. * @returns a new matrix from the current matrix
  5106. */
  5107. Matrix.prototype.clone = function () {
  5108. 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]);
  5109. };
  5110. /**
  5111. * Returns the name of the current matrix class
  5112. * @returns the string "Matrix"
  5113. */
  5114. Matrix.prototype.getClassName = function () {
  5115. return "Matrix";
  5116. };
  5117. /**
  5118. * Gets the hash code of the current matrix
  5119. * @returns the hash code
  5120. */
  5121. Matrix.prototype.getHashCode = function () {
  5122. var hash = this.m[0] || 0;
  5123. for (var i = 1; i < 16; i++) {
  5124. hash = (hash * 397) ^ (this.m[i] || 0);
  5125. }
  5126. return hash;
  5127. };
  5128. /**
  5129. * Decomposes the current Matrix into a translation, rotation and scaling components
  5130. * @param scale defines the scale vector3 passed as a reference to update
  5131. * @param rotation defines the rotation quaternion passed as a reference to update
  5132. * @param translation defines the translation vector3 passed as a reference to update
  5133. * @returns true if operation was successful
  5134. */
  5135. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5136. if (translation) {
  5137. translation.x = this.m[12];
  5138. translation.y = this.m[13];
  5139. translation.z = this.m[14];
  5140. }
  5141. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5142. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5143. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5144. if (this.determinant() <= 0) {
  5145. scale.y *= -1;
  5146. }
  5147. if (rotation) {
  5148. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5149. rotation.x = 0;
  5150. rotation.y = 0;
  5151. rotation.z = 0;
  5152. rotation.w = 1;
  5153. return false;
  5154. }
  5155. 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]);
  5156. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5157. }
  5158. return true;
  5159. };
  5160. /**
  5161. * Gets specific row of the matrix
  5162. * @param index defines the number of the row to get
  5163. * @returns the index-th row of the current matrix as a new Vector4
  5164. */
  5165. Matrix.prototype.getRow = function (index) {
  5166. if (index < 0 || index > 3) {
  5167. return null;
  5168. }
  5169. var i = index * 4;
  5170. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5171. };
  5172. /**
  5173. * Sets the index-th row of the current matrix to the vector4 values
  5174. * @param index defines the number of the row to set
  5175. * @param row defines the target vector4
  5176. * @returns the updated current matrix
  5177. */
  5178. Matrix.prototype.setRow = function (index, row) {
  5179. if (index < 0 || index > 3) {
  5180. return this;
  5181. }
  5182. var i = index * 4;
  5183. this.m[i + 0] = row.x;
  5184. this.m[i + 1] = row.y;
  5185. this.m[i + 2] = row.z;
  5186. this.m[i + 3] = row.w;
  5187. this._markAsUpdated();
  5188. return this;
  5189. };
  5190. /**
  5191. * Compute the transpose of the matrix
  5192. * @returns the new transposed matrix
  5193. */
  5194. Matrix.prototype.transpose = function () {
  5195. return Matrix.Transpose(this);
  5196. };
  5197. /**
  5198. * Compute the transpose of the matrix and store it in a given matrix
  5199. * @param result defines the target matrix
  5200. * @returns the current matrix
  5201. */
  5202. Matrix.prototype.transposeToRef = function (result) {
  5203. Matrix.TransposeToRef(this, result);
  5204. return this;
  5205. };
  5206. /**
  5207. * Sets the index-th row of the current matrix with the passed 4 x float values
  5208. * @param index defines the row index
  5209. * @param x defines the x component to set
  5210. * @param y defines the y component to set
  5211. * @param z defines the z component to set
  5212. * @param w defines the w component to set
  5213. * @returns the updated current matrix
  5214. */
  5215. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5216. if (index < 0 || index > 3) {
  5217. return this;
  5218. }
  5219. var i = index * 4;
  5220. this.m[i + 0] = x;
  5221. this.m[i + 1] = y;
  5222. this.m[i + 2] = z;
  5223. this.m[i + 3] = w;
  5224. this._markAsUpdated();
  5225. return this;
  5226. };
  5227. /**
  5228. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5229. * @param scale defines the scale factor
  5230. * @returns a new matrix
  5231. */
  5232. Matrix.prototype.scale = function (scale) {
  5233. var result = new Matrix();
  5234. this.scaleToRef(scale, result);
  5235. return result;
  5236. };
  5237. /**
  5238. * Scale the current matrix values by a factor to a given result matrix
  5239. * @param scale defines the scale factor
  5240. * @param result defines the matrix to store the result
  5241. * @returns the current matrix
  5242. */
  5243. Matrix.prototype.scaleToRef = function (scale, result) {
  5244. for (var index = 0; index < 16; index++) {
  5245. result.m[index] = this.m[index] * scale;
  5246. }
  5247. result._markAsUpdated();
  5248. return this;
  5249. };
  5250. /**
  5251. * Scale the current matrix values by a factor and add the result to a given matrix
  5252. * @param scale defines the scale factor
  5253. * @param result defines the Matrix to store the result
  5254. * @returns the current matrix
  5255. */
  5256. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5257. for (var index = 0; index < 16; index++) {
  5258. result.m[index] += this.m[index] * scale;
  5259. }
  5260. result._markAsUpdated();
  5261. return this;
  5262. };
  5263. /**
  5264. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5265. * @param ref matrix to store the result
  5266. */
  5267. Matrix.prototype.toNormalMatrix = function (ref) {
  5268. this.invertToRef(ref);
  5269. ref.transpose();
  5270. var m = ref.m;
  5271. 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);
  5272. };
  5273. /**
  5274. * Gets only rotation part of the current matrix
  5275. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5276. */
  5277. Matrix.prototype.getRotationMatrix = function () {
  5278. var result = Matrix.Identity();
  5279. this.getRotationMatrixToRef(result);
  5280. return result;
  5281. };
  5282. /**
  5283. * Extracts the rotation matrix from the current one and sets it as the passed "result"
  5284. * @param result defines the target matrix to store data to
  5285. * @returns the current matrix
  5286. */
  5287. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5288. var m = this.m;
  5289. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5290. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5291. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5292. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5293. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5294. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5295. 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);
  5296. return this;
  5297. };
  5298. // Statics
  5299. /**
  5300. * Creates a matrix from an array
  5301. * @param array defines the source array
  5302. * @param offset defines an offset in the source array
  5303. * @returns a new Matrix set from the starting index of the passed array
  5304. */
  5305. Matrix.FromArray = function (array, offset) {
  5306. var result = new Matrix();
  5307. if (!offset) {
  5308. offset = 0;
  5309. }
  5310. Matrix.FromArrayToRef(array, offset, result);
  5311. return result;
  5312. };
  5313. /**
  5314. * Copy the content of an array into a given matrix
  5315. * @param array defines the source array
  5316. * @param offset defines an offset in the source array
  5317. * @param result defines the target matrix
  5318. */
  5319. Matrix.FromArrayToRef = function (array, offset, result) {
  5320. for (var index = 0; index < 16; index++) {
  5321. result.m[index] = array[index + offset];
  5322. }
  5323. result._markAsUpdated();
  5324. };
  5325. /**
  5326. * Stores an array into a matrix after having multiplied each component by a given factor
  5327. * @param array defines the source array
  5328. * @param offset defines the offset in the source array
  5329. * @param scale defines the scaling factor
  5330. * @param result defines the target matrix
  5331. */
  5332. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5333. for (var index = 0; index < 16; index++) {
  5334. result.m[index] = array[index + offset] * scale;
  5335. }
  5336. result._markAsUpdated();
  5337. };
  5338. /**
  5339. * Stores a list of values (16) inside a given matrix
  5340. * @param initialM11 defines 1st value of 1st row
  5341. * @param initialM12 defines 2nd value of 1st row
  5342. * @param initialM13 defines 3rd value of 1st row
  5343. * @param initialM14 defines 4th value of 1st row
  5344. * @param initialM21 defines 1st value of 2nd row
  5345. * @param initialM22 defines 2nd value of 2nd row
  5346. * @param initialM23 defines 3rd value of 2nd row
  5347. * @param initialM24 defines 4th value of 2nd row
  5348. * @param initialM31 defines 1st value of 3rd row
  5349. * @param initialM32 defines 2nd value of 3rd row
  5350. * @param initialM33 defines 3rd value of 3rd row
  5351. * @param initialM34 defines 4th value of 3rd row
  5352. * @param initialM41 defines 1st value of 4th row
  5353. * @param initialM42 defines 2nd value of 4th row
  5354. * @param initialM43 defines 3rd value of 4th row
  5355. * @param initialM44 defines 4th value of 4th row
  5356. * @param result defines the target matrix
  5357. */
  5358. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5359. result.m[0] = initialM11;
  5360. result.m[1] = initialM12;
  5361. result.m[2] = initialM13;
  5362. result.m[3] = initialM14;
  5363. result.m[4] = initialM21;
  5364. result.m[5] = initialM22;
  5365. result.m[6] = initialM23;
  5366. result.m[7] = initialM24;
  5367. result.m[8] = initialM31;
  5368. result.m[9] = initialM32;
  5369. result.m[10] = initialM33;
  5370. result.m[11] = initialM34;
  5371. result.m[12] = initialM41;
  5372. result.m[13] = initialM42;
  5373. result.m[14] = initialM43;
  5374. result.m[15] = initialM44;
  5375. result._markAsUpdated();
  5376. };
  5377. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5378. /**
  5379. * Gets an identity matrix that must not be updated
  5380. */
  5381. get: function () {
  5382. return Matrix._identityReadOnly;
  5383. },
  5384. enumerable: true,
  5385. configurable: true
  5386. });
  5387. /**
  5388. * Creates new matrix from a list of values (16)
  5389. * @param initialM11 defines 1st value of 1st row
  5390. * @param initialM12 defines 2nd value of 1st row
  5391. * @param initialM13 defines 3rd value of 1st row
  5392. * @param initialM14 defines 4th value of 1st row
  5393. * @param initialM21 defines 1st value of 2nd row
  5394. * @param initialM22 defines 2nd value of 2nd row
  5395. * @param initialM23 defines 3rd value of 2nd row
  5396. * @param initialM24 defines 4th value of 2nd row
  5397. * @param initialM31 defines 1st value of 3rd row
  5398. * @param initialM32 defines 2nd value of 3rd row
  5399. * @param initialM33 defines 3rd value of 3rd row
  5400. * @param initialM34 defines 4th value of 3rd row
  5401. * @param initialM41 defines 1st value of 4th row
  5402. * @param initialM42 defines 2nd value of 4th row
  5403. * @param initialM43 defines 3rd value of 4th row
  5404. * @param initialM44 defines 4th value of 4th row
  5405. * @returns the new matrix
  5406. */
  5407. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5408. var result = new Matrix();
  5409. result.m[0] = initialM11;
  5410. result.m[1] = initialM12;
  5411. result.m[2] = initialM13;
  5412. result.m[3] = initialM14;
  5413. result.m[4] = initialM21;
  5414. result.m[5] = initialM22;
  5415. result.m[6] = initialM23;
  5416. result.m[7] = initialM24;
  5417. result.m[8] = initialM31;
  5418. result.m[9] = initialM32;
  5419. result.m[10] = initialM33;
  5420. result.m[11] = initialM34;
  5421. result.m[12] = initialM41;
  5422. result.m[13] = initialM42;
  5423. result.m[14] = initialM43;
  5424. result.m[15] = initialM44;
  5425. return result;
  5426. };
  5427. /**
  5428. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5429. * @param scale defines the scale vector3
  5430. * @param rotation defines the rotation quaternion
  5431. * @param translation defines the translation vector3
  5432. * @returns a new matrix
  5433. */
  5434. Matrix.Compose = function (scale, rotation, translation) {
  5435. var result = Matrix.Identity();
  5436. Matrix.ComposeToRef(scale, rotation, translation, result);
  5437. return result;
  5438. };
  5439. /**
  5440. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5441. * @param scale defines the scale vector3
  5442. * @param rotation defines the rotation quaternion
  5443. * @param translation defines the translation vector3
  5444. * @param result defines the target matrix
  5445. */
  5446. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5447. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5448. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5449. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5450. result.setTranslation(translation);
  5451. };
  5452. /**
  5453. * Creates a new identity matrix
  5454. * @returns a new identity matrix
  5455. */
  5456. Matrix.Identity = function () {
  5457. 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);
  5458. };
  5459. /**
  5460. * Creates a new identity matrix and stores the result in a given matrix
  5461. * @param result defines the target matrix
  5462. */
  5463. Matrix.IdentityToRef = function (result) {
  5464. 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);
  5465. };
  5466. /**
  5467. * Creates a new zero matrix
  5468. * @returns a new zero matrix
  5469. */
  5470. Matrix.Zero = function () {
  5471. 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);
  5472. };
  5473. /**
  5474. * Creates a new rotation matrix for "angle" radians around the X axis
  5475. * @param angle defines the angle (in radians) to use
  5476. * @return the new matrix
  5477. */
  5478. Matrix.RotationX = function (angle) {
  5479. var result = new Matrix();
  5480. Matrix.RotationXToRef(angle, result);
  5481. return result;
  5482. };
  5483. /**
  5484. * Creates a new matrix as the invert of a given matrix
  5485. * @param source defines the source matrix
  5486. * @returns the new matrix
  5487. */
  5488. Matrix.Invert = function (source) {
  5489. var result = new Matrix();
  5490. source.invertToRef(result);
  5491. return result;
  5492. };
  5493. /**
  5494. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5495. * @param angle defines the angle (in radians) to use
  5496. * @param result defines the target matrix
  5497. */
  5498. Matrix.RotationXToRef = function (angle, result) {
  5499. var s = Math.sin(angle);
  5500. var c = Math.cos(angle);
  5501. result.m[0] = 1.0;
  5502. result.m[15] = 1.0;
  5503. result.m[5] = c;
  5504. result.m[10] = c;
  5505. result.m[9] = -s;
  5506. result.m[6] = s;
  5507. result.m[1] = 0.0;
  5508. result.m[2] = 0.0;
  5509. result.m[3] = 0.0;
  5510. result.m[4] = 0.0;
  5511. result.m[7] = 0.0;
  5512. result.m[8] = 0.0;
  5513. result.m[11] = 0.0;
  5514. result.m[12] = 0.0;
  5515. result.m[13] = 0.0;
  5516. result.m[14] = 0.0;
  5517. result._markAsUpdated();
  5518. };
  5519. /**
  5520. * Creates a new rotation matrix for "angle" radians around the Y axis
  5521. * @param angle defines the angle (in radians) to use
  5522. * @return the new matrix
  5523. */
  5524. Matrix.RotationY = function (angle) {
  5525. var result = new Matrix();
  5526. Matrix.RotationYToRef(angle, result);
  5527. return result;
  5528. };
  5529. /**
  5530. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5531. * @param angle defines the angle (in radians) to use
  5532. * @param result defines the target matrix
  5533. */
  5534. Matrix.RotationYToRef = function (angle, result) {
  5535. var s = Math.sin(angle);
  5536. var c = Math.cos(angle);
  5537. result.m[5] = 1.0;
  5538. result.m[15] = 1.0;
  5539. result.m[0] = c;
  5540. result.m[2] = -s;
  5541. result.m[8] = s;
  5542. result.m[10] = c;
  5543. result.m[1] = 0.0;
  5544. result.m[3] = 0.0;
  5545. result.m[4] = 0.0;
  5546. result.m[6] = 0.0;
  5547. result.m[7] = 0.0;
  5548. result.m[9] = 0.0;
  5549. result.m[11] = 0.0;
  5550. result.m[12] = 0.0;
  5551. result.m[13] = 0.0;
  5552. result.m[14] = 0.0;
  5553. result._markAsUpdated();
  5554. };
  5555. /**
  5556. * Creates a new rotation matrix for "angle" radians around the Z axis
  5557. * @param angle defines the angle (in radians) to use
  5558. * @return the new matrix
  5559. */
  5560. Matrix.RotationZ = function (angle) {
  5561. var result = new Matrix();
  5562. Matrix.RotationZToRef(angle, result);
  5563. return result;
  5564. };
  5565. /**
  5566. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5567. * @param angle defines the angle (in radians) to use
  5568. * @param result defines the target matrix
  5569. */
  5570. Matrix.RotationZToRef = function (angle, result) {
  5571. var s = Math.sin(angle);
  5572. var c = Math.cos(angle);
  5573. result.m[10] = 1.0;
  5574. result.m[15] = 1.0;
  5575. result.m[0] = c;
  5576. result.m[1] = s;
  5577. result.m[4] = -s;
  5578. result.m[5] = c;
  5579. result.m[2] = 0.0;
  5580. result.m[3] = 0.0;
  5581. result.m[6] = 0.0;
  5582. result.m[7] = 0.0;
  5583. result.m[8] = 0.0;
  5584. result.m[9] = 0.0;
  5585. result.m[11] = 0.0;
  5586. result.m[12] = 0.0;
  5587. result.m[13] = 0.0;
  5588. result.m[14] = 0.0;
  5589. result._markAsUpdated();
  5590. };
  5591. /**
  5592. * Creates a new rotation matrix for "angle" radians around the given axis
  5593. * @param axis defines the axis to use
  5594. * @param angle defines the angle (in radians) to use
  5595. * @return the new matrix
  5596. */
  5597. Matrix.RotationAxis = function (axis, angle) {
  5598. var result = Matrix.Zero();
  5599. Matrix.RotationAxisToRef(axis, angle, result);
  5600. return result;
  5601. };
  5602. /**
  5603. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5604. * @param axis defines the axis to use
  5605. * @param angle defines the angle (in radians) to use
  5606. * @param result defines the target matrix
  5607. */
  5608. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5609. var s = Math.sin(-angle);
  5610. var c = Math.cos(-angle);
  5611. var c1 = 1 - c;
  5612. axis.normalize();
  5613. result.m[0] = (axis.x * axis.x) * c1 + c;
  5614. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5615. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5616. result.m[3] = 0.0;
  5617. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5618. result.m[5] = (axis.y * axis.y) * c1 + c;
  5619. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5620. result.m[7] = 0.0;
  5621. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5622. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5623. result.m[10] = (axis.z * axis.z) * c1 + c;
  5624. result.m[11] = 0.0;
  5625. result.m[15] = 1.0;
  5626. result._markAsUpdated();
  5627. };
  5628. /**
  5629. * Creates a rotation matrix
  5630. * @param yaw defines the yaw angle in radians (Y axis)
  5631. * @param pitch defines the pitch angle in radians (X axis)
  5632. * @param roll defines the roll angle in radians (X axis)
  5633. * @returns the new rotation matrix
  5634. */
  5635. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5636. var result = new Matrix();
  5637. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5638. return result;
  5639. };
  5640. /**
  5641. * Creates a rotation matrix and stores it in a given matrix
  5642. * @param yaw defines the yaw angle in radians (Y axis)
  5643. * @param pitch defines the pitch angle in radians (X axis)
  5644. * @param roll defines the roll angle in radians (X axis)
  5645. * @param result defines the target matrix
  5646. */
  5647. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5648. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5649. this._tempQuaternion.toRotationMatrix(result);
  5650. };
  5651. /**
  5652. * Creates a scaling matrix
  5653. * @param x defines the scale factor on X axis
  5654. * @param y defines the scale factor on Y axis
  5655. * @param z defines the scale factor on Z axis
  5656. * @returns the new matrix
  5657. */
  5658. Matrix.Scaling = function (x, y, z) {
  5659. var result = Matrix.Zero();
  5660. Matrix.ScalingToRef(x, y, z, result);
  5661. return result;
  5662. };
  5663. /**
  5664. * Creates a scaling matrix and stores it in a given matrix
  5665. * @param x defines the scale factor on X axis
  5666. * @param y defines the scale factor on Y axis
  5667. * @param z defines the scale factor on Z axis
  5668. * @param result defines the target matrix
  5669. */
  5670. Matrix.ScalingToRef = function (x, y, z, result) {
  5671. result.m[0] = x;
  5672. result.m[1] = 0.0;
  5673. result.m[2] = 0.0;
  5674. result.m[3] = 0.0;
  5675. result.m[4] = 0.0;
  5676. result.m[5] = y;
  5677. result.m[6] = 0.0;
  5678. result.m[7] = 0.0;
  5679. result.m[8] = 0.0;
  5680. result.m[9] = 0.0;
  5681. result.m[10] = z;
  5682. result.m[11] = 0.0;
  5683. result.m[12] = 0.0;
  5684. result.m[13] = 0.0;
  5685. result.m[14] = 0.0;
  5686. result.m[15] = 1.0;
  5687. result._markAsUpdated();
  5688. };
  5689. /**
  5690. * Creates a translation matrix
  5691. * @param x defines the translation on X axis
  5692. * @param y defines the translation on Y axis
  5693. * @param z defines the translationon Z axis
  5694. * @returns the new matrix
  5695. */
  5696. Matrix.Translation = function (x, y, z) {
  5697. var result = Matrix.Identity();
  5698. Matrix.TranslationToRef(x, y, z, result);
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a translation matrix and stores it in a given matrix
  5703. * @param x defines the translation on X axis
  5704. * @param y defines the translation on Y axis
  5705. * @param z defines the translationon Z axis
  5706. * @param result defines the target matrix
  5707. */
  5708. Matrix.TranslationToRef = function (x, y, z, result) {
  5709. 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);
  5710. };
  5711. /**
  5712. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5713. * @param startValue defines the start value
  5714. * @param endValue defines the end value
  5715. * @param gradient defines the gradient factor
  5716. * @returns the new matrix
  5717. */
  5718. Matrix.Lerp = function (startValue, endValue, gradient) {
  5719. var result = Matrix.Zero();
  5720. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5721. return result;
  5722. };
  5723. /**
  5724. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5725. * @param startValue defines the start value
  5726. * @param endValue defines the end value
  5727. * @param gradient defines the gradient factor
  5728. * @param result defines the Matrix object where to store data
  5729. */
  5730. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5731. for (var index = 0; index < 16; index++) {
  5732. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5733. }
  5734. result._markAsUpdated();
  5735. };
  5736. /**
  5737. * Builds a new matrix whose values are computed by:
  5738. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5739. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5740. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5741. * @param startValue defines the first matrix
  5742. * @param endValue defines the second matrix
  5743. * @param gradient defines the gradient between the two matrices
  5744. * @returns the new matrix
  5745. */
  5746. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5747. var result = Matrix.Zero();
  5748. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5749. return result;
  5750. };
  5751. /**
  5752. * Update a matrix to values which are computed by:
  5753. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5754. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5755. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5756. * @param startValue defines the first matrix
  5757. * @param endValue defines the second matrix
  5758. * @param gradient defines the gradient between the two matrices
  5759. * @param result defines the target matrix
  5760. */
  5761. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5762. var startScale = MathTmp.Vector3[0];
  5763. var startRotation = MathTmp.Quaternion[0];
  5764. var startTranslation = MathTmp.Vector3[1];
  5765. startValue.decompose(startScale, startRotation, startTranslation);
  5766. var endScale = MathTmp.Vector3[2];
  5767. var endRotation = MathTmp.Quaternion[1];
  5768. var endTranslation = MathTmp.Vector3[3];
  5769. endValue.decompose(endScale, endRotation, endTranslation);
  5770. var resultScale = MathTmp.Vector3[4];
  5771. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  5772. var resultRotation = MathTmp.Quaternion[2];
  5773. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  5774. var resultTranslation = MathTmp.Vector3[5];
  5775. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  5776. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  5777. };
  5778. /**
  5779. * 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"
  5780. * This function works in left handed mode
  5781. * @param eye defines the final position of the entity
  5782. * @param target defines where the entity should look at
  5783. * @param up defines the up vector for the entity
  5784. * @returns the new matrix
  5785. */
  5786. Matrix.LookAtLH = function (eye, target, up) {
  5787. var result = Matrix.Zero();
  5788. Matrix.LookAtLHToRef(eye, target, up, result);
  5789. return result;
  5790. };
  5791. /**
  5792. * 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".
  5793. * This function works in left handed mode
  5794. * @param eye defines the final position of the entity
  5795. * @param target defines where the entity should look at
  5796. * @param up defines the up vector for the entity
  5797. * @param result defines the target matrix
  5798. */
  5799. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5800. // Z axis
  5801. target.subtractToRef(eye, this._zAxis);
  5802. this._zAxis.normalize();
  5803. // X axis
  5804. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5805. if (this._xAxis.lengthSquared() === 0) {
  5806. this._xAxis.x = 1.0;
  5807. }
  5808. else {
  5809. this._xAxis.normalize();
  5810. }
  5811. // Y axis
  5812. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5813. this._yAxis.normalize();
  5814. // Eye angles
  5815. var ex = -Vector3.Dot(this._xAxis, eye);
  5816. var ey = -Vector3.Dot(this._yAxis, eye);
  5817. var ez = -Vector3.Dot(this._zAxis, eye);
  5818. 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);
  5819. };
  5820. /**
  5821. * 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"
  5822. * This function works in right handed mode
  5823. * @param eye defines the final position of the entity
  5824. * @param target defines where the entity should look at
  5825. * @param up defines the up vector for the entity
  5826. * @returns the new matrix
  5827. */
  5828. Matrix.LookAtRH = function (eye, target, up) {
  5829. var result = Matrix.Zero();
  5830. Matrix.LookAtRHToRef(eye, target, up, result);
  5831. return result;
  5832. };
  5833. /**
  5834. * 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".
  5835. * This function works in right handed mode
  5836. * @param eye defines the final position of the entity
  5837. * @param target defines where the entity should look at
  5838. * @param up defines the up vector for the entity
  5839. * @param result defines the target matrix
  5840. */
  5841. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5842. // Z axis
  5843. eye.subtractToRef(target, this._zAxis);
  5844. this._zAxis.normalize();
  5845. // X axis
  5846. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5847. if (this._xAxis.lengthSquared() === 0) {
  5848. this._xAxis.x = 1.0;
  5849. }
  5850. else {
  5851. this._xAxis.normalize();
  5852. }
  5853. // Y axis
  5854. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5855. this._yAxis.normalize();
  5856. // Eye angles
  5857. var ex = -Vector3.Dot(this._xAxis, eye);
  5858. var ey = -Vector3.Dot(this._yAxis, eye);
  5859. var ez = -Vector3.Dot(this._zAxis, eye);
  5860. 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);
  5861. };
  5862. /**
  5863. * Create a left-handed orthographic projection matrix
  5864. * @param width defines the viewport width
  5865. * @param height defines the viewport height
  5866. * @param znear defines the near clip plane
  5867. * @param zfar defines the far clip plane
  5868. * @returns a new matrix as a left-handed orthographic projection matrix
  5869. */
  5870. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5871. var matrix = Matrix.Zero();
  5872. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5873. return matrix;
  5874. };
  5875. /**
  5876. * Store a left-handed orthographic projection to a given matrix
  5877. * @param width defines the viewport width
  5878. * @param height defines the viewport height
  5879. * @param znear defines the near clip plane
  5880. * @param zfar defines the far clip plane
  5881. * @param result defines the target matrix
  5882. */
  5883. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5884. var n = znear;
  5885. var f = zfar;
  5886. var a = 2.0 / width;
  5887. var b = 2.0 / height;
  5888. var c = 2.0 / (f - n);
  5889. var d = -(f + n) / (f - n);
  5890. 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);
  5891. };
  5892. /**
  5893. * Create a left-handed orthographic projection matrix
  5894. * @param left defines the viewport left coordinate
  5895. * @param right defines the viewport right coordinate
  5896. * @param bottom defines the viewport bottom coordinate
  5897. * @param top defines the viewport top coordinate
  5898. * @param znear defines the near clip plane
  5899. * @param zfar defines the far clip plane
  5900. * @returns a new matrix as a left-handed orthographic projection matrix
  5901. */
  5902. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5903. var matrix = Matrix.Zero();
  5904. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5905. return matrix;
  5906. };
  5907. /**
  5908. * Stores a left-handed orthographic projection into a given matrix
  5909. * @param left defines the viewport left coordinate
  5910. * @param right defines the viewport right coordinate
  5911. * @param bottom defines the viewport bottom coordinate
  5912. * @param top defines the viewport top coordinate
  5913. * @param znear defines the near clip plane
  5914. * @param zfar defines the far clip plane
  5915. * @param result defines the target matrix
  5916. */
  5917. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5918. var n = znear;
  5919. var f = zfar;
  5920. var a = 2.0 / (right - left);
  5921. var b = 2.0 / (top - bottom);
  5922. var c = 2.0 / (f - n);
  5923. var d = -(f + n) / (f - n);
  5924. var i0 = (left + right) / (left - right);
  5925. var i1 = (top + bottom) / (bottom - top);
  5926. 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);
  5927. };
  5928. /**
  5929. * Creates a right-handed orthographic projection matrix
  5930. * @param left defines the viewport left coordinate
  5931. * @param right defines the viewport right coordinate
  5932. * @param bottom defines the viewport bottom coordinate
  5933. * @param top defines the viewport top coordinate
  5934. * @param znear defines the near clip plane
  5935. * @param zfar defines the far clip plane
  5936. * @returns a new matrix as a right-handed orthographic projection matrix
  5937. */
  5938. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5939. var matrix = Matrix.Zero();
  5940. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5941. return matrix;
  5942. };
  5943. /**
  5944. * Stores a right-handed orthographic projection into a given matrix
  5945. * @param left defines the viewport left coordinate
  5946. * @param right defines the viewport right coordinate
  5947. * @param bottom defines the viewport bottom coordinate
  5948. * @param top defines the viewport top coordinate
  5949. * @param znear defines the near clip plane
  5950. * @param zfar defines the far clip plane
  5951. * @param result defines the target matrix
  5952. */
  5953. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5954. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5955. result.m[10] *= -1.0;
  5956. };
  5957. /**
  5958. * Creates a left-handed perspective projection matrix
  5959. * @param width defines the viewport width
  5960. * @param height defines the viewport height
  5961. * @param znear defines the near clip plane
  5962. * @param zfar defines the far clip plane
  5963. * @returns a new matrix as a left-handed perspective projection matrix
  5964. */
  5965. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5966. var matrix = Matrix.Zero();
  5967. var n = znear;
  5968. var f = zfar;
  5969. var a = 2.0 * n / width;
  5970. var b = 2.0 * n / height;
  5971. var c = (f + n) / (f - n);
  5972. var d = -2.0 * f * n / (f - n);
  5973. 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);
  5974. return matrix;
  5975. };
  5976. /**
  5977. * Creates a left-handed perspective projection matrix
  5978. * @param fov defines the horizontal field of view
  5979. * @param aspect defines the aspect ratio
  5980. * @param znear defines the near clip plane
  5981. * @param zfar defines the far clip plane
  5982. * @returns a new matrix as a left-handed perspective projection matrix
  5983. */
  5984. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5985. var matrix = Matrix.Zero();
  5986. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5987. return matrix;
  5988. };
  5989. /**
  5990. * Stores a left-handed perspective projection into a given matrix
  5991. * @param fov defines the horizontal field of view
  5992. * @param aspect defines the aspect ratio
  5993. * @param znear defines the near clip plane
  5994. * @param zfar defines the far clip plane
  5995. * @param result defines the target matrix
  5996. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  5997. */
  5998. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5999. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6000. var n = znear;
  6001. var f = zfar;
  6002. var t = 1.0 / (Math.tan(fov * 0.5));
  6003. var a = isVerticalFovFixed ? (t / aspect) : t;
  6004. var b = isVerticalFovFixed ? t : (t * aspect);
  6005. var c = (f + n) / (f - n);
  6006. var d = -2.0 * f * n / (f - n);
  6007. 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);
  6008. };
  6009. /**
  6010. * Creates a right-handed perspective projection matrix
  6011. * @param fov defines the horizontal field of view
  6012. * @param aspect defines the aspect ratio
  6013. * @param znear defines the near clip plane
  6014. * @param zfar defines the far clip plane
  6015. * @returns a new matrix as a right-handed perspective projection matrix
  6016. */
  6017. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6018. var matrix = Matrix.Zero();
  6019. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6020. return matrix;
  6021. };
  6022. /**
  6023. * Stores a right-handed perspective projection into a given matrix
  6024. * @param fov defines the horizontal field of view
  6025. * @param aspect defines the aspect ratio
  6026. * @param znear defines the near clip plane
  6027. * @param zfar defines the far clip plane
  6028. * @param result defines the target matrix
  6029. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6030. */
  6031. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6032. //alternatively this could be expressed as:
  6033. // m = PerspectiveFovLHToRef
  6034. // m[10] *= -1.0;
  6035. // m[11] *= -1.0;
  6036. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6037. var n = znear;
  6038. var f = zfar;
  6039. var t = 1.0 / (Math.tan(fov * 0.5));
  6040. var a = isVerticalFovFixed ? (t / aspect) : t;
  6041. var b = isVerticalFovFixed ? t : (t * aspect);
  6042. var c = -(f + n) / (f - n);
  6043. var d = -2 * f * n / (f - n);
  6044. 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);
  6045. };
  6046. /**
  6047. * Stores a perspective projection for WebVR info a given matrix
  6048. * @param fov defines the field of view
  6049. * @param znear defines the near clip plane
  6050. * @param zfar defines the far clip plane
  6051. * @param result defines the target matrix
  6052. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6053. */
  6054. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6055. if (rightHanded === void 0) { rightHanded = false; }
  6056. var rightHandedFactor = rightHanded ? -1 : 1;
  6057. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6058. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6059. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6060. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6061. var xScale = 2.0 / (leftTan + rightTan);
  6062. var yScale = 2.0 / (upTan + downTan);
  6063. result.m[0] = xScale;
  6064. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6065. result.m[5] = yScale;
  6066. result.m[6] = result.m[7] = 0.0;
  6067. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6068. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6069. result.m[10] = -zfar / (znear - zfar);
  6070. result.m[11] = 1.0 * rightHandedFactor;
  6071. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6072. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6073. result._markAsUpdated();
  6074. };
  6075. /**
  6076. * Computes a complete transformation matrix
  6077. * @param viewport defines the viewport to use
  6078. * @param world defines the world matrix
  6079. * @param view defines the view matrix
  6080. * @param projection defines the projection matrix
  6081. * @param zmin defines the near clip plane
  6082. * @param zmax defines the far clip plane
  6083. * @returns the transformation matrix
  6084. */
  6085. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6086. var cw = viewport.width;
  6087. var ch = viewport.height;
  6088. var cx = viewport.x;
  6089. var cy = viewport.y;
  6090. 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);
  6091. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6092. };
  6093. /**
  6094. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6095. * @param matrix defines the matrix to use
  6096. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed matrix
  6097. */
  6098. Matrix.GetAsMatrix2x2 = function (matrix) {
  6099. return new Float32Array([
  6100. matrix.m[0], matrix.m[1],
  6101. matrix.m[4], matrix.m[5]
  6102. ]);
  6103. };
  6104. /**
  6105. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6106. * @param matrix defines the matrix to use
  6107. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed matrix
  6108. */
  6109. Matrix.GetAsMatrix3x3 = function (matrix) {
  6110. return new Float32Array([
  6111. matrix.m[0], matrix.m[1], matrix.m[2],
  6112. matrix.m[4], matrix.m[5], matrix.m[6],
  6113. matrix.m[8], matrix.m[9], matrix.m[10]
  6114. ]);
  6115. };
  6116. /**
  6117. * Compute the transpose of a given matrix
  6118. * @param matrix defines the matrix to transpose
  6119. * @returns the new matrix
  6120. */
  6121. Matrix.Transpose = function (matrix) {
  6122. var result = new Matrix();
  6123. Matrix.TransposeToRef(matrix, result);
  6124. return result;
  6125. };
  6126. /**
  6127. * Compute the transpose of a matrix and store it in a target matrix
  6128. * @param matrix defines the matrix to transpose
  6129. * @param result defines the target matrix
  6130. */
  6131. Matrix.TransposeToRef = function (matrix, result) {
  6132. result.m[0] = matrix.m[0];
  6133. result.m[1] = matrix.m[4];
  6134. result.m[2] = matrix.m[8];
  6135. result.m[3] = matrix.m[12];
  6136. result.m[4] = matrix.m[1];
  6137. result.m[5] = matrix.m[5];
  6138. result.m[6] = matrix.m[9];
  6139. result.m[7] = matrix.m[13];
  6140. result.m[8] = matrix.m[2];
  6141. result.m[9] = matrix.m[6];
  6142. result.m[10] = matrix.m[10];
  6143. result.m[11] = matrix.m[14];
  6144. result.m[12] = matrix.m[3];
  6145. result.m[13] = matrix.m[7];
  6146. result.m[14] = matrix.m[11];
  6147. result.m[15] = matrix.m[15];
  6148. };
  6149. /**
  6150. * Computes a reflection matrix from a plane
  6151. * @param plane defines the reflection plane
  6152. * @returns a new matrix
  6153. */
  6154. Matrix.Reflection = function (plane) {
  6155. var matrix = new Matrix();
  6156. Matrix.ReflectionToRef(plane, matrix);
  6157. return matrix;
  6158. };
  6159. /**
  6160. * Computes a reflection matrix from a plane
  6161. * @param plane defines the reflection plane
  6162. * @param result defines the target matrix
  6163. */
  6164. Matrix.ReflectionToRef = function (plane, result) {
  6165. plane.normalize();
  6166. var x = plane.normal.x;
  6167. var y = plane.normal.y;
  6168. var z = plane.normal.z;
  6169. var temp = -2 * x;
  6170. var temp2 = -2 * y;
  6171. var temp3 = -2 * z;
  6172. result.m[0] = (temp * x) + 1;
  6173. result.m[1] = temp2 * x;
  6174. result.m[2] = temp3 * x;
  6175. result.m[3] = 0.0;
  6176. result.m[4] = temp * y;
  6177. result.m[5] = (temp2 * y) + 1;
  6178. result.m[6] = temp3 * y;
  6179. result.m[7] = 0.0;
  6180. result.m[8] = temp * z;
  6181. result.m[9] = temp2 * z;
  6182. result.m[10] = (temp3 * z) + 1;
  6183. result.m[11] = 0.0;
  6184. result.m[12] = temp * plane.d;
  6185. result.m[13] = temp2 * plane.d;
  6186. result.m[14] = temp3 * plane.d;
  6187. result.m[15] = 1.0;
  6188. result._markAsUpdated();
  6189. };
  6190. /**
  6191. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6192. * @param xaxis defines the value of the 1st axis
  6193. * @param yaxis defines the value of the 2nd axis
  6194. * @param zaxis defines the value of the 3rd axis
  6195. * @param result defines the target matrix
  6196. */
  6197. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6198. result.m[0] = xaxis.x;
  6199. result.m[1] = xaxis.y;
  6200. result.m[2] = xaxis.z;
  6201. result.m[3] = 0.0;
  6202. result.m[4] = yaxis.x;
  6203. result.m[5] = yaxis.y;
  6204. result.m[6] = yaxis.z;
  6205. result.m[7] = 0.0;
  6206. result.m[8] = zaxis.x;
  6207. result.m[9] = zaxis.y;
  6208. result.m[10] = zaxis.z;
  6209. result.m[11] = 0.0;
  6210. result.m[12] = 0.0;
  6211. result.m[13] = 0.0;
  6212. result.m[14] = 0.0;
  6213. result.m[15] = 1.0;
  6214. result._markAsUpdated();
  6215. };
  6216. /**
  6217. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6218. * @param quat defines the quaternion to use
  6219. * @param result defines the target matrix
  6220. */
  6221. Matrix.FromQuaternionToRef = function (quat, result) {
  6222. var xx = quat.x * quat.x;
  6223. var yy = quat.y * quat.y;
  6224. var zz = quat.z * quat.z;
  6225. var xy = quat.x * quat.y;
  6226. var zw = quat.z * quat.w;
  6227. var zx = quat.z * quat.x;
  6228. var yw = quat.y * quat.w;
  6229. var yz = quat.y * quat.z;
  6230. var xw = quat.x * quat.w;
  6231. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6232. result.m[1] = 2.0 * (xy + zw);
  6233. result.m[2] = 2.0 * (zx - yw);
  6234. result.m[3] = 0.0;
  6235. result.m[4] = 2.0 * (xy - zw);
  6236. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6237. result.m[6] = 2.0 * (yz + xw);
  6238. result.m[7] = 0.0;
  6239. result.m[8] = 2.0 * (zx + yw);
  6240. result.m[9] = 2.0 * (yz - xw);
  6241. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6242. result.m[11] = 0.0;
  6243. result.m[12] = 0.0;
  6244. result.m[13] = 0.0;
  6245. result.m[14] = 0.0;
  6246. result.m[15] = 1.0;
  6247. result._markAsUpdated();
  6248. };
  6249. Matrix._tempQuaternion = new Quaternion();
  6250. Matrix._xAxis = Vector3.Zero();
  6251. Matrix._yAxis = Vector3.Zero();
  6252. Matrix._zAxis = Vector3.Zero();
  6253. Matrix._updateFlagSeed = 0;
  6254. Matrix._identityReadOnly = Matrix.Identity();
  6255. return Matrix;
  6256. }());
  6257. BABYLON.Matrix = Matrix;
  6258. var Plane = /** @class */ (function () {
  6259. /**
  6260. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6261. */
  6262. function Plane(a, b, c, d) {
  6263. this.normal = new Vector3(a, b, c);
  6264. this.d = d;
  6265. }
  6266. /**
  6267. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6268. */
  6269. Plane.prototype.asArray = function () {
  6270. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6271. };
  6272. // Methods
  6273. /**
  6274. * Returns a new plane copied from the current Plane.
  6275. */
  6276. Plane.prototype.clone = function () {
  6277. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6278. };
  6279. /**
  6280. * Returns the string "Plane".
  6281. */
  6282. Plane.prototype.getClassName = function () {
  6283. return "Plane";
  6284. };
  6285. /**
  6286. * Returns the Plane hash code.
  6287. */
  6288. Plane.prototype.getHashCode = function () {
  6289. var hash = this.normal.getHashCode();
  6290. hash = (hash * 397) ^ (this.d || 0);
  6291. return hash;
  6292. };
  6293. /**
  6294. * Normalize the current Plane in place.
  6295. * Returns the updated Plane.
  6296. */
  6297. Plane.prototype.normalize = function () {
  6298. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6299. var magnitude = 0.0;
  6300. if (norm !== 0) {
  6301. magnitude = 1.0 / norm;
  6302. }
  6303. this.normal.x *= magnitude;
  6304. this.normal.y *= magnitude;
  6305. this.normal.z *= magnitude;
  6306. this.d *= magnitude;
  6307. return this;
  6308. };
  6309. /**
  6310. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6311. */
  6312. Plane.prototype.transform = function (transformation) {
  6313. var transposedMatrix = Matrix.Transpose(transformation);
  6314. var x = this.normal.x;
  6315. var y = this.normal.y;
  6316. var z = this.normal.z;
  6317. var d = this.d;
  6318. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6319. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6320. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6321. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6322. return new Plane(normalX, normalY, normalZ, finalD);
  6323. };
  6324. /**
  6325. * Returns the dot product (float) of the point coordinates and the plane normal.
  6326. */
  6327. Plane.prototype.dotCoordinate = function (point) {
  6328. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6329. };
  6330. /**
  6331. * Updates the current Plane from the plane defined by the three passed points.
  6332. * Returns the updated Plane.
  6333. */
  6334. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6335. var x1 = point2.x - point1.x;
  6336. var y1 = point2.y - point1.y;
  6337. var z1 = point2.z - point1.z;
  6338. var x2 = point3.x - point1.x;
  6339. var y2 = point3.y - point1.y;
  6340. var z2 = point3.z - point1.z;
  6341. var yz = (y1 * z2) - (z1 * y2);
  6342. var xz = (z1 * x2) - (x1 * z2);
  6343. var xy = (x1 * y2) - (y1 * x2);
  6344. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6345. var invPyth;
  6346. if (pyth !== 0) {
  6347. invPyth = 1.0 / pyth;
  6348. }
  6349. else {
  6350. invPyth = 0.0;
  6351. }
  6352. this.normal.x = yz * invPyth;
  6353. this.normal.y = xz * invPyth;
  6354. this.normal.z = xy * invPyth;
  6355. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6356. return this;
  6357. };
  6358. /**
  6359. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6360. */
  6361. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6362. var dot = Vector3.Dot(this.normal, direction);
  6363. return (dot <= epsilon);
  6364. };
  6365. /**
  6366. * Returns the signed distance (float) from the passed point to the Plane.
  6367. */
  6368. Plane.prototype.signedDistanceTo = function (point) {
  6369. return Vector3.Dot(point, this.normal) + this.d;
  6370. };
  6371. // Statics
  6372. /**
  6373. * Returns a new Plane from the passed array.
  6374. */
  6375. Plane.FromArray = function (array) {
  6376. return new Plane(array[0], array[1], array[2], array[3]);
  6377. };
  6378. /**
  6379. * Returns a new Plane defined by the three passed points.
  6380. */
  6381. Plane.FromPoints = function (point1, point2, point3) {
  6382. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6383. result.copyFromPoints(point1, point2, point3);
  6384. return result;
  6385. };
  6386. /**
  6387. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6388. * Note : the vector "normal" is updated because normalized.
  6389. */
  6390. Plane.FromPositionAndNormal = function (origin, normal) {
  6391. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6392. normal.normalize();
  6393. result.normal = normal;
  6394. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6395. return result;
  6396. };
  6397. /**
  6398. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6399. */
  6400. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6401. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6402. return Vector3.Dot(point, normal) + d;
  6403. };
  6404. return Plane;
  6405. }());
  6406. BABYLON.Plane = Plane;
  6407. var Viewport = /** @class */ (function () {
  6408. /**
  6409. * Creates a Viewport object located at (x, y) and sized (width, height).
  6410. */
  6411. function Viewport(x, y, width, height) {
  6412. this.x = x;
  6413. this.y = y;
  6414. this.width = width;
  6415. this.height = height;
  6416. }
  6417. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6418. if (renderWidthOrEngine.getRenderWidth) {
  6419. var engine = renderWidthOrEngine;
  6420. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6421. }
  6422. var renderWidth = renderWidthOrEngine;
  6423. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6424. };
  6425. /**
  6426. * Returns a new Viewport copied from the current one.
  6427. */
  6428. Viewport.prototype.clone = function () {
  6429. return new Viewport(this.x, this.y, this.width, this.height);
  6430. };
  6431. return Viewport;
  6432. }());
  6433. BABYLON.Viewport = Viewport;
  6434. var Frustum = /** @class */ (function () {
  6435. function Frustum() {
  6436. }
  6437. /**
  6438. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6439. */
  6440. Frustum.GetPlanes = function (transform) {
  6441. var frustumPlanes = [];
  6442. for (var index = 0; index < 6; index++) {
  6443. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6444. }
  6445. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6446. return frustumPlanes;
  6447. };
  6448. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6449. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6450. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6451. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6452. frustumPlane.d = transform.m[15] + transform.m[14];
  6453. frustumPlane.normalize();
  6454. };
  6455. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6456. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6457. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6458. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6459. frustumPlane.d = transform.m[15] - transform.m[14];
  6460. frustumPlane.normalize();
  6461. };
  6462. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6463. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6464. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6465. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6466. frustumPlane.d = transform.m[15] + transform.m[12];
  6467. frustumPlane.normalize();
  6468. };
  6469. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6470. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6471. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6472. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6473. frustumPlane.d = transform.m[15] - transform.m[12];
  6474. frustumPlane.normalize();
  6475. };
  6476. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6477. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6478. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6479. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6480. frustumPlane.d = transform.m[15] - transform.m[13];
  6481. frustumPlane.normalize();
  6482. };
  6483. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6484. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6485. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6486. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6487. frustumPlane.d = transform.m[15] + transform.m[13];
  6488. frustumPlane.normalize();
  6489. };
  6490. /**
  6491. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6492. */
  6493. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6494. // Near
  6495. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6496. // Far
  6497. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6498. // Left
  6499. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6500. // Right
  6501. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6502. // Top
  6503. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6504. // Bottom
  6505. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6506. };
  6507. return Frustum;
  6508. }());
  6509. BABYLON.Frustum = Frustum;
  6510. var Space;
  6511. (function (Space) {
  6512. Space[Space["LOCAL"] = 0] = "LOCAL";
  6513. Space[Space["WORLD"] = 1] = "WORLD";
  6514. Space[Space["BONE"] = 2] = "BONE";
  6515. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6516. var Axis = /** @class */ (function () {
  6517. function Axis() {
  6518. }
  6519. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6520. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6521. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6522. return Axis;
  6523. }());
  6524. BABYLON.Axis = Axis;
  6525. ;
  6526. var BezierCurve = /** @class */ (function () {
  6527. function BezierCurve() {
  6528. }
  6529. /**
  6530. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6531. */
  6532. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6533. // Extract X (which is equal to time here)
  6534. var f0 = 1 - 3 * x2 + 3 * x1;
  6535. var f1 = 3 * x2 - 6 * x1;
  6536. var f2 = 3 * x1;
  6537. var refinedT = t;
  6538. for (var i = 0; i < 5; i++) {
  6539. var refinedT2 = refinedT * refinedT;
  6540. var refinedT3 = refinedT2 * refinedT;
  6541. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6542. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6543. refinedT -= (x - t) * slope;
  6544. refinedT = Math.min(1, Math.max(0, refinedT));
  6545. }
  6546. // Resolve cubic bezier for the given x
  6547. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6548. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6549. Math.pow(refinedT, 3);
  6550. };
  6551. return BezierCurve;
  6552. }());
  6553. BABYLON.BezierCurve = BezierCurve;
  6554. var Orientation;
  6555. (function (Orientation) {
  6556. Orientation[Orientation["CW"] = 0] = "CW";
  6557. Orientation[Orientation["CCW"] = 1] = "CCW";
  6558. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6559. var Angle = /** @class */ (function () {
  6560. /**
  6561. * Creates an Angle object of "radians" radians (float).
  6562. */
  6563. function Angle(radians) {
  6564. var _this = this;
  6565. /**
  6566. * Returns the Angle value in degrees (float).
  6567. */
  6568. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6569. /**
  6570. * Returns the Angle value in radians (float).
  6571. */
  6572. this.radians = function () { return _this._radians; };
  6573. this._radians = radians;
  6574. if (this._radians < 0.0)
  6575. this._radians += (2.0 * Math.PI);
  6576. }
  6577. /**
  6578. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6579. */
  6580. Angle.BetweenTwoPoints = function (a, b) {
  6581. var delta = b.subtract(a);
  6582. var theta = Math.atan2(delta.y, delta.x);
  6583. return new Angle(theta);
  6584. };
  6585. /**
  6586. * Returns a new Angle object from the passed float in radians.
  6587. */
  6588. Angle.FromRadians = function (radians) {
  6589. return new Angle(radians);
  6590. };
  6591. /**
  6592. * Returns a new Angle object from the passed float in degrees.
  6593. */
  6594. Angle.FromDegrees = function (degrees) {
  6595. return new Angle(degrees * Math.PI / 180.0);
  6596. };
  6597. return Angle;
  6598. }());
  6599. BABYLON.Angle = Angle;
  6600. var Arc2 = /** @class */ (function () {
  6601. /**
  6602. * Creates an Arc object from the three passed points : start, middle and end.
  6603. */
  6604. function Arc2(startPoint, midPoint, endPoint) {
  6605. this.startPoint = startPoint;
  6606. this.midPoint = midPoint;
  6607. this.endPoint = endPoint;
  6608. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6609. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6610. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6611. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6612. 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);
  6613. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6614. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6615. var a1 = this.startAngle.degrees();
  6616. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6617. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6618. // angles correction
  6619. if (a2 - a1 > +180.0)
  6620. a2 -= 360.0;
  6621. if (a2 - a1 < -180.0)
  6622. a2 += 360.0;
  6623. if (a3 - a2 > +180.0)
  6624. a3 -= 360.0;
  6625. if (a3 - a2 < -180.0)
  6626. a3 += 360.0;
  6627. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6628. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6629. }
  6630. return Arc2;
  6631. }());
  6632. BABYLON.Arc2 = Arc2;
  6633. var Path2 = /** @class */ (function () {
  6634. /**
  6635. * Creates a Path2 object from the starting 2D coordinates x and y.
  6636. */
  6637. function Path2(x, y) {
  6638. this._points = new Array();
  6639. this._length = 0.0;
  6640. this.closed = false;
  6641. this._points.push(new Vector2(x, y));
  6642. }
  6643. /**
  6644. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6645. * Returns the updated Path2.
  6646. */
  6647. Path2.prototype.addLineTo = function (x, y) {
  6648. if (this.closed) {
  6649. return this;
  6650. }
  6651. var newPoint = new Vector2(x, y);
  6652. var previousPoint = this._points[this._points.length - 1];
  6653. this._points.push(newPoint);
  6654. this._length += newPoint.subtract(previousPoint).length();
  6655. return this;
  6656. };
  6657. /**
  6658. * 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.
  6659. * Returns the updated Path2.
  6660. */
  6661. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6662. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6663. if (this.closed) {
  6664. return this;
  6665. }
  6666. var startPoint = this._points[this._points.length - 1];
  6667. var midPoint = new Vector2(midX, midY);
  6668. var endPoint = new Vector2(endX, endY);
  6669. var arc = new Arc2(startPoint, midPoint, endPoint);
  6670. var increment = arc.angle.radians() / numberOfSegments;
  6671. if (arc.orientation === Orientation.CW)
  6672. increment *= -1;
  6673. var currentAngle = arc.startAngle.radians() + increment;
  6674. for (var i = 0; i < numberOfSegments; i++) {
  6675. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6676. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6677. this.addLineTo(x, y);
  6678. currentAngle += increment;
  6679. }
  6680. return this;
  6681. };
  6682. /**
  6683. * Closes the Path2.
  6684. * Returns the Path2.
  6685. */
  6686. Path2.prototype.close = function () {
  6687. this.closed = true;
  6688. return this;
  6689. };
  6690. /**
  6691. * Returns the Path2 total length (float).
  6692. */
  6693. Path2.prototype.length = function () {
  6694. var result = this._length;
  6695. if (!this.closed) {
  6696. var lastPoint = this._points[this._points.length - 1];
  6697. var firstPoint = this._points[0];
  6698. result += (firstPoint.subtract(lastPoint).length());
  6699. }
  6700. return result;
  6701. };
  6702. /**
  6703. * Returns the Path2 internal array of points.
  6704. */
  6705. Path2.prototype.getPoints = function () {
  6706. return this._points;
  6707. };
  6708. /**
  6709. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6710. */
  6711. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6712. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6713. return Vector2.Zero();
  6714. }
  6715. var lengthPosition = normalizedLengthPosition * this.length();
  6716. var previousOffset = 0;
  6717. for (var i = 0; i < this._points.length; i++) {
  6718. var j = (i + 1) % this._points.length;
  6719. var a = this._points[i];
  6720. var b = this._points[j];
  6721. var bToA = b.subtract(a);
  6722. var nextOffset = (bToA.length() + previousOffset);
  6723. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6724. var dir = bToA.normalize();
  6725. var localOffset = lengthPosition - previousOffset;
  6726. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6727. }
  6728. previousOffset = nextOffset;
  6729. }
  6730. return Vector2.Zero();
  6731. };
  6732. /**
  6733. * Returns a new Path2 starting at the coordinates (x, y).
  6734. */
  6735. Path2.StartingAt = function (x, y) {
  6736. return new Path2(x, y);
  6737. };
  6738. return Path2;
  6739. }());
  6740. BABYLON.Path2 = Path2;
  6741. var Path3D = /** @class */ (function () {
  6742. /**
  6743. * new Path3D(path, normal, raw)
  6744. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6745. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6746. * path : an array of Vector3, the curve axis of the Path3D
  6747. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6748. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6749. */
  6750. function Path3D(path, firstNormal, raw) {
  6751. if (firstNormal === void 0) { firstNormal = null; }
  6752. this.path = path;
  6753. this._curve = new Array();
  6754. this._distances = new Array();
  6755. this._tangents = new Array();
  6756. this._normals = new Array();
  6757. this._binormals = new Array();
  6758. for (var p = 0; p < path.length; p++) {
  6759. this._curve[p] = path[p].clone(); // hard copy
  6760. }
  6761. this._raw = raw || false;
  6762. this._compute(firstNormal);
  6763. }
  6764. /**
  6765. * Returns the Path3D array of successive Vector3 designing its curve.
  6766. */
  6767. Path3D.prototype.getCurve = function () {
  6768. return this._curve;
  6769. };
  6770. /**
  6771. * Returns an array populated with tangent vectors on each Path3D curve point.
  6772. */
  6773. Path3D.prototype.getTangents = function () {
  6774. return this._tangents;
  6775. };
  6776. /**
  6777. * Returns an array populated with normal vectors on each Path3D curve point.
  6778. */
  6779. Path3D.prototype.getNormals = function () {
  6780. return this._normals;
  6781. };
  6782. /**
  6783. * Returns an array populated with binormal vectors on each Path3D curve point.
  6784. */
  6785. Path3D.prototype.getBinormals = function () {
  6786. return this._binormals;
  6787. };
  6788. /**
  6789. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6790. */
  6791. Path3D.prototype.getDistances = function () {
  6792. return this._distances;
  6793. };
  6794. /**
  6795. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6796. * Returns the same object updated.
  6797. */
  6798. Path3D.prototype.update = function (path, firstNormal) {
  6799. if (firstNormal === void 0) { firstNormal = null; }
  6800. for (var p = 0; p < path.length; p++) {
  6801. this._curve[p].x = path[p].x;
  6802. this._curve[p].y = path[p].y;
  6803. this._curve[p].z = path[p].z;
  6804. }
  6805. this._compute(firstNormal);
  6806. return this;
  6807. };
  6808. // private function compute() : computes tangents, normals and binormals
  6809. Path3D.prototype._compute = function (firstNormal) {
  6810. var l = this._curve.length;
  6811. // first and last tangents
  6812. this._tangents[0] = this._getFirstNonNullVector(0);
  6813. if (!this._raw) {
  6814. this._tangents[0].normalize();
  6815. }
  6816. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6817. if (!this._raw) {
  6818. this._tangents[l - 1].normalize();
  6819. }
  6820. // normals and binormals at first point : arbitrary vector with _normalVector()
  6821. var tg0 = this._tangents[0];
  6822. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6823. this._normals[0] = pp0;
  6824. if (!this._raw) {
  6825. this._normals[0].normalize();
  6826. }
  6827. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6828. if (!this._raw) {
  6829. this._binormals[0].normalize();
  6830. }
  6831. this._distances[0] = 0.0;
  6832. // normals and binormals : next points
  6833. var prev; // previous vector (segment)
  6834. var cur; // current vector (segment)
  6835. var curTang; // current tangent
  6836. // previous normal
  6837. var prevBinor; // previous binormal
  6838. for (var i = 1; i < l; i++) {
  6839. // tangents
  6840. prev = this._getLastNonNullVector(i);
  6841. if (i < l - 1) {
  6842. cur = this._getFirstNonNullVector(i);
  6843. this._tangents[i] = prev.add(cur);
  6844. this._tangents[i].normalize();
  6845. }
  6846. this._distances[i] = this._distances[i - 1] + prev.length();
  6847. // normals and binormals
  6848. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6849. curTang = this._tangents[i];
  6850. prevBinor = this._binormals[i - 1];
  6851. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6852. if (!this._raw) {
  6853. this._normals[i].normalize();
  6854. }
  6855. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6856. if (!this._raw) {
  6857. this._binormals[i].normalize();
  6858. }
  6859. }
  6860. };
  6861. // private function getFirstNonNullVector(index)
  6862. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6863. Path3D.prototype._getFirstNonNullVector = function (index) {
  6864. var i = 1;
  6865. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6866. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6867. i++;
  6868. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6869. }
  6870. return nNVector;
  6871. };
  6872. // private function getLastNonNullVector(index)
  6873. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6874. Path3D.prototype._getLastNonNullVector = function (index) {
  6875. var i = 1;
  6876. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6877. while (nLVector.length() === 0 && index > i + 1) {
  6878. i++;
  6879. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6880. }
  6881. return nLVector;
  6882. };
  6883. // private function normalVector(v0, vt, va) :
  6884. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6885. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6886. Path3D.prototype._normalVector = function (v0, vt, va) {
  6887. var normal0;
  6888. var tgl = vt.length();
  6889. if (tgl === 0.0) {
  6890. tgl = 1.0;
  6891. }
  6892. if (va === undefined || va === null) {
  6893. var point;
  6894. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6895. point = new Vector3(0.0, -1.0, 0.0);
  6896. }
  6897. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6898. point = new Vector3(1.0, 0.0, 0.0);
  6899. }
  6900. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6901. point = new Vector3(0.0, 0.0, 1.0);
  6902. }
  6903. else {
  6904. point = Vector3.Zero();
  6905. }
  6906. normal0 = Vector3.Cross(vt, point);
  6907. }
  6908. else {
  6909. normal0 = Vector3.Cross(vt, va);
  6910. Vector3.CrossToRef(normal0, vt, normal0);
  6911. }
  6912. normal0.normalize();
  6913. return normal0;
  6914. };
  6915. return Path3D;
  6916. }());
  6917. BABYLON.Path3D = Path3D;
  6918. var Curve3 = /** @class */ (function () {
  6919. /**
  6920. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6921. * A Curve3 is designed from a series of successive Vector3.
  6922. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6923. */
  6924. function Curve3(points) {
  6925. this._length = 0.0;
  6926. this._points = points;
  6927. this._length = this._computeLength(points);
  6928. }
  6929. /**
  6930. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6931. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6932. * @param v1 (Vector3) the control point
  6933. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6934. * @param nbPoints (integer) the wanted number of points in the curve
  6935. */
  6936. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6937. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6938. var bez = new Array();
  6939. var equation = function (t, val0, val1, val2) {
  6940. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6941. return res;
  6942. };
  6943. for (var i = 0; i <= nbPoints; i++) {
  6944. 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)));
  6945. }
  6946. return new Curve3(bez);
  6947. };
  6948. /**
  6949. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6950. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6951. * @param v1 (Vector3) the first control point
  6952. * @param v2 (Vector3) the second control point
  6953. * @param v3 (Vector3) the end point of the Cubic Bezier
  6954. * @param nbPoints (integer) the wanted number of points in the curve
  6955. */
  6956. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6957. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6958. var bez = new Array();
  6959. var equation = function (t, val0, val1, val2, val3) {
  6960. 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;
  6961. return res;
  6962. };
  6963. for (var i = 0; i <= nbPoints; i++) {
  6964. 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)));
  6965. }
  6966. return new Curve3(bez);
  6967. };
  6968. /**
  6969. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6970. * @param p1 (Vector3) the origin point of the Hermite Spline
  6971. * @param t1 (Vector3) the tangent vector at the origin point
  6972. * @param p2 (Vector3) the end point of the Hermite Spline
  6973. * @param t2 (Vector3) the tangent vector at the end point
  6974. * @param nbPoints (integer) the wanted number of points in the curve
  6975. */
  6976. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6977. var hermite = new Array();
  6978. var step = 1.0 / nbPoints;
  6979. for (var i = 0; i <= nbPoints; i++) {
  6980. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6981. }
  6982. return new Curve3(hermite);
  6983. };
  6984. /**
  6985. * Returns a Curve3 object along a CatmullRom Spline curve :
  6986. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6987. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6988. */
  6989. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6990. var totalPoints = new Array();
  6991. totalPoints.push(points[0].clone());
  6992. Array.prototype.push.apply(totalPoints, points);
  6993. totalPoints.push(points[points.length - 1].clone());
  6994. var catmullRom = new Array();
  6995. var step = 1.0 / nbPoints;
  6996. var amount = 0.0;
  6997. for (var i = 0; i < totalPoints.length - 3; i++) {
  6998. amount = 0;
  6999. for (var c = 0; c < nbPoints; c++) {
  7000. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7001. amount += step;
  7002. }
  7003. }
  7004. i--;
  7005. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7006. return new Curve3(catmullRom);
  7007. };
  7008. /**
  7009. * Returns the Curve3 stored array of successive Vector3
  7010. */
  7011. Curve3.prototype.getPoints = function () {
  7012. return this._points;
  7013. };
  7014. /**
  7015. * Returns the computed length (float) of the curve.
  7016. */
  7017. Curve3.prototype.length = function () {
  7018. return this._length;
  7019. };
  7020. /**
  7021. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7022. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7023. * curveA and curveB keep unchanged.
  7024. */
  7025. Curve3.prototype.continue = function (curve) {
  7026. var lastPoint = this._points[this._points.length - 1];
  7027. var continuedPoints = this._points.slice();
  7028. var curvePoints = curve.getPoints();
  7029. for (var i = 1; i < curvePoints.length; i++) {
  7030. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7031. }
  7032. var continuedCurve = new Curve3(continuedPoints);
  7033. return continuedCurve;
  7034. };
  7035. Curve3.prototype._computeLength = function (path) {
  7036. var l = 0;
  7037. for (var i = 1; i < path.length; i++) {
  7038. l += (path[i].subtract(path[i - 1])).length();
  7039. }
  7040. return l;
  7041. };
  7042. return Curve3;
  7043. }());
  7044. BABYLON.Curve3 = Curve3;
  7045. // Vertex formats
  7046. var PositionNormalVertex = /** @class */ (function () {
  7047. function PositionNormalVertex(position, normal) {
  7048. if (position === void 0) { position = Vector3.Zero(); }
  7049. if (normal === void 0) { normal = Vector3.Up(); }
  7050. this.position = position;
  7051. this.normal = normal;
  7052. }
  7053. PositionNormalVertex.prototype.clone = function () {
  7054. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7055. };
  7056. return PositionNormalVertex;
  7057. }());
  7058. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7059. var PositionNormalTextureVertex = /** @class */ (function () {
  7060. function PositionNormalTextureVertex(position, normal, uv) {
  7061. if (position === void 0) { position = Vector3.Zero(); }
  7062. if (normal === void 0) { normal = Vector3.Up(); }
  7063. if (uv === void 0) { uv = Vector2.Zero(); }
  7064. this.position = position;
  7065. this.normal = normal;
  7066. this.uv = uv;
  7067. }
  7068. PositionNormalTextureVertex.prototype.clone = function () {
  7069. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7070. };
  7071. return PositionNormalTextureVertex;
  7072. }());
  7073. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7074. // Temporary pre-allocated objects for engine internal use
  7075. // usage in any internal function :
  7076. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7077. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7078. var Tmp = /** @class */ (function () {
  7079. function Tmp() {
  7080. }
  7081. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7082. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7083. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7084. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7085. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7086. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7087. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7088. Matrix.Zero(), Matrix.Zero(),
  7089. Matrix.Zero(), Matrix.Zero(),
  7090. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7091. return Tmp;
  7092. }());
  7093. BABYLON.Tmp = Tmp;
  7094. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  7095. var MathTmp = /** @class */ (function () {
  7096. function MathTmp() {
  7097. }
  7098. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7099. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7100. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7101. return MathTmp;
  7102. }());
  7103. })(BABYLON || (BABYLON = {}));
  7104. //# sourceMappingURL=babylon.math.js.map
  7105. "use strict";
  7106. var BABYLON;
  7107. (function (BABYLON) {
  7108. var Scalar = /** @class */ (function () {
  7109. function Scalar() {
  7110. }
  7111. /**
  7112. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7113. */
  7114. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7115. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7116. var num = a - b;
  7117. return -epsilon <= num && num <= epsilon;
  7118. };
  7119. /**
  7120. * Returns a string : the upper case translation of the number i to hexadecimal.
  7121. */
  7122. Scalar.ToHex = function (i) {
  7123. var str = i.toString(16);
  7124. if (i <= 15) {
  7125. return ("0" + str).toUpperCase();
  7126. }
  7127. return str.toUpperCase();
  7128. };
  7129. /**
  7130. * Returns -1 if value is negative and +1 is value is positive.
  7131. * Returns the value itself if it's equal to zero.
  7132. */
  7133. Scalar.Sign = function (value) {
  7134. value = +value; // convert to a number
  7135. if (value === 0 || isNaN(value))
  7136. return value;
  7137. return value > 0 ? 1 : -1;
  7138. };
  7139. /**
  7140. * Returns the value itself if it's between min and max.
  7141. * Returns min if the value is lower than min.
  7142. * Returns max if the value is greater than max.
  7143. */
  7144. Scalar.Clamp = function (value, min, max) {
  7145. if (min === void 0) { min = 0; }
  7146. if (max === void 0) { max = 1; }
  7147. return Math.min(max, Math.max(min, value));
  7148. };
  7149. /**
  7150. * Returns the log2 of value.
  7151. */
  7152. Scalar.Log2 = function (value) {
  7153. return Math.log(value) * Math.LOG2E;
  7154. };
  7155. /**
  7156. * Loops the value, so that it is never larger than length and never smaller than 0.
  7157. *
  7158. * This is similar to the modulo operator but it works with floating point numbers.
  7159. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7160. * With t = 5 and length = 2.5, the result would be 0.0.
  7161. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7162. */
  7163. Scalar.Repeat = function (value, length) {
  7164. return value - Math.floor(value / length) * length;
  7165. };
  7166. /**
  7167. * Normalize the value between 0.0 and 1.0 using min and max values
  7168. */
  7169. Scalar.Normalize = function (value, min, max) {
  7170. return (value - min) / (max - min);
  7171. };
  7172. /**
  7173. * Denormalize the value from 0.0 and 1.0 using min and max values
  7174. */
  7175. Scalar.Denormalize = function (normalized, min, max) {
  7176. return (normalized * (max - min) + min);
  7177. };
  7178. /**
  7179. * Calculates the shortest difference between two given angles given in degrees.
  7180. */
  7181. Scalar.DeltaAngle = function (current, target) {
  7182. var num = Scalar.Repeat(target - current, 360.0);
  7183. if (num > 180.0) {
  7184. num -= 360.0;
  7185. }
  7186. return num;
  7187. };
  7188. /**
  7189. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7190. *
  7191. * The returned value will move back and forth between 0 and length
  7192. */
  7193. Scalar.PingPong = function (tx, length) {
  7194. var t = Scalar.Repeat(tx, length * 2.0);
  7195. return length - Math.abs(t - length);
  7196. };
  7197. /**
  7198. * Interpolates between min and max with smoothing at the limits.
  7199. *
  7200. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7201. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7202. */
  7203. Scalar.SmoothStep = function (from, to, tx) {
  7204. var t = Scalar.Clamp(tx);
  7205. t = -2.0 * t * t * t + 3.0 * t * t;
  7206. return to * t + from * (1.0 - t);
  7207. };
  7208. /**
  7209. * Moves a value current towards target.
  7210. *
  7211. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7212. * Negative values of maxDelta pushes the value away from target.
  7213. */
  7214. Scalar.MoveTowards = function (current, target, maxDelta) {
  7215. var result = 0;
  7216. if (Math.abs(target - current) <= maxDelta) {
  7217. result = target;
  7218. }
  7219. else {
  7220. result = current + Scalar.Sign(target - current) * maxDelta;
  7221. }
  7222. return result;
  7223. };
  7224. /**
  7225. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7226. *
  7227. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7228. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7229. */
  7230. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7231. var num = Scalar.DeltaAngle(current, target);
  7232. var result = 0;
  7233. if (-maxDelta < num && num < maxDelta) {
  7234. result = target;
  7235. }
  7236. else {
  7237. target = current + num;
  7238. result = Scalar.MoveTowards(current, target, maxDelta);
  7239. }
  7240. return result;
  7241. };
  7242. /**
  7243. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7244. */
  7245. Scalar.Lerp = function (start, end, amount) {
  7246. return start + ((end - start) * amount);
  7247. };
  7248. /**
  7249. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7250. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7251. */
  7252. Scalar.LerpAngle = function (start, end, amount) {
  7253. var num = Scalar.Repeat(end - start, 360.0);
  7254. if (num > 180.0) {
  7255. num -= 360.0;
  7256. }
  7257. return start + num * Scalar.Clamp(amount);
  7258. };
  7259. /**
  7260. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7261. */
  7262. Scalar.InverseLerp = function (a, b, value) {
  7263. var result = 0;
  7264. if (a != b) {
  7265. result = Scalar.Clamp((value - a) / (b - a));
  7266. }
  7267. else {
  7268. result = 0.0;
  7269. }
  7270. return result;
  7271. };
  7272. /**
  7273. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7274. */
  7275. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7276. var squared = amount * amount;
  7277. var cubed = amount * squared;
  7278. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7279. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7280. var part3 = (cubed - (2.0 * squared)) + amount;
  7281. var part4 = cubed - squared;
  7282. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7283. };
  7284. /**
  7285. * Returns a random float number between and min and max values
  7286. */
  7287. Scalar.RandomRange = function (min, max) {
  7288. if (min === max)
  7289. return min;
  7290. return ((Math.random() * (max - min)) + min);
  7291. };
  7292. /**
  7293. * This function returns percentage of a number in a given range.
  7294. *
  7295. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7296. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7297. */
  7298. Scalar.RangeToPercent = function (number, min, max) {
  7299. return ((number - min) / (max - min));
  7300. };
  7301. /**
  7302. * This function returns number that corresponds to the percentage in a given range.
  7303. *
  7304. * PercentToRange(0.34,0,100) will return 34.
  7305. */
  7306. Scalar.PercentToRange = function (percent, min, max) {
  7307. return ((max - min) * percent + min);
  7308. };
  7309. /**
  7310. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7311. * @param angle The angle to normalize in radian.
  7312. * @return The converted angle.
  7313. */
  7314. Scalar.NormalizeRadians = function (angle) {
  7315. // More precise but slower version kept for reference.
  7316. // angle = angle % Tools.TwoPi;
  7317. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7318. //if (angle > Math.PI) {
  7319. // angle -= Tools.TwoPi;
  7320. //}
  7321. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7322. return angle;
  7323. };
  7324. /**
  7325. * Two pi constants convenient for computation.
  7326. */
  7327. Scalar.TwoPi = Math.PI * 2;
  7328. return Scalar;
  7329. }());
  7330. BABYLON.Scalar = Scalar;
  7331. })(BABYLON || (BABYLON = {}));
  7332. //# sourceMappingURL=babylon.math.scalar.js.map
  7333. "use strict";
  7334. //# sourceMappingURL=babylon.mixins.js.map
  7335. "use strict";
  7336. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7337. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7338. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7339. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7340. //# sourceMappingURL=babylon.webgl2.js.map
  7341. "use strict";
  7342. var BABYLON;
  7343. (function (BABYLON) {
  7344. var __decoratorInitialStore = {};
  7345. var __mergedStore = {};
  7346. var _copySource = function (creationFunction, source, instanciate) {
  7347. var destination = creationFunction();
  7348. // Tags
  7349. if (BABYLON.Tags) {
  7350. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7351. }
  7352. var classStore = getMergedStore(destination);
  7353. // Properties
  7354. for (var property in classStore) {
  7355. var propertyDescriptor = classStore[property];
  7356. var sourceProperty = source[property];
  7357. var propertyType = propertyDescriptor.type;
  7358. if (sourceProperty !== undefined && sourceProperty !== null) {
  7359. switch (propertyType) {
  7360. case 0: // Value
  7361. case 6: // Mesh reference
  7362. case 11:// Camera reference
  7363. destination[property] = sourceProperty;
  7364. break;
  7365. case 1:// Texture
  7366. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7367. break;
  7368. case 2: // Color3
  7369. case 3: // FresnelParameters
  7370. case 4: // Vector2
  7371. case 5: // Vector3
  7372. case 7: // Color Curves
  7373. case 10:// Quaternion
  7374. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7375. break;
  7376. }
  7377. }
  7378. }
  7379. return destination;
  7380. };
  7381. function getDirectStore(target) {
  7382. var classKey = target.getClassName();
  7383. if (!__decoratorInitialStore[classKey]) {
  7384. __decoratorInitialStore[classKey] = {};
  7385. }
  7386. return __decoratorInitialStore[classKey];
  7387. }
  7388. /**
  7389. * Return the list of properties flagged as serializable
  7390. * @param target: host object
  7391. */
  7392. function getMergedStore(target) {
  7393. var classKey = target.getClassName();
  7394. if (__mergedStore[classKey]) {
  7395. return __mergedStore[classKey];
  7396. }
  7397. __mergedStore[classKey] = {};
  7398. var store = __mergedStore[classKey];
  7399. var currentTarget = target;
  7400. var currentKey = classKey;
  7401. while (currentKey) {
  7402. var initialStore = __decoratorInitialStore[currentKey];
  7403. for (var property in initialStore) {
  7404. store[property] = initialStore[property];
  7405. }
  7406. var parent_1 = void 0;
  7407. var done = false;
  7408. do {
  7409. parent_1 = Object.getPrototypeOf(currentTarget);
  7410. if (!parent_1.getClassName) {
  7411. done = true;
  7412. break;
  7413. }
  7414. if (parent_1.getClassName() !== currentKey) {
  7415. break;
  7416. }
  7417. currentTarget = parent_1;
  7418. } while (parent_1);
  7419. if (done) {
  7420. break;
  7421. }
  7422. currentKey = parent_1.getClassName();
  7423. currentTarget = parent_1;
  7424. }
  7425. return store;
  7426. }
  7427. function generateSerializableMember(type, sourceName) {
  7428. return function (target, propertyKey) {
  7429. var classStore = getDirectStore(target);
  7430. if (!classStore[propertyKey]) {
  7431. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7432. }
  7433. };
  7434. }
  7435. function generateExpandMember(setCallback, targetKey) {
  7436. if (targetKey === void 0) { targetKey = null; }
  7437. return function (target, propertyKey) {
  7438. var key = targetKey || ("_" + propertyKey);
  7439. Object.defineProperty(target, propertyKey, {
  7440. get: function () {
  7441. return this[key];
  7442. },
  7443. set: function (value) {
  7444. if (this[key] === value) {
  7445. return;
  7446. }
  7447. this[key] = value;
  7448. target[setCallback].apply(this);
  7449. },
  7450. enumerable: true,
  7451. configurable: true
  7452. });
  7453. };
  7454. }
  7455. function expandToProperty(callback, targetKey) {
  7456. if (targetKey === void 0) { targetKey = null; }
  7457. return generateExpandMember(callback, targetKey);
  7458. }
  7459. BABYLON.expandToProperty = expandToProperty;
  7460. function serialize(sourceName) {
  7461. return generateSerializableMember(0, sourceName); // value member
  7462. }
  7463. BABYLON.serialize = serialize;
  7464. function serializeAsTexture(sourceName) {
  7465. return generateSerializableMember(1, sourceName); // texture member
  7466. }
  7467. BABYLON.serializeAsTexture = serializeAsTexture;
  7468. function serializeAsColor3(sourceName) {
  7469. return generateSerializableMember(2, sourceName); // color3 member
  7470. }
  7471. BABYLON.serializeAsColor3 = serializeAsColor3;
  7472. function serializeAsFresnelParameters(sourceName) {
  7473. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7474. }
  7475. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7476. function serializeAsVector2(sourceName) {
  7477. return generateSerializableMember(4, sourceName); // vector2 member
  7478. }
  7479. BABYLON.serializeAsVector2 = serializeAsVector2;
  7480. function serializeAsVector3(sourceName) {
  7481. return generateSerializableMember(5, sourceName); // vector3 member
  7482. }
  7483. BABYLON.serializeAsVector3 = serializeAsVector3;
  7484. function serializeAsMeshReference(sourceName) {
  7485. return generateSerializableMember(6, sourceName); // mesh reference member
  7486. }
  7487. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7488. function serializeAsColorCurves(sourceName) {
  7489. return generateSerializableMember(7, sourceName); // color curves
  7490. }
  7491. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7492. function serializeAsColor4(sourceName) {
  7493. return generateSerializableMember(8, sourceName); // color 4
  7494. }
  7495. BABYLON.serializeAsColor4 = serializeAsColor4;
  7496. function serializeAsImageProcessingConfiguration(sourceName) {
  7497. return generateSerializableMember(9, sourceName); // image processing
  7498. }
  7499. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7500. function serializeAsQuaternion(sourceName) {
  7501. return generateSerializableMember(10, sourceName); // quaternion member
  7502. }
  7503. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7504. /**
  7505. * Decorator used to define property that can be serialized as reference to a camera
  7506. * @param sourceName defines the name of the property to decorate
  7507. */
  7508. function serializeAsCameraReference(sourceName) {
  7509. return generateSerializableMember(11, sourceName); // camera reference member
  7510. }
  7511. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7512. var SerializationHelper = /** @class */ (function () {
  7513. function SerializationHelper() {
  7514. }
  7515. SerializationHelper.Serialize = function (entity, serializationObject) {
  7516. if (!serializationObject) {
  7517. serializationObject = {};
  7518. }
  7519. // Tags
  7520. if (BABYLON.Tags) {
  7521. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7522. }
  7523. var serializedProperties = getMergedStore(entity);
  7524. // Properties
  7525. for (var property in serializedProperties) {
  7526. var propertyDescriptor = serializedProperties[property];
  7527. var targetPropertyName = propertyDescriptor.sourceName || property;
  7528. var propertyType = propertyDescriptor.type;
  7529. var sourceProperty = entity[property];
  7530. if (sourceProperty !== undefined && sourceProperty !== null) {
  7531. switch (propertyType) {
  7532. case 0:// Value
  7533. serializationObject[targetPropertyName] = sourceProperty;
  7534. break;
  7535. case 1:// Texture
  7536. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7537. break;
  7538. case 2:// Color3
  7539. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7540. break;
  7541. case 3:// FresnelParameters
  7542. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7543. break;
  7544. case 4:// Vector2
  7545. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7546. break;
  7547. case 5:// Vector3
  7548. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7549. break;
  7550. case 6:// Mesh reference
  7551. serializationObject[targetPropertyName] = sourceProperty.id;
  7552. break;
  7553. case 7:// Color Curves
  7554. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7555. break;
  7556. case 8:// Color 4
  7557. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7558. break;
  7559. case 9:// Image Processing
  7560. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7561. break;
  7562. case 10:// Quaternion
  7563. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7564. break;
  7565. case 11:// Camera reference
  7566. serializationObject[targetPropertyName] = sourceProperty.id;
  7567. break;
  7568. }
  7569. }
  7570. }
  7571. return serializationObject;
  7572. };
  7573. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7574. if (rootUrl === void 0) { rootUrl = null; }
  7575. var destination = creationFunction();
  7576. if (!rootUrl) {
  7577. rootUrl = "";
  7578. }
  7579. // Tags
  7580. if (BABYLON.Tags) {
  7581. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7582. }
  7583. var classStore = getMergedStore(destination);
  7584. // Properties
  7585. for (var property in classStore) {
  7586. var propertyDescriptor = classStore[property];
  7587. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7588. var propertyType = propertyDescriptor.type;
  7589. if (sourceProperty !== undefined && sourceProperty !== null) {
  7590. var dest = destination;
  7591. switch (propertyType) {
  7592. case 0:// Value
  7593. dest[property] = sourceProperty;
  7594. break;
  7595. case 1:// Texture
  7596. if (scene) {
  7597. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7598. }
  7599. break;
  7600. case 2:// Color3
  7601. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7602. break;
  7603. case 3:// FresnelParameters
  7604. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7605. break;
  7606. case 4:// Vector2
  7607. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7608. break;
  7609. case 5:// Vector3
  7610. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7611. break;
  7612. case 6:// Mesh reference
  7613. if (scene) {
  7614. dest[property] = scene.getLastMeshByID(sourceProperty);
  7615. }
  7616. break;
  7617. case 7:// Color Curves
  7618. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7619. break;
  7620. case 8:// Color 4
  7621. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7622. break;
  7623. case 9:// Image Processing
  7624. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7625. break;
  7626. case 10:// Quaternion
  7627. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7628. break;
  7629. case 11:// Camera reference
  7630. if (scene) {
  7631. dest[property] = scene.getCameraByID(sourceProperty);
  7632. }
  7633. break;
  7634. }
  7635. }
  7636. }
  7637. return destination;
  7638. };
  7639. SerializationHelper.Clone = function (creationFunction, source) {
  7640. return _copySource(creationFunction, source, false);
  7641. };
  7642. SerializationHelper.Instanciate = function (creationFunction, source) {
  7643. return _copySource(creationFunction, source, true);
  7644. };
  7645. return SerializationHelper;
  7646. }());
  7647. BABYLON.SerializationHelper = SerializationHelper;
  7648. })(BABYLON || (BABYLON = {}));
  7649. //# sourceMappingURL=babylon.decorators.js.map
  7650. "use strict";
  7651. var BABYLON;
  7652. (function (BABYLON) {
  7653. /**
  7654. * Wrapper class for promise with external resolve and reject.
  7655. */
  7656. var Deferred = /** @class */ (function () {
  7657. /**
  7658. * Constructor for this deferred object.
  7659. */
  7660. function Deferred() {
  7661. var _this = this;
  7662. this.promise = new Promise(function (resolve, reject) {
  7663. _this._resolve = resolve;
  7664. _this._reject = reject;
  7665. });
  7666. }
  7667. Object.defineProperty(Deferred.prototype, "resolve", {
  7668. /**
  7669. * The resolve method of the promise associated with this deferred object.
  7670. */
  7671. get: function () {
  7672. return this._resolve;
  7673. },
  7674. enumerable: true,
  7675. configurable: true
  7676. });
  7677. Object.defineProperty(Deferred.prototype, "reject", {
  7678. /**
  7679. * The reject method of the promise associated with this deferred object.
  7680. */
  7681. get: function () {
  7682. return this._reject;
  7683. },
  7684. enumerable: true,
  7685. configurable: true
  7686. });
  7687. return Deferred;
  7688. }());
  7689. BABYLON.Deferred = Deferred;
  7690. })(BABYLON || (BABYLON = {}));
  7691. //# sourceMappingURL=babylon.deferred.js.map
  7692. "use strict";
  7693. var BABYLON;
  7694. (function (BABYLON) {
  7695. /**
  7696. * A class serves as a medium between the observable and its observers
  7697. */
  7698. var EventState = /** @class */ (function () {
  7699. /**
  7700. * Create a new EventState
  7701. * @param mask defines the mask associated with this state
  7702. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7703. * @param target defines the original target of the state
  7704. * @param currentTarget defines the current target of the state
  7705. */
  7706. function EventState(mask, skipNextObservers, target, currentTarget) {
  7707. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7708. this.initalize(mask, skipNextObservers, target, currentTarget);
  7709. }
  7710. /**
  7711. * Initialize the current event state
  7712. * @param mask defines the mask associated with this state
  7713. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7714. * @param target defines the original target of the state
  7715. * @param currentTarget defines the current target of the state
  7716. * @returns the current event state
  7717. */
  7718. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7719. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7720. this.mask = mask;
  7721. this.skipNextObservers = skipNextObservers;
  7722. this.target = target;
  7723. this.currentTarget = currentTarget;
  7724. return this;
  7725. };
  7726. return EventState;
  7727. }());
  7728. BABYLON.EventState = EventState;
  7729. /**
  7730. * Represent an Observer registered to a given Observable object.
  7731. */
  7732. var Observer = /** @class */ (function () {
  7733. /**
  7734. * Creates a new observer
  7735. * @param callback defines the callback to call when the observer is notified
  7736. * @param mask defines the mask of the observer (used to filter notifications)
  7737. * @param scope defines the current scope used to restore the JS context
  7738. */
  7739. function Observer(
  7740. /**
  7741. * Defines the callback to call when the observer is notified
  7742. */
  7743. callback,
  7744. /**
  7745. * Defines the mask of the observer (used to filter notifications)
  7746. */
  7747. mask,
  7748. /**
  7749. * Defines the current scope used to restore the JS context
  7750. */
  7751. scope) {
  7752. if (scope === void 0) { scope = null; }
  7753. this.callback = callback;
  7754. this.mask = mask;
  7755. this.scope = scope;
  7756. /** @ignore */
  7757. this._willBeUnregistered = false;
  7758. /**
  7759. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7760. */
  7761. this.unregisterOnNextCall = false;
  7762. }
  7763. return Observer;
  7764. }());
  7765. BABYLON.Observer = Observer;
  7766. /**
  7767. * Represent a list of observers registered to multiple Observables object.
  7768. */
  7769. var MultiObserver = /** @class */ (function () {
  7770. function MultiObserver() {
  7771. }
  7772. /**
  7773. * Release associated resources
  7774. */
  7775. MultiObserver.prototype.dispose = function () {
  7776. if (this._observers && this._observables) {
  7777. for (var index = 0; index < this._observers.length; index++) {
  7778. this._observables[index].remove(this._observers[index]);
  7779. }
  7780. }
  7781. this._observers = null;
  7782. this._observables = null;
  7783. };
  7784. /**
  7785. * Raise a callback when one of the observable will notify
  7786. * @param observables defines a list of observables to watch
  7787. * @param callback defines the callback to call on notification
  7788. * @param mask defines the mask used to filter notifications
  7789. * @param scope defines the current scope used to restore the JS context
  7790. * @returns the new MultiObserver
  7791. */
  7792. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7793. if (mask === void 0) { mask = -1; }
  7794. if (scope === void 0) { scope = null; }
  7795. var result = new MultiObserver();
  7796. result._observers = new Array();
  7797. result._observables = observables;
  7798. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7799. var observable = observables_1[_i];
  7800. var observer = observable.add(callback, mask, false, scope);
  7801. if (observer) {
  7802. result._observers.push(observer);
  7803. }
  7804. }
  7805. return result;
  7806. };
  7807. return MultiObserver;
  7808. }());
  7809. BABYLON.MultiObserver = MultiObserver;
  7810. /**
  7811. * The Observable class is a simple implementation of the Observable pattern.
  7812. *
  7813. * 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.
  7814. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7815. * 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).
  7816. * 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.
  7817. */
  7818. var Observable = /** @class */ (function () {
  7819. /**
  7820. * Creates a new observable
  7821. * @param onObserverAdded defines a callback to call when a new observer is added
  7822. */
  7823. function Observable(onObserverAdded) {
  7824. this._observers = new Array();
  7825. this._eventState = new EventState(0);
  7826. if (onObserverAdded) {
  7827. this._onObserverAdded = onObserverAdded;
  7828. }
  7829. }
  7830. /**
  7831. * Create a new Observer with the specified callback
  7832. * @param callback the callback that will be executed for that Observer
  7833. * @param mask the mask used to filter observers
  7834. * @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.
  7835. * @param scope optional scope for the callback to be called from
  7836. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7837. * @returns the new observer created for the callback
  7838. */
  7839. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7840. if (mask === void 0) { mask = -1; }
  7841. if (insertFirst === void 0) { insertFirst = false; }
  7842. if (scope === void 0) { scope = null; }
  7843. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7844. if (!callback) {
  7845. return null;
  7846. }
  7847. var observer = new Observer(callback, mask, scope);
  7848. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7849. if (insertFirst) {
  7850. this._observers.unshift(observer);
  7851. }
  7852. else {
  7853. this._observers.push(observer);
  7854. }
  7855. if (this._onObserverAdded) {
  7856. this._onObserverAdded(observer);
  7857. }
  7858. return observer;
  7859. };
  7860. /**
  7861. * Remove an Observer from the Observable object
  7862. * @param observer the instance of the Observer to remove
  7863. * @returns false if it doesn't belong to this Observable
  7864. */
  7865. Observable.prototype.remove = function (observer) {
  7866. if (!observer) {
  7867. return false;
  7868. }
  7869. var index = this._observers.indexOf(observer);
  7870. if (index !== -1) {
  7871. this._observers.splice(index, 1);
  7872. return true;
  7873. }
  7874. return false;
  7875. };
  7876. /**
  7877. * Remove a callback from the Observable object
  7878. * @param callback the callback to remove
  7879. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7880. * @returns false if it doesn't belong to this Observable
  7881. */
  7882. Observable.prototype.removeCallback = function (callback, scope) {
  7883. for (var index = 0; index < this._observers.length; index++) {
  7884. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7885. this._observers.splice(index, 1);
  7886. return true;
  7887. }
  7888. }
  7889. return false;
  7890. };
  7891. Observable.prototype._deferUnregister = function (observer) {
  7892. var _this = this;
  7893. observer.unregisterOnNextCall = false;
  7894. observer._willBeUnregistered = true;
  7895. BABYLON.Tools.SetImmediate(function () {
  7896. _this.remove(observer);
  7897. });
  7898. };
  7899. /**
  7900. * Notify all Observers by calling their respective callback with the given data
  7901. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7902. * @param eventData defines the data to send to all observers
  7903. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7904. * @param target defines the original target of the state
  7905. * @param currentTarget defines the current target of the state
  7906. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7907. */
  7908. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7909. if (mask === void 0) { mask = -1; }
  7910. if (!this._observers.length) {
  7911. return true;
  7912. }
  7913. var state = this._eventState;
  7914. state.mask = mask;
  7915. state.target = target;
  7916. state.currentTarget = currentTarget;
  7917. state.skipNextObservers = false;
  7918. state.lastReturnValue = eventData;
  7919. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7920. var obs = _a[_i];
  7921. if (obs._willBeUnregistered) {
  7922. continue;
  7923. }
  7924. if (obs.mask & mask) {
  7925. if (obs.scope) {
  7926. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7927. }
  7928. else {
  7929. state.lastReturnValue = obs.callback(eventData, state);
  7930. }
  7931. if (obs.unregisterOnNextCall) {
  7932. this._deferUnregister(obs);
  7933. }
  7934. }
  7935. if (state.skipNextObservers) {
  7936. return false;
  7937. }
  7938. }
  7939. return true;
  7940. };
  7941. /**
  7942. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7943. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7944. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7945. * and it is crucial that all callbacks will be executed.
  7946. * The order of the callbacks is kept, callbacks are not executed parallel.
  7947. *
  7948. * @param eventData The data to be sent to each callback
  7949. * @param mask is used to filter observers defaults to -1
  7950. * @param target defines the callback target (see EventState)
  7951. * @param currentTarget defines he current object in the bubbling phase
  7952. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7953. */
  7954. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7955. var _this = this;
  7956. if (mask === void 0) { mask = -1; }
  7957. // create an empty promise
  7958. var p = Promise.resolve(eventData);
  7959. // no observers? return this promise.
  7960. if (!this._observers.length) {
  7961. return p;
  7962. }
  7963. var state = this._eventState;
  7964. state.mask = mask;
  7965. state.target = target;
  7966. state.currentTarget = currentTarget;
  7967. state.skipNextObservers = false;
  7968. // execute one callback after another (not using Promise.all, the order is important)
  7969. this._observers.forEach(function (obs) {
  7970. if (state.skipNextObservers) {
  7971. return;
  7972. }
  7973. if (obs._willBeUnregistered) {
  7974. return;
  7975. }
  7976. if (obs.mask & mask) {
  7977. if (obs.scope) {
  7978. p = p.then(function (lastReturnedValue) {
  7979. state.lastReturnValue = lastReturnedValue;
  7980. return obs.callback.apply(obs.scope, [eventData, state]);
  7981. });
  7982. }
  7983. else {
  7984. p = p.then(function (lastReturnedValue) {
  7985. state.lastReturnValue = lastReturnedValue;
  7986. return obs.callback(eventData, state);
  7987. });
  7988. }
  7989. if (obs.unregisterOnNextCall) {
  7990. _this._deferUnregister(obs);
  7991. }
  7992. }
  7993. });
  7994. // return the eventData
  7995. return p.then(function () { return eventData; });
  7996. };
  7997. /**
  7998. * Notify a specific observer
  7999. * @param observer defines the observer to notify
  8000. * @param eventData defines the data to be sent to each callback
  8001. * @param mask is used to filter observers defaults to -1
  8002. */
  8003. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8004. if (mask === void 0) { mask = -1; }
  8005. var state = this._eventState;
  8006. state.mask = mask;
  8007. state.skipNextObservers = false;
  8008. observer.callback(eventData, state);
  8009. };
  8010. /**
  8011. * Gets a boolean indicating if the observable has at least one observer
  8012. * @returns true is the Observable has at least one Observer registered
  8013. */
  8014. Observable.prototype.hasObservers = function () {
  8015. return this._observers.length > 0;
  8016. };
  8017. /**
  8018. * Clear the list of observers
  8019. */
  8020. Observable.prototype.clear = function () {
  8021. this._observers = new Array();
  8022. this._onObserverAdded = null;
  8023. };
  8024. /**
  8025. * Clone the current observable
  8026. * @returns a new observable
  8027. */
  8028. Observable.prototype.clone = function () {
  8029. var result = new Observable();
  8030. result._observers = this._observers.slice(0);
  8031. return result;
  8032. };
  8033. /**
  8034. * Does this observable handles observer registered with a given mask
  8035. * @param mask defines the mask to be tested
  8036. * @return whether or not one observer registered with the given mask is handeled
  8037. **/
  8038. Observable.prototype.hasSpecificMask = function (mask) {
  8039. if (mask === void 0) { mask = -1; }
  8040. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8041. var obs = _a[_i];
  8042. if (obs.mask & mask || obs.mask === mask) {
  8043. return true;
  8044. }
  8045. }
  8046. return false;
  8047. };
  8048. return Observable;
  8049. }());
  8050. BABYLON.Observable = Observable;
  8051. })(BABYLON || (BABYLON = {}));
  8052. //# sourceMappingURL=babylon.observable.js.map
  8053. "use strict";
  8054. var BABYLON;
  8055. (function (BABYLON) {
  8056. var SmartArray = /** @class */ (function () {
  8057. function SmartArray(capacity) {
  8058. this.length = 0;
  8059. this.data = new Array(capacity);
  8060. this._id = SmartArray._GlobalId++;
  8061. }
  8062. SmartArray.prototype.push = function (value) {
  8063. this.data[this.length++] = value;
  8064. if (this.length > this.data.length) {
  8065. this.data.length *= 2;
  8066. }
  8067. };
  8068. SmartArray.prototype.forEach = function (func) {
  8069. for (var index = 0; index < this.length; index++) {
  8070. func(this.data[index]);
  8071. }
  8072. };
  8073. SmartArray.prototype.sort = function (compareFn) {
  8074. this.data.sort(compareFn);
  8075. };
  8076. SmartArray.prototype.reset = function () {
  8077. this.length = 0;
  8078. };
  8079. SmartArray.prototype.dispose = function () {
  8080. this.reset();
  8081. if (this.data) {
  8082. this.data.length = 0;
  8083. this.data = [];
  8084. }
  8085. };
  8086. SmartArray.prototype.concat = function (array) {
  8087. if (array.length === 0) {
  8088. return;
  8089. }
  8090. if (this.length + array.length > this.data.length) {
  8091. this.data.length = (this.length + array.length) * 2;
  8092. }
  8093. for (var index = 0; index < array.length; index++) {
  8094. this.data[this.length++] = (array.data || array)[index];
  8095. }
  8096. };
  8097. SmartArray.prototype.indexOf = function (value) {
  8098. var position = this.data.indexOf(value);
  8099. if (position >= this.length) {
  8100. return -1;
  8101. }
  8102. return position;
  8103. };
  8104. SmartArray.prototype.contains = function (value) {
  8105. return this.data.indexOf(value) !== -1;
  8106. };
  8107. // Statics
  8108. SmartArray._GlobalId = 0;
  8109. return SmartArray;
  8110. }());
  8111. BABYLON.SmartArray = SmartArray;
  8112. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8113. __extends(SmartArrayNoDuplicate, _super);
  8114. function SmartArrayNoDuplicate() {
  8115. var _this = _super !== null && _super.apply(this, arguments) || this;
  8116. _this._duplicateId = 0;
  8117. return _this;
  8118. }
  8119. SmartArrayNoDuplicate.prototype.push = function (value) {
  8120. _super.prototype.push.call(this, value);
  8121. if (!value.__smartArrayFlags) {
  8122. value.__smartArrayFlags = {};
  8123. }
  8124. value.__smartArrayFlags[this._id] = this._duplicateId;
  8125. };
  8126. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8127. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8128. return false;
  8129. }
  8130. this.push(value);
  8131. return true;
  8132. };
  8133. SmartArrayNoDuplicate.prototype.reset = function () {
  8134. _super.prototype.reset.call(this);
  8135. this._duplicateId++;
  8136. };
  8137. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8138. if (array.length === 0) {
  8139. return;
  8140. }
  8141. if (this.length + array.length > this.data.length) {
  8142. this.data.length = (this.length + array.length) * 2;
  8143. }
  8144. for (var index = 0; index < array.length; index++) {
  8145. var item = (array.data || array)[index];
  8146. this.pushNoDuplicate(item);
  8147. }
  8148. };
  8149. return SmartArrayNoDuplicate;
  8150. }(SmartArray));
  8151. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8152. })(BABYLON || (BABYLON = {}));
  8153. //# sourceMappingURL=babylon.smartArray.js.map
  8154. "use strict";
  8155. var BABYLON;
  8156. (function (BABYLON) {
  8157. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8158. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8159. var LoadFileError = /** @class */ (function (_super) {
  8160. __extends(LoadFileError, _super);
  8161. function LoadFileError(message, request) {
  8162. var _this = _super.call(this, message) || this;
  8163. _this.request = request;
  8164. _this.name = "LoadFileError";
  8165. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8166. return _this;
  8167. }
  8168. // Polyfill for Object.setPrototypeOf if necessary.
  8169. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8170. return LoadFileError;
  8171. }(Error));
  8172. BABYLON.LoadFileError = LoadFileError;
  8173. var RetryStrategy = /** @class */ (function () {
  8174. function RetryStrategy() {
  8175. }
  8176. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8177. if (maxRetries === void 0) { maxRetries = 3; }
  8178. if (baseInterval === void 0) { baseInterval = 500; }
  8179. return function (url, request, retryIndex) {
  8180. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8181. return -1;
  8182. }
  8183. return Math.pow(2, retryIndex) * baseInterval;
  8184. };
  8185. };
  8186. return RetryStrategy;
  8187. }());
  8188. BABYLON.RetryStrategy = RetryStrategy;
  8189. // Screenshots
  8190. var screenshotCanvas;
  8191. var cloneValue = function (source, destinationObject) {
  8192. if (!source)
  8193. return null;
  8194. if (source instanceof BABYLON.Mesh) {
  8195. return null;
  8196. }
  8197. if (source instanceof BABYLON.SubMesh) {
  8198. return source.clone(destinationObject);
  8199. }
  8200. else if (source.clone) {
  8201. return source.clone();
  8202. }
  8203. return null;
  8204. };
  8205. var Tools = /** @class */ (function () {
  8206. function Tools() {
  8207. }
  8208. /**
  8209. * Interpolates between a and b via alpha
  8210. * @param a The lower value (returned when alpha = 0)
  8211. * @param b The upper value (returned when alpha = 1)
  8212. * @param alpha The interpolation-factor
  8213. * @return The mixed value
  8214. */
  8215. Tools.Mix = function (a, b, alpha) {
  8216. return a * (1 - alpha) + b * alpha;
  8217. };
  8218. Tools.Instantiate = function (className) {
  8219. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8220. return Tools.RegisteredExternalClasses[className];
  8221. }
  8222. var arr = className.split(".");
  8223. var fn = (window || this);
  8224. for (var i = 0, len = arr.length; i < len; i++) {
  8225. fn = fn[arr[i]];
  8226. }
  8227. if (typeof fn !== "function") {
  8228. return null;
  8229. }
  8230. return fn;
  8231. };
  8232. /**
  8233. * Provides a slice function that will work even on IE
  8234. * @param data defines the array to slice
  8235. * @param start defines the start of the data (optional)
  8236. * @param end defines the end of the data (optional)
  8237. * @returns the new sliced array
  8238. */
  8239. Tools.Slice = function (data, start, end) {
  8240. if (data.slice) {
  8241. return data.slice(start, end);
  8242. }
  8243. return Array.prototype.slice.call(data, start, end);
  8244. };
  8245. Tools.SetImmediate = function (action) {
  8246. if (window.setImmediate) {
  8247. window.setImmediate(action);
  8248. }
  8249. else {
  8250. setTimeout(action, 1);
  8251. }
  8252. };
  8253. Tools.IsExponentOfTwo = function (value) {
  8254. var count = 1;
  8255. do {
  8256. count *= 2;
  8257. } while (count < value);
  8258. return count === value;
  8259. };
  8260. /**
  8261. * Find the next highest power of two.
  8262. * @param x Number to start search from.
  8263. * @return Next highest power of two.
  8264. */
  8265. Tools.CeilingPOT = function (x) {
  8266. x--;
  8267. x |= x >> 1;
  8268. x |= x >> 2;
  8269. x |= x >> 4;
  8270. x |= x >> 8;
  8271. x |= x >> 16;
  8272. x++;
  8273. return x;
  8274. };
  8275. /**
  8276. * Find the next lowest power of two.
  8277. * @param x Number to start search from.
  8278. * @return Next lowest power of two.
  8279. */
  8280. Tools.FloorPOT = function (x) {
  8281. x = x | (x >> 1);
  8282. x = x | (x >> 2);
  8283. x = x | (x >> 4);
  8284. x = x | (x >> 8);
  8285. x = x | (x >> 16);
  8286. return x - (x >> 1);
  8287. };
  8288. /**
  8289. * Find the nearest power of two.
  8290. * @param x Number to start search from.
  8291. * @return Next nearest power of two.
  8292. */
  8293. Tools.NearestPOT = function (x) {
  8294. var c = Tools.CeilingPOT(x);
  8295. var f = Tools.FloorPOT(x);
  8296. return (c - x) > (x - f) ? f : c;
  8297. };
  8298. Tools.GetExponentOfTwo = function (value, max, mode) {
  8299. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8300. var pot;
  8301. switch (mode) {
  8302. case BABYLON.Engine.SCALEMODE_FLOOR:
  8303. pot = Tools.FloorPOT(value);
  8304. break;
  8305. case BABYLON.Engine.SCALEMODE_NEAREST:
  8306. pot = Tools.NearestPOT(value);
  8307. break;
  8308. case BABYLON.Engine.SCALEMODE_CEILING:
  8309. default:
  8310. pot = Tools.CeilingPOT(value);
  8311. break;
  8312. }
  8313. return Math.min(pot, max);
  8314. };
  8315. Tools.GetFilename = function (path) {
  8316. var index = path.lastIndexOf("/");
  8317. if (index < 0)
  8318. return path;
  8319. return path.substring(index + 1);
  8320. };
  8321. /**
  8322. * Extracts the "folder" part of a path (everything before the filename).
  8323. * @param uri The URI to extract the info from
  8324. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8325. * @returns The "folder" part of the path
  8326. */
  8327. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8328. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8329. var index = uri.lastIndexOf("/");
  8330. if (index < 0) {
  8331. if (returnUnchangedIfNoSlash) {
  8332. return uri;
  8333. }
  8334. return "";
  8335. }
  8336. return uri.substring(0, index + 1);
  8337. };
  8338. Tools.GetDOMTextContent = function (element) {
  8339. var result = "";
  8340. var child = element.firstChild;
  8341. while (child) {
  8342. if (child.nodeType === 3) {
  8343. result += child.textContent;
  8344. }
  8345. child = child.nextSibling;
  8346. }
  8347. return result;
  8348. };
  8349. Tools.ToDegrees = function (angle) {
  8350. return angle * 180 / Math.PI;
  8351. };
  8352. Tools.ToRadians = function (angle) {
  8353. return angle * Math.PI / 180;
  8354. };
  8355. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8356. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8357. var output = "";
  8358. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8359. var i = 0;
  8360. var bytes = new Uint8Array(buffer);
  8361. while (i < bytes.length) {
  8362. chr1 = bytes[i++];
  8363. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8364. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8365. enc1 = chr1 >> 2;
  8366. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8367. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8368. enc4 = chr3 & 63;
  8369. if (isNaN(chr2)) {
  8370. enc3 = enc4 = 64;
  8371. }
  8372. else if (isNaN(chr3)) {
  8373. enc4 = 64;
  8374. }
  8375. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8376. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8377. }
  8378. return "data:image/png;base64," + output;
  8379. };
  8380. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8381. if (bias === void 0) { bias = null; }
  8382. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8383. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8384. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8385. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8386. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8387. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8388. }
  8389. if (bias) {
  8390. minimum.x -= minimum.x * bias.x + bias.y;
  8391. minimum.y -= minimum.y * bias.x + bias.y;
  8392. minimum.z -= minimum.z * bias.x + bias.y;
  8393. maximum.x += maximum.x * bias.x + bias.y;
  8394. maximum.y += maximum.y * bias.x + bias.y;
  8395. maximum.z += maximum.z * bias.x + bias.y;
  8396. }
  8397. return {
  8398. minimum: minimum,
  8399. maximum: maximum
  8400. };
  8401. };
  8402. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8403. if (bias === void 0) { bias = null; }
  8404. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8405. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8406. if (!stride) {
  8407. stride = 3;
  8408. }
  8409. for (var index = start; index < start + count; index++) {
  8410. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8411. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8412. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8413. }
  8414. if (bias) {
  8415. minimum.x -= minimum.x * bias.x + bias.y;
  8416. minimum.y -= minimum.y * bias.x + bias.y;
  8417. minimum.z -= minimum.z * bias.x + bias.y;
  8418. maximum.x += maximum.x * bias.x + bias.y;
  8419. maximum.y += maximum.y * bias.x + bias.y;
  8420. maximum.z += maximum.z * bias.x + bias.y;
  8421. }
  8422. return {
  8423. minimum: minimum,
  8424. maximum: maximum
  8425. };
  8426. };
  8427. Tools.Vector2ArrayFeeder = function (array) {
  8428. return function (index) {
  8429. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8430. var length = isFloatArray ? array.length / 2 : array.length;
  8431. if (index >= length) {
  8432. return null;
  8433. }
  8434. if (isFloatArray) {
  8435. var fa = array;
  8436. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8437. }
  8438. var a = array;
  8439. return a[index];
  8440. };
  8441. };
  8442. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8443. if (bias === void 0) { bias = null; }
  8444. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8445. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8446. var i = 0;
  8447. var cur = feeder(i++);
  8448. while (cur) {
  8449. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8450. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8451. cur = feeder(i++);
  8452. }
  8453. if (bias) {
  8454. minimum.x -= minimum.x * bias.x + bias.y;
  8455. minimum.y -= minimum.y * bias.x + bias.y;
  8456. maximum.x += maximum.x * bias.x + bias.y;
  8457. maximum.y += maximum.y * bias.x + bias.y;
  8458. }
  8459. return {
  8460. minimum: minimum,
  8461. maximum: maximum
  8462. };
  8463. };
  8464. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8465. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8466. return null;
  8467. return Array.isArray(obj) ? obj : [obj];
  8468. };
  8469. // Misc.
  8470. Tools.GetPointerPrefix = function () {
  8471. var eventPrefix = "pointer";
  8472. // Check if pointer events are supported
  8473. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8474. eventPrefix = "mouse";
  8475. }
  8476. return eventPrefix;
  8477. };
  8478. /**
  8479. * @param func - the function to be called
  8480. * @param requester - the object that will request the next frame. Falls back to window.
  8481. */
  8482. Tools.QueueNewFrame = function (func, requester) {
  8483. if (!Tools.IsWindowObjectExist()) {
  8484. return setTimeout(func, 16);
  8485. }
  8486. if (!requester) {
  8487. requester = window;
  8488. }
  8489. if (requester.requestAnimationFrame) {
  8490. return requester.requestAnimationFrame(func);
  8491. }
  8492. else if (requester.msRequestAnimationFrame) {
  8493. return requester.msRequestAnimationFrame(func);
  8494. }
  8495. else if (requester.webkitRequestAnimationFrame) {
  8496. return requester.webkitRequestAnimationFrame(func);
  8497. }
  8498. else if (requester.mozRequestAnimationFrame) {
  8499. return requester.mozRequestAnimationFrame(func);
  8500. }
  8501. else if (requester.oRequestAnimationFrame) {
  8502. return requester.oRequestAnimationFrame(func);
  8503. }
  8504. else {
  8505. return window.setTimeout(func, 16);
  8506. }
  8507. };
  8508. Tools.RequestFullscreen = function (element) {
  8509. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8510. if (!requestFunction)
  8511. return;
  8512. requestFunction.call(element);
  8513. };
  8514. Tools.ExitFullscreen = function () {
  8515. if (document.exitFullscreen) {
  8516. document.exitFullscreen();
  8517. }
  8518. else if (document.mozCancelFullScreen) {
  8519. document.mozCancelFullScreen();
  8520. }
  8521. else if (document.webkitCancelFullScreen) {
  8522. document.webkitCancelFullScreen();
  8523. }
  8524. else if (document.msCancelFullScreen) {
  8525. document.msCancelFullScreen();
  8526. }
  8527. };
  8528. Tools.SetCorsBehavior = function (url, element) {
  8529. if (url && url.indexOf("data:") === 0) {
  8530. return;
  8531. }
  8532. if (Tools.CorsBehavior) {
  8533. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8534. element.crossOrigin = Tools.CorsBehavior;
  8535. }
  8536. else {
  8537. var result = Tools.CorsBehavior(url);
  8538. if (result) {
  8539. element.crossOrigin = result;
  8540. }
  8541. }
  8542. }
  8543. };
  8544. // External files
  8545. Tools.CleanUrl = function (url) {
  8546. url = url.replace(/#/mg, "%23");
  8547. return url;
  8548. };
  8549. Tools.LoadImage = function (url, onLoad, onError, database) {
  8550. if (url instanceof ArrayBuffer) {
  8551. url = Tools.EncodeArrayBufferTobase64(url);
  8552. }
  8553. url = Tools.CleanUrl(url);
  8554. url = Tools.PreprocessUrl(url);
  8555. var img = new Image();
  8556. Tools.SetCorsBehavior(url, img);
  8557. var loadHandler = function () {
  8558. img.removeEventListener("load", loadHandler);
  8559. img.removeEventListener("error", errorHandler);
  8560. onLoad(img);
  8561. };
  8562. var errorHandler = function (err) {
  8563. img.removeEventListener("load", loadHandler);
  8564. img.removeEventListener("error", errorHandler);
  8565. Tools.Error("Error while trying to load image: " + url);
  8566. if (onError) {
  8567. onError("Error while trying to load image: " + url, err);
  8568. }
  8569. };
  8570. img.addEventListener("load", loadHandler);
  8571. img.addEventListener("error", errorHandler);
  8572. var noIndexedDB = function () {
  8573. img.src = url;
  8574. };
  8575. var loadFromIndexedDB = function () {
  8576. if (database) {
  8577. database.loadImageFromDB(url, img);
  8578. }
  8579. };
  8580. //ANY database to do!
  8581. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8582. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8583. }
  8584. else {
  8585. if (url.indexOf("file:") !== -1) {
  8586. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8587. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8588. try {
  8589. var blobURL;
  8590. try {
  8591. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8592. }
  8593. catch (ex) {
  8594. // Chrome doesn't support oneTimeOnly parameter
  8595. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8596. }
  8597. img.src = blobURL;
  8598. }
  8599. catch (e) {
  8600. img.src = "";
  8601. }
  8602. return img;
  8603. }
  8604. }
  8605. noIndexedDB();
  8606. }
  8607. return img;
  8608. };
  8609. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8610. url = Tools.CleanUrl(url);
  8611. url = Tools.PreprocessUrl(url);
  8612. // If file and file input are set
  8613. if (url.indexOf("file:") !== -1) {
  8614. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8615. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8616. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8617. }
  8618. }
  8619. var loadUrl = Tools.BaseUrl + url;
  8620. var aborted = false;
  8621. var fileRequest = {
  8622. onCompleteObservable: new BABYLON.Observable(),
  8623. abort: function () { return aborted = true; },
  8624. };
  8625. var requestFile = function () {
  8626. var request = new XMLHttpRequest();
  8627. var retryHandle = null;
  8628. fileRequest.abort = function () {
  8629. aborted = true;
  8630. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8631. request.abort();
  8632. }
  8633. if (retryHandle !== null) {
  8634. clearTimeout(retryHandle);
  8635. retryHandle = null;
  8636. }
  8637. };
  8638. var retryLoop = function (retryIndex) {
  8639. request.open('GET', loadUrl, true);
  8640. if (useArrayBuffer) {
  8641. request.responseType = "arraybuffer";
  8642. }
  8643. if (onProgress) {
  8644. request.addEventListener("progress", onProgress);
  8645. }
  8646. var onLoadEnd = function () {
  8647. request.removeEventListener("loadend", onLoadEnd);
  8648. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8649. fileRequest.onCompleteObservable.clear();
  8650. };
  8651. request.addEventListener("loadend", onLoadEnd);
  8652. var onReadyStateChange = function () {
  8653. if (aborted) {
  8654. return;
  8655. }
  8656. // In case of undefined state in some browsers.
  8657. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8658. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8659. request.removeEventListener("readystatechange", onReadyStateChange);
  8660. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8661. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8662. return;
  8663. }
  8664. var retryStrategy = Tools.DefaultRetryStrategy;
  8665. if (retryStrategy) {
  8666. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8667. if (waitTime !== -1) {
  8668. // Prevent the request from completing for retry.
  8669. request.removeEventListener("loadend", onLoadEnd);
  8670. request = new XMLHttpRequest();
  8671. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8672. return;
  8673. }
  8674. }
  8675. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8676. if (onError) {
  8677. onError(request, e);
  8678. }
  8679. else {
  8680. throw e;
  8681. }
  8682. }
  8683. };
  8684. request.addEventListener("readystatechange", onReadyStateChange);
  8685. request.send();
  8686. };
  8687. retryLoop(0);
  8688. };
  8689. // Caching all files
  8690. if (database && database.enableSceneOffline) {
  8691. var noIndexedDB_1 = function () {
  8692. if (!aborted) {
  8693. requestFile();
  8694. }
  8695. };
  8696. var loadFromIndexedDB = function () {
  8697. // TODO: database needs to support aborting and should return a IFileRequest
  8698. if (aborted) {
  8699. return;
  8700. }
  8701. if (database) {
  8702. database.loadFileFromDB(url, function (data) {
  8703. if (!aborted) {
  8704. onSuccess(data);
  8705. }
  8706. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8707. }, onProgress ? function (event) {
  8708. if (!aborted) {
  8709. onProgress(event);
  8710. }
  8711. } : undefined, noIndexedDB_1, useArrayBuffer);
  8712. }
  8713. };
  8714. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8715. }
  8716. else {
  8717. requestFile();
  8718. }
  8719. return fileRequest;
  8720. };
  8721. /**
  8722. * Load a script (identified by an url). When the url returns, the
  8723. * content of this file is added into a new script element, attached to the DOM (body element)
  8724. */
  8725. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8726. var head = document.getElementsByTagName('head')[0];
  8727. var script = document.createElement('script');
  8728. script.type = 'text/javascript';
  8729. script.src = scriptUrl;
  8730. script.onload = function () {
  8731. if (onSuccess) {
  8732. onSuccess();
  8733. }
  8734. };
  8735. script.onerror = function (e) {
  8736. if (onError) {
  8737. onError("Unable to load script '" + scriptUrl + "'", e);
  8738. }
  8739. };
  8740. head.appendChild(script);
  8741. };
  8742. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8743. var reader = new FileReader();
  8744. var request = {
  8745. onCompleteObservable: new BABYLON.Observable(),
  8746. abort: function () { return reader.abort(); },
  8747. };
  8748. reader.onloadend = function (e) {
  8749. request.onCompleteObservable.notifyObservers(request);
  8750. };
  8751. reader.onload = function (e) {
  8752. //target doesn't have result from ts 1.3
  8753. callback(e.target['result']);
  8754. };
  8755. reader.onprogress = progressCallback;
  8756. reader.readAsDataURL(fileToLoad);
  8757. return request;
  8758. };
  8759. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8760. var reader = new FileReader();
  8761. var request = {
  8762. onCompleteObservable: new BABYLON.Observable(),
  8763. abort: function () { return reader.abort(); },
  8764. };
  8765. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8766. reader.onerror = function (e) {
  8767. Tools.Log("Error while reading file: " + fileToLoad.name);
  8768. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8769. };
  8770. reader.onload = function (e) {
  8771. //target doesn't have result from ts 1.3
  8772. callback(e.target['result']);
  8773. };
  8774. if (progressCallBack) {
  8775. reader.onprogress = progressCallBack;
  8776. }
  8777. if (!useArrayBuffer) {
  8778. // Asynchronous read
  8779. reader.readAsText(fileToLoad);
  8780. }
  8781. else {
  8782. reader.readAsArrayBuffer(fileToLoad);
  8783. }
  8784. return request;
  8785. };
  8786. //returns a downloadable url to a file content.
  8787. Tools.FileAsURL = function (content) {
  8788. var fileBlob = new Blob([content]);
  8789. var url = window.URL || window.webkitURL;
  8790. var link = url.createObjectURL(fileBlob);
  8791. return link;
  8792. };
  8793. // Misc.
  8794. Tools.Format = function (value, decimals) {
  8795. if (decimals === void 0) { decimals = 2; }
  8796. return value.toFixed(decimals);
  8797. };
  8798. Tools.CheckExtends = function (v, min, max) {
  8799. if (v.x < min.x)
  8800. min.x = v.x;
  8801. if (v.y < min.y)
  8802. min.y = v.y;
  8803. if (v.z < min.z)
  8804. min.z = v.z;
  8805. if (v.x > max.x)
  8806. max.x = v.x;
  8807. if (v.y > max.y)
  8808. max.y = v.y;
  8809. if (v.z > max.z)
  8810. max.z = v.z;
  8811. };
  8812. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8813. for (var prop in source) {
  8814. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8815. continue;
  8816. }
  8817. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8818. continue;
  8819. }
  8820. var sourceValue = source[prop];
  8821. var typeOfSourceValue = typeof sourceValue;
  8822. if (typeOfSourceValue === "function") {
  8823. continue;
  8824. }
  8825. try {
  8826. if (typeOfSourceValue === "object") {
  8827. if (sourceValue instanceof Array) {
  8828. destination[prop] = [];
  8829. if (sourceValue.length > 0) {
  8830. if (typeof sourceValue[0] == "object") {
  8831. for (var index = 0; index < sourceValue.length; index++) {
  8832. var clonedValue = cloneValue(sourceValue[index], destination);
  8833. if (destination[prop].indexOf(clonedValue) === -1) {
  8834. destination[prop].push(clonedValue);
  8835. }
  8836. }
  8837. }
  8838. else {
  8839. destination[prop] = sourceValue.slice(0);
  8840. }
  8841. }
  8842. }
  8843. else {
  8844. destination[prop] = cloneValue(sourceValue, destination);
  8845. }
  8846. }
  8847. else {
  8848. destination[prop] = sourceValue;
  8849. }
  8850. }
  8851. catch (e) {
  8852. // Just ignore error (it could be because of a read-only property)
  8853. }
  8854. }
  8855. };
  8856. Tools.IsEmpty = function (obj) {
  8857. for (var i in obj) {
  8858. if (obj.hasOwnProperty(i)) {
  8859. return false;
  8860. }
  8861. }
  8862. return true;
  8863. };
  8864. Tools.RegisterTopRootEvents = function (events) {
  8865. for (var index = 0; index < events.length; index++) {
  8866. var event = events[index];
  8867. window.addEventListener(event.name, event.handler, false);
  8868. try {
  8869. if (window.parent) {
  8870. window.parent.addEventListener(event.name, event.handler, false);
  8871. }
  8872. }
  8873. catch (e) {
  8874. // Silently fails...
  8875. }
  8876. }
  8877. };
  8878. Tools.UnregisterTopRootEvents = function (events) {
  8879. for (var index = 0; index < events.length; index++) {
  8880. var event = events[index];
  8881. window.removeEventListener(event.name, event.handler);
  8882. try {
  8883. if (window.parent) {
  8884. window.parent.removeEventListener(event.name, event.handler);
  8885. }
  8886. }
  8887. catch (e) {
  8888. // Silently fails...
  8889. }
  8890. }
  8891. };
  8892. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8893. if (mimeType === void 0) { mimeType = "image/png"; }
  8894. // Read the contents of the framebuffer
  8895. var numberOfChannelsByLine = width * 4;
  8896. var halfHeight = height / 2;
  8897. //Reading datas from WebGL
  8898. var data = engine.readPixels(0, 0, width, height);
  8899. //To flip image on Y axis.
  8900. for (var i = 0; i < halfHeight; i++) {
  8901. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8902. var currentCell = j + i * numberOfChannelsByLine;
  8903. var targetLine = height - i - 1;
  8904. var targetCell = j + targetLine * numberOfChannelsByLine;
  8905. var temp = data[currentCell];
  8906. data[currentCell] = data[targetCell];
  8907. data[targetCell] = temp;
  8908. }
  8909. }
  8910. // Create a 2D canvas to store the result
  8911. if (!screenshotCanvas) {
  8912. screenshotCanvas = document.createElement('canvas');
  8913. }
  8914. screenshotCanvas.width = width;
  8915. screenshotCanvas.height = height;
  8916. var context = screenshotCanvas.getContext('2d');
  8917. if (context) {
  8918. // Copy the pixels to a 2D canvas
  8919. var imageData = context.createImageData(width, height);
  8920. var castData = (imageData.data);
  8921. castData.set(data);
  8922. context.putImageData(imageData, 0, 0);
  8923. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8924. }
  8925. };
  8926. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8927. if (mimeType === void 0) { mimeType = "image/png"; }
  8928. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8929. if (successCallback) {
  8930. successCallback(base64Image);
  8931. }
  8932. else {
  8933. // We need HTMLCanvasElement.toBlob for HD screenshots
  8934. if (!screenshotCanvas.toBlob) {
  8935. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8936. screenshotCanvas.toBlob = function (callback, type, quality) {
  8937. var _this = this;
  8938. setTimeout(function () {
  8939. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8940. for (var i = 0; i < len; i++) {
  8941. arr[i] = binStr.charCodeAt(i);
  8942. }
  8943. callback(new Blob([arr], { type: type || 'image/png' }));
  8944. });
  8945. };
  8946. }
  8947. screenshotCanvas.toBlob(function (blob) {
  8948. var url = URL.createObjectURL(blob);
  8949. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8950. if (("download" in document.createElement("a"))) {
  8951. var a = window.document.createElement("a");
  8952. a.href = url;
  8953. if (fileName) {
  8954. a.setAttribute("download", fileName);
  8955. }
  8956. else {
  8957. var date = new Date();
  8958. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8959. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8960. }
  8961. window.document.body.appendChild(a);
  8962. a.addEventListener("click", function () {
  8963. if (a.parentElement) {
  8964. a.parentElement.removeChild(a);
  8965. }
  8966. });
  8967. a.click();
  8968. }
  8969. else {
  8970. var newWindow = window.open("");
  8971. if (!newWindow)
  8972. return;
  8973. var img = newWindow.document.createElement("img");
  8974. img.onload = function () {
  8975. // no longer need to read the blob so it's revoked
  8976. URL.revokeObjectURL(url);
  8977. };
  8978. img.src = url;
  8979. newWindow.document.body.appendChild(img);
  8980. }
  8981. });
  8982. }
  8983. };
  8984. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8985. if (mimeType === void 0) { mimeType = "image/png"; }
  8986. var width;
  8987. var height;
  8988. // If a precision value is specified
  8989. if (size.precision) {
  8990. width = Math.round(engine.getRenderWidth() * size.precision);
  8991. height = Math.round(width / engine.getAspectRatio(camera));
  8992. }
  8993. else if (size.width && size.height) {
  8994. width = size.width;
  8995. height = size.height;
  8996. }
  8997. else if (size.width && !size.height) {
  8998. width = size.width;
  8999. height = Math.round(width / engine.getAspectRatio(camera));
  9000. }
  9001. else if (size.height && !size.width) {
  9002. height = size.height;
  9003. width = Math.round(height * engine.getAspectRatio(camera));
  9004. }
  9005. else if (!isNaN(size)) {
  9006. height = size;
  9007. width = size;
  9008. }
  9009. else {
  9010. Tools.Error("Invalid 'size' parameter !");
  9011. return;
  9012. }
  9013. if (!screenshotCanvas) {
  9014. screenshotCanvas = document.createElement('canvas');
  9015. }
  9016. screenshotCanvas.width = width;
  9017. screenshotCanvas.height = height;
  9018. var renderContext = screenshotCanvas.getContext("2d");
  9019. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9020. var newWidth = width;
  9021. var newHeight = newWidth / ratio;
  9022. if (newHeight > height) {
  9023. newHeight = height;
  9024. newWidth = newHeight * ratio;
  9025. }
  9026. var offsetX = Math.max(0, width - newWidth) / 2;
  9027. var offsetY = Math.max(0, height - newHeight) / 2;
  9028. var renderingCanvas = engine.getRenderingCanvas();
  9029. if (renderContext && renderingCanvas) {
  9030. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9031. }
  9032. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9033. };
  9034. /**
  9035. * Generates an image screenshot from the specified camera.
  9036. *
  9037. * @param engine The engine to use for rendering
  9038. * @param camera The camera to use for rendering
  9039. * @param size This parameter can be set to a single number or to an object with the
  9040. * following (optional) properties: precision, width, height. If a single number is passed,
  9041. * it will be used for both width and height. If an object is passed, the screenshot size
  9042. * will be derived from the parameters. The precision property is a multiplier allowing
  9043. * rendering at a higher or lower resolution.
  9044. * @param successCallback The callback receives a single parameter which contains the
  9045. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9046. * src parameter of an <img> to display it.
  9047. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9048. * Check your browser for supported MIME types.
  9049. * @param samples Texture samples (default: 1)
  9050. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9051. * @param fileName A name for for the downloaded file.
  9052. * @constructor
  9053. */
  9054. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9055. if (mimeType === void 0) { mimeType = "image/png"; }
  9056. if (samples === void 0) { samples = 1; }
  9057. if (antialiasing === void 0) { antialiasing = false; }
  9058. var width;
  9059. var height;
  9060. //If a precision value is specified
  9061. if (size.precision) {
  9062. width = Math.round(engine.getRenderWidth() * size.precision);
  9063. height = Math.round(width / engine.getAspectRatio(camera));
  9064. size = { width: width, height: height };
  9065. }
  9066. else if (size.width && size.height) {
  9067. width = size.width;
  9068. height = size.height;
  9069. }
  9070. else if (size.width && !size.height) {
  9071. width = size.width;
  9072. height = Math.round(width / engine.getAspectRatio(camera));
  9073. size = { width: width, height: height };
  9074. }
  9075. else if (size.height && !size.width) {
  9076. height = size.height;
  9077. width = Math.round(height * engine.getAspectRatio(camera));
  9078. size = { width: width, height: height };
  9079. }
  9080. else if (!isNaN(size)) {
  9081. height = size;
  9082. width = size;
  9083. }
  9084. else {
  9085. Tools.Error("Invalid 'size' parameter !");
  9086. return;
  9087. }
  9088. var scene = camera.getScene();
  9089. var previousCamera = null;
  9090. if (scene.activeCamera !== camera) {
  9091. previousCamera = scene.activeCamera;
  9092. scene.activeCamera = camera;
  9093. }
  9094. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9095. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9096. texture.renderList = null;
  9097. texture.samples = samples;
  9098. if (antialiasing) {
  9099. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9100. }
  9101. texture.onAfterRenderObservable.add(function () {
  9102. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9103. });
  9104. scene.incrementRenderId();
  9105. scene.resetCachedMaterial();
  9106. texture.render(true);
  9107. texture.dispose();
  9108. if (previousCamera) {
  9109. scene.activeCamera = previousCamera;
  9110. }
  9111. camera.getProjectionMatrix(true); // Force cache refresh;
  9112. };
  9113. // XHR response validator for local file scenario
  9114. Tools.ValidateXHRData = function (xhr, dataType) {
  9115. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9116. if (dataType === void 0) { dataType = 7; }
  9117. try {
  9118. if (dataType & 1) {
  9119. if (xhr.responseText && xhr.responseText.length > 0) {
  9120. return true;
  9121. }
  9122. else if (dataType === 1) {
  9123. return false;
  9124. }
  9125. }
  9126. if (dataType & 2) {
  9127. // Check header width and height since there is no "TGA" magic number
  9128. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9129. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9130. return true;
  9131. }
  9132. else if (dataType === 2) {
  9133. return false;
  9134. }
  9135. }
  9136. if (dataType & 4) {
  9137. // Check for the "DDS" magic number
  9138. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9139. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9140. return true;
  9141. }
  9142. else {
  9143. return false;
  9144. }
  9145. }
  9146. }
  9147. catch (e) {
  9148. // Global protection
  9149. }
  9150. return false;
  9151. };
  9152. /**
  9153. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9154. * Be aware Math.random() could cause collisions, but:
  9155. * "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"
  9156. */
  9157. Tools.RandomId = function () {
  9158. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9159. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9160. return v.toString(16);
  9161. });
  9162. };
  9163. /**
  9164. * Test if the given uri is a base64 string.
  9165. * @param uri The uri to test
  9166. * @return True if the uri is a base64 string or false otherwise.
  9167. */
  9168. Tools.IsBase64 = function (uri) {
  9169. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9170. };
  9171. /**
  9172. * Decode the given base64 uri.
  9173. * @param uri The uri to decode
  9174. * @return The decoded base64 data.
  9175. */
  9176. Tools.DecodeBase64 = function (uri) {
  9177. var decodedString = atob(uri.split(",")[1]);
  9178. var bufferLength = decodedString.length;
  9179. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9180. for (var i = 0; i < bufferLength; i++) {
  9181. bufferView[i] = decodedString.charCodeAt(i);
  9182. }
  9183. return bufferView.buffer;
  9184. };
  9185. Object.defineProperty(Tools, "NoneLogLevel", {
  9186. get: function () {
  9187. return Tools._NoneLogLevel;
  9188. },
  9189. enumerable: true,
  9190. configurable: true
  9191. });
  9192. Object.defineProperty(Tools, "MessageLogLevel", {
  9193. get: function () {
  9194. return Tools._MessageLogLevel;
  9195. },
  9196. enumerable: true,
  9197. configurable: true
  9198. });
  9199. Object.defineProperty(Tools, "WarningLogLevel", {
  9200. get: function () {
  9201. return Tools._WarningLogLevel;
  9202. },
  9203. enumerable: true,
  9204. configurable: true
  9205. });
  9206. Object.defineProperty(Tools, "ErrorLogLevel", {
  9207. get: function () {
  9208. return Tools._ErrorLogLevel;
  9209. },
  9210. enumerable: true,
  9211. configurable: true
  9212. });
  9213. Object.defineProperty(Tools, "AllLogLevel", {
  9214. get: function () {
  9215. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9216. },
  9217. enumerable: true,
  9218. configurable: true
  9219. });
  9220. Tools._AddLogEntry = function (entry) {
  9221. Tools._LogCache = entry + Tools._LogCache;
  9222. if (Tools.OnNewCacheEntry) {
  9223. Tools.OnNewCacheEntry(entry);
  9224. }
  9225. };
  9226. Tools._FormatMessage = function (message) {
  9227. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9228. var date = new Date();
  9229. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9230. };
  9231. Tools._LogDisabled = function (message) {
  9232. // nothing to do
  9233. };
  9234. Tools._LogEnabled = function (message) {
  9235. var formattedMessage = Tools._FormatMessage(message);
  9236. console.log("BJS - " + formattedMessage);
  9237. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9238. Tools._AddLogEntry(entry);
  9239. };
  9240. Tools._WarnDisabled = function (message) {
  9241. // nothing to do
  9242. };
  9243. Tools._WarnEnabled = function (message) {
  9244. var formattedMessage = Tools._FormatMessage(message);
  9245. console.warn("BJS - " + formattedMessage);
  9246. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9247. Tools._AddLogEntry(entry);
  9248. };
  9249. Tools._ErrorDisabled = function (message) {
  9250. // nothing to do
  9251. };
  9252. Tools._ErrorEnabled = function (message) {
  9253. Tools.errorsCount++;
  9254. var formattedMessage = Tools._FormatMessage(message);
  9255. console.error("BJS - " + formattedMessage);
  9256. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9257. Tools._AddLogEntry(entry);
  9258. };
  9259. Object.defineProperty(Tools, "LogCache", {
  9260. get: function () {
  9261. return Tools._LogCache;
  9262. },
  9263. enumerable: true,
  9264. configurable: true
  9265. });
  9266. Tools.ClearLogCache = function () {
  9267. Tools._LogCache = "";
  9268. Tools.errorsCount = 0;
  9269. };
  9270. Object.defineProperty(Tools, "LogLevels", {
  9271. set: function (level) {
  9272. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9273. Tools.Log = Tools._LogEnabled;
  9274. }
  9275. else {
  9276. Tools.Log = Tools._LogDisabled;
  9277. }
  9278. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9279. Tools.Warn = Tools._WarnEnabled;
  9280. }
  9281. else {
  9282. Tools.Warn = Tools._WarnDisabled;
  9283. }
  9284. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9285. Tools.Error = Tools._ErrorEnabled;
  9286. }
  9287. else {
  9288. Tools.Error = Tools._ErrorDisabled;
  9289. }
  9290. },
  9291. enumerable: true,
  9292. configurable: true
  9293. });
  9294. Tools.IsWindowObjectExist = function () {
  9295. return (typeof window) !== "undefined";
  9296. };
  9297. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9298. get: function () {
  9299. return Tools._PerformanceNoneLogLevel;
  9300. },
  9301. enumerable: true,
  9302. configurable: true
  9303. });
  9304. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9305. get: function () {
  9306. return Tools._PerformanceUserMarkLogLevel;
  9307. },
  9308. enumerable: true,
  9309. configurable: true
  9310. });
  9311. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9312. get: function () {
  9313. return Tools._PerformanceConsoleLogLevel;
  9314. },
  9315. enumerable: true,
  9316. configurable: true
  9317. });
  9318. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9319. set: function (level) {
  9320. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9321. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9322. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9323. return;
  9324. }
  9325. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9326. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9327. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9328. return;
  9329. }
  9330. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9331. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9332. },
  9333. enumerable: true,
  9334. configurable: true
  9335. });
  9336. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9337. };
  9338. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9339. };
  9340. Tools._StartUserMark = function (counterName, condition) {
  9341. if (condition === void 0) { condition = true; }
  9342. if (!Tools._performance) {
  9343. if (!Tools.IsWindowObjectExist()) {
  9344. return;
  9345. }
  9346. Tools._performance = window.performance;
  9347. }
  9348. if (!condition || !Tools._performance.mark) {
  9349. return;
  9350. }
  9351. Tools._performance.mark(counterName + "-Begin");
  9352. };
  9353. Tools._EndUserMark = function (counterName, condition) {
  9354. if (condition === void 0) { condition = true; }
  9355. if (!condition || !Tools._performance.mark) {
  9356. return;
  9357. }
  9358. Tools._performance.mark(counterName + "-End");
  9359. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9360. };
  9361. Tools._StartPerformanceConsole = function (counterName, condition) {
  9362. if (condition === void 0) { condition = true; }
  9363. if (!condition) {
  9364. return;
  9365. }
  9366. Tools._StartUserMark(counterName, condition);
  9367. if (console.time) {
  9368. console.time(counterName);
  9369. }
  9370. };
  9371. Tools._EndPerformanceConsole = function (counterName, condition) {
  9372. if (condition === void 0) { condition = true; }
  9373. if (!condition) {
  9374. return;
  9375. }
  9376. Tools._EndUserMark(counterName, condition);
  9377. if (console.time) {
  9378. console.timeEnd(counterName);
  9379. }
  9380. };
  9381. Object.defineProperty(Tools, "Now", {
  9382. get: function () {
  9383. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9384. return window.performance.now();
  9385. }
  9386. return new Date().getTime();
  9387. },
  9388. enumerable: true,
  9389. configurable: true
  9390. });
  9391. /**
  9392. * This method will return the name of the class used to create the instance of the given object.
  9393. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9394. * @param object the object to get the class name from
  9395. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9396. */
  9397. Tools.GetClassName = function (object, isType) {
  9398. if (isType === void 0) { isType = false; }
  9399. var name = null;
  9400. if (!isType && object.getClassName) {
  9401. name = object.getClassName();
  9402. }
  9403. else {
  9404. if (object instanceof Object) {
  9405. var classObj = isType ? object : Object.getPrototypeOf(object);
  9406. name = classObj.constructor["__bjsclassName__"];
  9407. }
  9408. if (!name) {
  9409. name = typeof object;
  9410. }
  9411. }
  9412. return name;
  9413. };
  9414. Tools.First = function (array, predicate) {
  9415. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9416. var el = array_1[_i];
  9417. if (predicate(el)) {
  9418. return el;
  9419. }
  9420. }
  9421. return null;
  9422. };
  9423. /**
  9424. * This method will return the name of the full name of the class, including its owning module (if any).
  9425. * 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).
  9426. * @param object the object to get the class name from
  9427. * @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.
  9428. */
  9429. Tools.getFullClassName = function (object, isType) {
  9430. if (isType === void 0) { isType = false; }
  9431. var className = null;
  9432. var moduleName = null;
  9433. if (!isType && object.getClassName) {
  9434. className = object.getClassName();
  9435. }
  9436. else {
  9437. if (object instanceof Object) {
  9438. var classObj = isType ? object : Object.getPrototypeOf(object);
  9439. className = classObj.constructor["__bjsclassName__"];
  9440. moduleName = classObj.constructor["__bjsmoduleName__"];
  9441. }
  9442. if (!className) {
  9443. className = typeof object;
  9444. }
  9445. }
  9446. if (!className) {
  9447. return null;
  9448. }
  9449. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9450. };
  9451. /**
  9452. * 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.
  9453. * @param array
  9454. */
  9455. Tools.arrayOrStringFeeder = function (array) {
  9456. return function (index) {
  9457. if (index >= array.length) {
  9458. return null;
  9459. }
  9460. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9461. if (val && val.getHashCode) {
  9462. val = val.getHashCode();
  9463. }
  9464. if (typeof val === "string") {
  9465. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9466. }
  9467. return val;
  9468. };
  9469. };
  9470. /**
  9471. * Compute the hashCode of a stream of number
  9472. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9473. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9474. * @return the hash code computed
  9475. */
  9476. Tools.hashCodeFromStream = function (feeder) {
  9477. // Based from here: http://stackoverflow.com/a/7616484/802124
  9478. var hash = 0;
  9479. var index = 0;
  9480. var chr = feeder(index++);
  9481. while (chr != null) {
  9482. hash = ((hash << 5) - hash) + chr;
  9483. hash |= 0; // Convert to 32bit integer
  9484. chr = feeder(index++);
  9485. }
  9486. return hash;
  9487. };
  9488. /**
  9489. * Returns a promise that resolves after the given amount of time.
  9490. * @param delay Number of milliseconds to delay
  9491. * @returns Promise that resolves after the given amount of time
  9492. */
  9493. Tools.DelayAsync = function (delay) {
  9494. return new Promise(function (resolve) {
  9495. setTimeout(function () {
  9496. resolve();
  9497. }, delay);
  9498. });
  9499. };
  9500. Tools.BaseUrl = "";
  9501. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9502. /**
  9503. * Default behaviour for cors in the application.
  9504. * It can be a string if the expected behavior is identical in the entire app.
  9505. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9506. */
  9507. Tools.CorsBehavior = "anonymous";
  9508. Tools.UseFallbackTexture = true;
  9509. /**
  9510. * Use this object to register external classes like custom textures or material
  9511. * to allow the laoders to instantiate them
  9512. */
  9513. Tools.RegisteredExternalClasses = {};
  9514. // Used in case of a texture loading problem
  9515. 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";
  9516. Tools.PreprocessUrl = function (url) {
  9517. return url;
  9518. };
  9519. // Logs
  9520. Tools._NoneLogLevel = 0;
  9521. Tools._MessageLogLevel = 1;
  9522. Tools._WarningLogLevel = 2;
  9523. Tools._ErrorLogLevel = 4;
  9524. Tools._LogCache = "";
  9525. Tools.errorsCount = 0;
  9526. Tools.Log = Tools._LogEnabled;
  9527. Tools.Warn = Tools._WarnEnabled;
  9528. Tools.Error = Tools._ErrorEnabled;
  9529. // Performances
  9530. Tools._PerformanceNoneLogLevel = 0;
  9531. Tools._PerformanceUserMarkLogLevel = 1;
  9532. Tools._PerformanceConsoleLogLevel = 2;
  9533. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9534. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9535. return Tools;
  9536. }());
  9537. BABYLON.Tools = Tools;
  9538. /**
  9539. * This class is used to track a performance counter which is number based.
  9540. * The user has access to many properties which give statistics of different nature
  9541. *
  9542. * The implementer can track two kinds of Performance Counter: time and count
  9543. * 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.
  9544. * 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.
  9545. */
  9546. var PerfCounter = /** @class */ (function () {
  9547. function PerfCounter() {
  9548. this._startMonitoringTime = 0;
  9549. this._min = 0;
  9550. this._max = 0;
  9551. this._average = 0;
  9552. this._lastSecAverage = 0;
  9553. this._current = 0;
  9554. this._totalValueCount = 0;
  9555. this._totalAccumulated = 0;
  9556. this._lastSecAccumulated = 0;
  9557. this._lastSecTime = 0;
  9558. this._lastSecValueCount = 0;
  9559. }
  9560. Object.defineProperty(PerfCounter.prototype, "min", {
  9561. /**
  9562. * Returns the smallest value ever
  9563. */
  9564. get: function () {
  9565. return this._min;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(PerfCounter.prototype, "max", {
  9571. /**
  9572. * Returns the biggest value ever
  9573. */
  9574. get: function () {
  9575. return this._max;
  9576. },
  9577. enumerable: true,
  9578. configurable: true
  9579. });
  9580. Object.defineProperty(PerfCounter.prototype, "average", {
  9581. /**
  9582. * Returns the average value since the performance counter is running
  9583. */
  9584. get: function () {
  9585. return this._average;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9591. /**
  9592. * Returns the average value of the last second the counter was monitored
  9593. */
  9594. get: function () {
  9595. return this._lastSecAverage;
  9596. },
  9597. enumerable: true,
  9598. configurable: true
  9599. });
  9600. Object.defineProperty(PerfCounter.prototype, "current", {
  9601. /**
  9602. * Returns the current value
  9603. */
  9604. get: function () {
  9605. return this._current;
  9606. },
  9607. enumerable: true,
  9608. configurable: true
  9609. });
  9610. Object.defineProperty(PerfCounter.prototype, "total", {
  9611. get: function () {
  9612. return this._totalAccumulated;
  9613. },
  9614. enumerable: true,
  9615. configurable: true
  9616. });
  9617. Object.defineProperty(PerfCounter.prototype, "count", {
  9618. get: function () {
  9619. return this._totalValueCount;
  9620. },
  9621. enumerable: true,
  9622. configurable: true
  9623. });
  9624. /**
  9625. * Call this method to start monitoring a new frame.
  9626. * 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.
  9627. */
  9628. PerfCounter.prototype.fetchNewFrame = function () {
  9629. this._totalValueCount++;
  9630. this._current = 0;
  9631. this._lastSecValueCount++;
  9632. };
  9633. /**
  9634. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9635. * @param newCount the count value to add to the monitored count
  9636. * @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.
  9637. */
  9638. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9639. if (!PerfCounter.Enabled) {
  9640. return;
  9641. }
  9642. this._current += newCount;
  9643. if (fetchResult) {
  9644. this._fetchResult();
  9645. }
  9646. };
  9647. /**
  9648. * Start monitoring this performance counter
  9649. */
  9650. PerfCounter.prototype.beginMonitoring = function () {
  9651. if (!PerfCounter.Enabled) {
  9652. return;
  9653. }
  9654. this._startMonitoringTime = Tools.Now;
  9655. };
  9656. /**
  9657. * Compute the time lapsed since the previous beginMonitoring() call.
  9658. * @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
  9659. */
  9660. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9661. if (newFrame === void 0) { newFrame = true; }
  9662. if (!PerfCounter.Enabled) {
  9663. return;
  9664. }
  9665. if (newFrame) {
  9666. this.fetchNewFrame();
  9667. }
  9668. var currentTime = Tools.Now;
  9669. this._current = currentTime - this._startMonitoringTime;
  9670. if (newFrame) {
  9671. this._fetchResult();
  9672. }
  9673. };
  9674. PerfCounter.prototype._fetchResult = function () {
  9675. this._totalAccumulated += this._current;
  9676. this._lastSecAccumulated += this._current;
  9677. // Min/Max update
  9678. this._min = Math.min(this._min, this._current);
  9679. this._max = Math.max(this._max, this._current);
  9680. this._average = this._totalAccumulated / this._totalValueCount;
  9681. // Reset last sec?
  9682. var now = Tools.Now;
  9683. if ((now - this._lastSecTime) > 1000) {
  9684. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9685. this._lastSecTime = now;
  9686. this._lastSecAccumulated = 0;
  9687. this._lastSecValueCount = 0;
  9688. }
  9689. };
  9690. PerfCounter.Enabled = true;
  9691. return PerfCounter;
  9692. }());
  9693. BABYLON.PerfCounter = PerfCounter;
  9694. /**
  9695. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9696. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9697. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9698. * @param name The name of the class, case should be preserved
  9699. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9700. */
  9701. function className(name, module) {
  9702. return function (target) {
  9703. target["__bjsclassName__"] = name;
  9704. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9705. };
  9706. }
  9707. BABYLON.className = className;
  9708. /**
  9709. * An implementation of a loop for asynchronous functions.
  9710. */
  9711. var AsyncLoop = /** @class */ (function () {
  9712. /**
  9713. * Constroctor.
  9714. * @param iterations the number of iterations.
  9715. * @param _fn the function to run each iteration
  9716. * @param _successCallback the callback that will be called upon succesful execution
  9717. * @param offset starting offset.
  9718. */
  9719. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9720. if (offset === void 0) { offset = 0; }
  9721. this.iterations = iterations;
  9722. this._fn = _fn;
  9723. this._successCallback = _successCallback;
  9724. this.index = offset - 1;
  9725. this._done = false;
  9726. }
  9727. /**
  9728. * Execute the next iteration. Must be called after the last iteration was finished.
  9729. */
  9730. AsyncLoop.prototype.executeNext = function () {
  9731. if (!this._done) {
  9732. if (this.index + 1 < this.iterations) {
  9733. ++this.index;
  9734. this._fn(this);
  9735. }
  9736. else {
  9737. this.breakLoop();
  9738. }
  9739. }
  9740. };
  9741. /**
  9742. * Break the loop and run the success callback.
  9743. */
  9744. AsyncLoop.prototype.breakLoop = function () {
  9745. this._done = true;
  9746. this._successCallback();
  9747. };
  9748. /**
  9749. * Helper function
  9750. */
  9751. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9752. if (offset === void 0) { offset = 0; }
  9753. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9754. loop.executeNext();
  9755. return loop;
  9756. };
  9757. /**
  9758. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9759. * @param iterations total number of iterations
  9760. * @param syncedIterations number of synchronous iterations in each async iteration.
  9761. * @param fn the function to call each iteration.
  9762. * @param callback a success call back that will be called when iterating stops.
  9763. * @param breakFunction a break condition (optional)
  9764. * @param timeout timeout settings for the setTimeout function. default - 0.
  9765. * @constructor
  9766. */
  9767. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9768. if (timeout === void 0) { timeout = 0; }
  9769. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9770. if (breakFunction && breakFunction())
  9771. loop.breakLoop();
  9772. else {
  9773. setTimeout(function () {
  9774. for (var i = 0; i < syncedIterations; ++i) {
  9775. var iteration = (loop.index * syncedIterations) + i;
  9776. if (iteration >= iterations)
  9777. break;
  9778. fn(iteration);
  9779. if (breakFunction && breakFunction()) {
  9780. loop.breakLoop();
  9781. break;
  9782. }
  9783. }
  9784. loop.executeNext();
  9785. }, timeout);
  9786. }
  9787. }, callback);
  9788. };
  9789. return AsyncLoop;
  9790. }());
  9791. BABYLON.AsyncLoop = AsyncLoop;
  9792. })(BABYLON || (BABYLON = {}));
  9793. //# sourceMappingURL=babylon.tools.js.map
  9794. "use strict";
  9795. var BABYLON;
  9796. (function (BABYLON) {
  9797. var PromiseStates;
  9798. (function (PromiseStates) {
  9799. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9800. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9801. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9802. })(PromiseStates || (PromiseStates = {}));
  9803. var FulFillmentAgregator = /** @class */ (function () {
  9804. function FulFillmentAgregator() {
  9805. this.count = 0;
  9806. this.target = 0;
  9807. this.results = [];
  9808. }
  9809. return FulFillmentAgregator;
  9810. }());
  9811. var InternalPromise = /** @class */ (function () {
  9812. function InternalPromise(resolver) {
  9813. var _this = this;
  9814. this._state = PromiseStates.Pending;
  9815. this._children = new Array();
  9816. this._rejectWasConsumed = false;
  9817. if (!resolver) {
  9818. return;
  9819. }
  9820. try {
  9821. resolver(function (value) {
  9822. _this._resolve(value);
  9823. }, function (reason) {
  9824. _this._reject(reason);
  9825. });
  9826. }
  9827. catch (e) {
  9828. this._reject(e);
  9829. }
  9830. }
  9831. InternalPromise.prototype.catch = function (onRejected) {
  9832. return this.then(undefined, onRejected);
  9833. };
  9834. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9835. var _this = this;
  9836. var newPromise = new InternalPromise();
  9837. newPromise._onFulfilled = onFulfilled;
  9838. newPromise._onRejected = onRejected;
  9839. // Composition
  9840. this._children.push(newPromise);
  9841. if (this._state !== PromiseStates.Pending) {
  9842. BABYLON.Tools.SetImmediate(function () {
  9843. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9844. var returnedValue = newPromise._resolve(_this._result);
  9845. if (returnedValue !== undefined && returnedValue !== null) {
  9846. if (returnedValue._state !== undefined) {
  9847. var returnedPromise = returnedValue;
  9848. newPromise._children.push(returnedPromise);
  9849. newPromise = returnedPromise;
  9850. }
  9851. else {
  9852. newPromise._result = returnedValue;
  9853. }
  9854. }
  9855. }
  9856. else {
  9857. newPromise._reject(_this._reason);
  9858. }
  9859. });
  9860. }
  9861. return newPromise;
  9862. };
  9863. InternalPromise.prototype._moveChildren = function (children) {
  9864. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9865. if (this._state === PromiseStates.Fulfilled) {
  9866. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9867. var child = _b[_i];
  9868. child._resolve(this._result);
  9869. }
  9870. }
  9871. else if (this._state === PromiseStates.Rejected) {
  9872. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9873. var child = _d[_c];
  9874. child._reject(this._reason);
  9875. }
  9876. }
  9877. var _a;
  9878. };
  9879. InternalPromise.prototype._resolve = function (value) {
  9880. try {
  9881. this._state = PromiseStates.Fulfilled;
  9882. var returnedValue = null;
  9883. if (this._onFulfilled) {
  9884. returnedValue = this._onFulfilled(value);
  9885. }
  9886. if (returnedValue !== undefined && returnedValue !== null) {
  9887. if (returnedValue._state !== undefined) {
  9888. // Transmit children
  9889. var returnedPromise = returnedValue;
  9890. returnedPromise._moveChildren(this._children);
  9891. value = returnedPromise._result;
  9892. }
  9893. else {
  9894. value = returnedValue;
  9895. }
  9896. }
  9897. this._result = value;
  9898. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9899. var child = _a[_i];
  9900. child._resolve(value);
  9901. }
  9902. this._children.length = 0;
  9903. delete this._onFulfilled;
  9904. delete this._onRejected;
  9905. }
  9906. catch (e) {
  9907. this._reject(e, true);
  9908. }
  9909. };
  9910. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9911. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9912. this._state = PromiseStates.Rejected;
  9913. this._reason = reason;
  9914. if (this._onRejected && !onLocalThrow) {
  9915. try {
  9916. this._onRejected(reason);
  9917. this._rejectWasConsumed = true;
  9918. }
  9919. catch (e) {
  9920. reason = e;
  9921. }
  9922. }
  9923. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9924. var child = _a[_i];
  9925. if (this._rejectWasConsumed) {
  9926. child._resolve(null);
  9927. }
  9928. else {
  9929. child._reject(reason);
  9930. }
  9931. }
  9932. this._children.length = 0;
  9933. delete this._onFulfilled;
  9934. delete this._onRejected;
  9935. };
  9936. InternalPromise.resolve = function (value) {
  9937. var newPromise = new InternalPromise();
  9938. newPromise._resolve(value);
  9939. return newPromise;
  9940. };
  9941. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9942. promise.then(function (value) {
  9943. agregator.results[index] = value;
  9944. agregator.count++;
  9945. if (agregator.count === agregator.target) {
  9946. agregator.rootPromise._resolve(agregator.results);
  9947. }
  9948. return null;
  9949. }, function (reason) {
  9950. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9951. agregator.rootPromise._reject(reason);
  9952. }
  9953. });
  9954. };
  9955. InternalPromise.all = function (promises) {
  9956. var newPromise = new InternalPromise();
  9957. var agregator = new FulFillmentAgregator();
  9958. agregator.target = promises.length;
  9959. agregator.rootPromise = newPromise;
  9960. if (promises.length) {
  9961. for (var index = 0; index < promises.length; index++) {
  9962. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9963. }
  9964. }
  9965. else {
  9966. newPromise._resolve([]);
  9967. }
  9968. return newPromise;
  9969. };
  9970. InternalPromise.race = function (promises) {
  9971. var newPromise = new InternalPromise();
  9972. if (promises.length) {
  9973. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9974. var promise = promises_1[_i];
  9975. promise.then(function (value) {
  9976. if (newPromise) {
  9977. newPromise._resolve(value);
  9978. newPromise = null;
  9979. }
  9980. return null;
  9981. }, function (reason) {
  9982. if (newPromise) {
  9983. newPromise._reject(reason);
  9984. newPromise = null;
  9985. }
  9986. });
  9987. }
  9988. }
  9989. return newPromise;
  9990. };
  9991. return InternalPromise;
  9992. }());
  9993. /**
  9994. * Helper class that provides a small promise polyfill
  9995. */
  9996. var PromisePolyfill = /** @class */ (function () {
  9997. function PromisePolyfill() {
  9998. }
  9999. /**
  10000. * Static function used to check if the polyfill is required
  10001. * If this is the case then the function will inject the polyfill to window.Promise
  10002. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10003. */
  10004. PromisePolyfill.Apply = function (force) {
  10005. if (force === void 0) { force = false; }
  10006. if (force || typeof Promise === 'undefined') {
  10007. var root = window;
  10008. root.Promise = InternalPromise;
  10009. }
  10010. };
  10011. return PromisePolyfill;
  10012. }());
  10013. BABYLON.PromisePolyfill = PromisePolyfill;
  10014. })(BABYLON || (BABYLON = {}));
  10015. //# sourceMappingURL=babylon.promise.js.map
  10016. "use strict";
  10017. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10018. var BABYLON;
  10019. (function (BABYLON) {
  10020. /**
  10021. * Helper class to push actions to a pool of workers.
  10022. */
  10023. var WorkerPool = /** @class */ (function () {
  10024. /**
  10025. * Constructor
  10026. * @param workers Array of workers to use for actions
  10027. */
  10028. function WorkerPool(workers) {
  10029. this._pendingActions = new Array();
  10030. this._workerInfos = workers.map(function (worker) { return ({
  10031. worker: worker,
  10032. active: false
  10033. }); });
  10034. }
  10035. /**
  10036. * Terminates all workers and clears any pending actions.
  10037. */
  10038. WorkerPool.prototype.dispose = function () {
  10039. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10040. var workerInfo = _a[_i];
  10041. workerInfo.worker.terminate();
  10042. }
  10043. delete this._workerInfos;
  10044. delete this._pendingActions;
  10045. };
  10046. /**
  10047. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10048. * pended until a worker has completed its action.
  10049. * @param action The action to perform. Call onComplete when the action is complete.
  10050. */
  10051. WorkerPool.prototype.push = function (action) {
  10052. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10053. var workerInfo = _a[_i];
  10054. if (!workerInfo.active) {
  10055. this._execute(workerInfo, action);
  10056. return;
  10057. }
  10058. }
  10059. this._pendingActions.push(action);
  10060. };
  10061. WorkerPool.prototype._execute = function (workerInfo, action) {
  10062. var _this = this;
  10063. workerInfo.active = true;
  10064. action(workerInfo.worker, function () {
  10065. workerInfo.active = false;
  10066. var nextAction = _this._pendingActions.shift();
  10067. if (nextAction) {
  10068. _this._execute(workerInfo, nextAction);
  10069. }
  10070. });
  10071. };
  10072. return WorkerPool;
  10073. }());
  10074. BABYLON.WorkerPool = WorkerPool;
  10075. })(BABYLON || (BABYLON = {}));
  10076. //# sourceMappingURL=babylon.workerPool.js.map
  10077. "use strict";
  10078. var BABYLON;
  10079. (function (BABYLON) {
  10080. var _AlphaState = /** @class */ (function () {
  10081. /**
  10082. * Initializes the state.
  10083. */
  10084. function _AlphaState() {
  10085. this._isAlphaBlendDirty = false;
  10086. this._isBlendFunctionParametersDirty = false;
  10087. this._isBlendEquationParametersDirty = false;
  10088. this._isBlendConstantsDirty = false;
  10089. this._alphaBlend = false;
  10090. this._blendFunctionParameters = new Array(4);
  10091. this._blendEquationParameters = new Array(2);
  10092. this._blendConstants = new Array(4);
  10093. this.reset();
  10094. }
  10095. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10096. get: function () {
  10097. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10098. },
  10099. enumerable: true,
  10100. configurable: true
  10101. });
  10102. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10103. get: function () {
  10104. return this._alphaBlend;
  10105. },
  10106. set: function (value) {
  10107. if (this._alphaBlend === value) {
  10108. return;
  10109. }
  10110. this._alphaBlend = value;
  10111. this._isAlphaBlendDirty = true;
  10112. },
  10113. enumerable: true,
  10114. configurable: true
  10115. });
  10116. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10117. if (this._blendConstants[0] === r &&
  10118. this._blendConstants[1] === g &&
  10119. this._blendConstants[2] === b &&
  10120. this._blendConstants[3] === a) {
  10121. return;
  10122. }
  10123. this._blendConstants[0] = r;
  10124. this._blendConstants[1] = g;
  10125. this._blendConstants[2] = b;
  10126. this._blendConstants[3] = a;
  10127. this._isBlendConstantsDirty = true;
  10128. };
  10129. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10130. if (this._blendFunctionParameters[0] === value0 &&
  10131. this._blendFunctionParameters[1] === value1 &&
  10132. this._blendFunctionParameters[2] === value2 &&
  10133. this._blendFunctionParameters[3] === value3) {
  10134. return;
  10135. }
  10136. this._blendFunctionParameters[0] = value0;
  10137. this._blendFunctionParameters[1] = value1;
  10138. this._blendFunctionParameters[2] = value2;
  10139. this._blendFunctionParameters[3] = value3;
  10140. this._isBlendFunctionParametersDirty = true;
  10141. };
  10142. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10143. if (this._blendEquationParameters[0] === rgb &&
  10144. this._blendEquationParameters[1] === alpha) {
  10145. return;
  10146. }
  10147. this._blendEquationParameters[0] = rgb;
  10148. this._blendEquationParameters[1] = alpha;
  10149. this._isBlendEquationParametersDirty = true;
  10150. };
  10151. _AlphaState.prototype.reset = function () {
  10152. this._alphaBlend = false;
  10153. this._blendFunctionParameters[0] = null;
  10154. this._blendFunctionParameters[1] = null;
  10155. this._blendFunctionParameters[2] = null;
  10156. this._blendFunctionParameters[3] = null;
  10157. this._blendEquationParameters[0] = null;
  10158. this._blendEquationParameters[1] = null;
  10159. this._blendConstants[0] = null;
  10160. this._blendConstants[1] = null;
  10161. this._blendConstants[2] = null;
  10162. this._blendConstants[3] = null;
  10163. this._isAlphaBlendDirty = true;
  10164. this._isBlendFunctionParametersDirty = false;
  10165. this._isBlendEquationParametersDirty = false;
  10166. this._isBlendConstantsDirty = false;
  10167. };
  10168. _AlphaState.prototype.apply = function (gl) {
  10169. if (!this.isDirty) {
  10170. return;
  10171. }
  10172. // Alpha blend
  10173. if (this._isAlphaBlendDirty) {
  10174. if (this._alphaBlend) {
  10175. gl.enable(gl.BLEND);
  10176. }
  10177. else {
  10178. gl.disable(gl.BLEND);
  10179. }
  10180. this._isAlphaBlendDirty = false;
  10181. }
  10182. // Alpha function
  10183. if (this._isBlendFunctionParametersDirty) {
  10184. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10185. this._isBlendFunctionParametersDirty = false;
  10186. }
  10187. // Alpha equation
  10188. if (this._isBlendEquationParametersDirty) {
  10189. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10190. this._isBlendEquationParametersDirty = false;
  10191. }
  10192. // Constants
  10193. if (this._isBlendConstantsDirty) {
  10194. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10195. this._isBlendConstantsDirty = false;
  10196. }
  10197. };
  10198. return _AlphaState;
  10199. }());
  10200. BABYLON._AlphaState = _AlphaState;
  10201. })(BABYLON || (BABYLON = {}));
  10202. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10203. "use strict";
  10204. var BABYLON;
  10205. (function (BABYLON) {
  10206. var _DepthCullingState = /** @class */ (function () {
  10207. /**
  10208. * Initializes the state.
  10209. */
  10210. function _DepthCullingState() {
  10211. this._isDepthTestDirty = false;
  10212. this._isDepthMaskDirty = false;
  10213. this._isDepthFuncDirty = false;
  10214. this._isCullFaceDirty = false;
  10215. this._isCullDirty = false;
  10216. this._isZOffsetDirty = false;
  10217. this._isFrontFaceDirty = false;
  10218. this.reset();
  10219. }
  10220. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10221. get: function () {
  10222. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10223. },
  10224. enumerable: true,
  10225. configurable: true
  10226. });
  10227. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10228. get: function () {
  10229. return this._zOffset;
  10230. },
  10231. set: function (value) {
  10232. if (this._zOffset === value) {
  10233. return;
  10234. }
  10235. this._zOffset = value;
  10236. this._isZOffsetDirty = true;
  10237. },
  10238. enumerable: true,
  10239. configurable: true
  10240. });
  10241. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10242. get: function () {
  10243. return this._cullFace;
  10244. },
  10245. set: function (value) {
  10246. if (this._cullFace === value) {
  10247. return;
  10248. }
  10249. this._cullFace = value;
  10250. this._isCullFaceDirty = true;
  10251. },
  10252. enumerable: true,
  10253. configurable: true
  10254. });
  10255. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10256. get: function () {
  10257. return this._cull;
  10258. },
  10259. set: function (value) {
  10260. if (this._cull === value) {
  10261. return;
  10262. }
  10263. this._cull = value;
  10264. this._isCullDirty = true;
  10265. },
  10266. enumerable: true,
  10267. configurable: true
  10268. });
  10269. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10270. get: function () {
  10271. return this._depthFunc;
  10272. },
  10273. set: function (value) {
  10274. if (this._depthFunc === value) {
  10275. return;
  10276. }
  10277. this._depthFunc = value;
  10278. this._isDepthFuncDirty = true;
  10279. },
  10280. enumerable: true,
  10281. configurable: true
  10282. });
  10283. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10284. get: function () {
  10285. return this._depthMask;
  10286. },
  10287. set: function (value) {
  10288. if (this._depthMask === value) {
  10289. return;
  10290. }
  10291. this._depthMask = value;
  10292. this._isDepthMaskDirty = true;
  10293. },
  10294. enumerable: true,
  10295. configurable: true
  10296. });
  10297. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10298. get: function () {
  10299. return this._depthTest;
  10300. },
  10301. set: function (value) {
  10302. if (this._depthTest === value) {
  10303. return;
  10304. }
  10305. this._depthTest = value;
  10306. this._isDepthTestDirty = true;
  10307. },
  10308. enumerable: true,
  10309. configurable: true
  10310. });
  10311. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10312. get: function () {
  10313. return this._frontFace;
  10314. },
  10315. set: function (value) {
  10316. if (this._frontFace === value) {
  10317. return;
  10318. }
  10319. this._frontFace = value;
  10320. this._isFrontFaceDirty = true;
  10321. },
  10322. enumerable: true,
  10323. configurable: true
  10324. });
  10325. _DepthCullingState.prototype.reset = function () {
  10326. this._depthMask = true;
  10327. this._depthTest = true;
  10328. this._depthFunc = null;
  10329. this._cullFace = null;
  10330. this._cull = null;
  10331. this._zOffset = 0;
  10332. this._frontFace = null;
  10333. this._isDepthTestDirty = true;
  10334. this._isDepthMaskDirty = true;
  10335. this._isDepthFuncDirty = false;
  10336. this._isCullFaceDirty = false;
  10337. this._isCullDirty = false;
  10338. this._isZOffsetDirty = false;
  10339. this._isFrontFaceDirty = false;
  10340. };
  10341. _DepthCullingState.prototype.apply = function (gl) {
  10342. if (!this.isDirty) {
  10343. return;
  10344. }
  10345. // Cull
  10346. if (this._isCullDirty) {
  10347. if (this.cull) {
  10348. gl.enable(gl.CULL_FACE);
  10349. }
  10350. else {
  10351. gl.disable(gl.CULL_FACE);
  10352. }
  10353. this._isCullDirty = false;
  10354. }
  10355. // Cull face
  10356. if (this._isCullFaceDirty) {
  10357. gl.cullFace(this.cullFace);
  10358. this._isCullFaceDirty = false;
  10359. }
  10360. // Depth mask
  10361. if (this._isDepthMaskDirty) {
  10362. gl.depthMask(this.depthMask);
  10363. this._isDepthMaskDirty = false;
  10364. }
  10365. // Depth test
  10366. if (this._isDepthTestDirty) {
  10367. if (this.depthTest) {
  10368. gl.enable(gl.DEPTH_TEST);
  10369. }
  10370. else {
  10371. gl.disable(gl.DEPTH_TEST);
  10372. }
  10373. this._isDepthTestDirty = false;
  10374. }
  10375. // Depth func
  10376. if (this._isDepthFuncDirty) {
  10377. gl.depthFunc(this.depthFunc);
  10378. this._isDepthFuncDirty = false;
  10379. }
  10380. // zOffset
  10381. if (this._isZOffsetDirty) {
  10382. if (this.zOffset) {
  10383. gl.enable(gl.POLYGON_OFFSET_FILL);
  10384. gl.polygonOffset(this.zOffset, 0);
  10385. }
  10386. else {
  10387. gl.disable(gl.POLYGON_OFFSET_FILL);
  10388. }
  10389. this._isZOffsetDirty = false;
  10390. }
  10391. // Front face
  10392. if (this._isFrontFaceDirty) {
  10393. gl.frontFace(this.frontFace);
  10394. this._isFrontFaceDirty = false;
  10395. }
  10396. };
  10397. return _DepthCullingState;
  10398. }());
  10399. BABYLON._DepthCullingState = _DepthCullingState;
  10400. })(BABYLON || (BABYLON = {}));
  10401. //# sourceMappingURL=babylon.depthCullingState.js.map
  10402. "use strict";
  10403. var BABYLON;
  10404. (function (BABYLON) {
  10405. var _StencilState = /** @class */ (function () {
  10406. function _StencilState() {
  10407. this._isStencilTestDirty = false;
  10408. this._isStencilMaskDirty = false;
  10409. this._isStencilFuncDirty = false;
  10410. this._isStencilOpDirty = false;
  10411. this.reset();
  10412. }
  10413. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10414. get: function () {
  10415. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10416. },
  10417. enumerable: true,
  10418. configurable: true
  10419. });
  10420. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10421. get: function () {
  10422. return this._stencilFunc;
  10423. },
  10424. set: function (value) {
  10425. if (this._stencilFunc === value) {
  10426. return;
  10427. }
  10428. this._stencilFunc = value;
  10429. this._isStencilFuncDirty = true;
  10430. },
  10431. enumerable: true,
  10432. configurable: true
  10433. });
  10434. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10435. get: function () {
  10436. return this._stencilFuncRef;
  10437. },
  10438. set: function (value) {
  10439. if (this._stencilFuncRef === value) {
  10440. return;
  10441. }
  10442. this._stencilFuncRef = value;
  10443. this._isStencilFuncDirty = true;
  10444. },
  10445. enumerable: true,
  10446. configurable: true
  10447. });
  10448. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10449. get: function () {
  10450. return this._stencilFuncMask;
  10451. },
  10452. set: function (value) {
  10453. if (this._stencilFuncMask === value) {
  10454. return;
  10455. }
  10456. this._stencilFuncMask = value;
  10457. this._isStencilFuncDirty = true;
  10458. },
  10459. enumerable: true,
  10460. configurable: true
  10461. });
  10462. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10463. get: function () {
  10464. return this._stencilOpStencilFail;
  10465. },
  10466. set: function (value) {
  10467. if (this._stencilOpStencilFail === value) {
  10468. return;
  10469. }
  10470. this._stencilOpStencilFail = value;
  10471. this._isStencilOpDirty = true;
  10472. },
  10473. enumerable: true,
  10474. configurable: true
  10475. });
  10476. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10477. get: function () {
  10478. return this._stencilOpDepthFail;
  10479. },
  10480. set: function (value) {
  10481. if (this._stencilOpDepthFail === value) {
  10482. return;
  10483. }
  10484. this._stencilOpDepthFail = value;
  10485. this._isStencilOpDirty = true;
  10486. },
  10487. enumerable: true,
  10488. configurable: true
  10489. });
  10490. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10491. get: function () {
  10492. return this._stencilOpStencilDepthPass;
  10493. },
  10494. set: function (value) {
  10495. if (this._stencilOpStencilDepthPass === value) {
  10496. return;
  10497. }
  10498. this._stencilOpStencilDepthPass = value;
  10499. this._isStencilOpDirty = true;
  10500. },
  10501. enumerable: true,
  10502. configurable: true
  10503. });
  10504. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10505. get: function () {
  10506. return this._stencilMask;
  10507. },
  10508. set: function (value) {
  10509. if (this._stencilMask === value) {
  10510. return;
  10511. }
  10512. this._stencilMask = value;
  10513. this._isStencilMaskDirty = true;
  10514. },
  10515. enumerable: true,
  10516. configurable: true
  10517. });
  10518. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10519. get: function () {
  10520. return this._stencilTest;
  10521. },
  10522. set: function (value) {
  10523. if (this._stencilTest === value) {
  10524. return;
  10525. }
  10526. this._stencilTest = value;
  10527. this._isStencilTestDirty = true;
  10528. },
  10529. enumerable: true,
  10530. configurable: true
  10531. });
  10532. _StencilState.prototype.reset = function () {
  10533. this._stencilTest = false;
  10534. this._stencilMask = 0xFF;
  10535. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10536. this._stencilFuncRef = 1;
  10537. this._stencilFuncMask = 0xFF;
  10538. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10539. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10540. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10541. this._isStencilTestDirty = true;
  10542. this._isStencilMaskDirty = true;
  10543. this._isStencilFuncDirty = true;
  10544. this._isStencilOpDirty = true;
  10545. };
  10546. _StencilState.prototype.apply = function (gl) {
  10547. if (!this.isDirty) {
  10548. return;
  10549. }
  10550. // Stencil test
  10551. if (this._isStencilTestDirty) {
  10552. if (this.stencilTest) {
  10553. gl.enable(gl.STENCIL_TEST);
  10554. }
  10555. else {
  10556. gl.disable(gl.STENCIL_TEST);
  10557. }
  10558. this._isStencilTestDirty = false;
  10559. }
  10560. // Stencil mask
  10561. if (this._isStencilMaskDirty) {
  10562. gl.stencilMask(this.stencilMask);
  10563. this._isStencilMaskDirty = false;
  10564. }
  10565. // Stencil func
  10566. if (this._isStencilFuncDirty) {
  10567. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10568. this._isStencilFuncDirty = false;
  10569. }
  10570. // Stencil op
  10571. if (this._isStencilOpDirty) {
  10572. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10573. this._isStencilOpDirty = false;
  10574. }
  10575. };
  10576. return _StencilState;
  10577. }());
  10578. BABYLON._StencilState = _StencilState;
  10579. })(BABYLON || (BABYLON = {}));
  10580. //# sourceMappingURL=babylon.stencilState.js.map
  10581. "use strict";
  10582. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10583. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10584. s = arguments[i];
  10585. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10586. t[p] = s[p];
  10587. }
  10588. return t;
  10589. };
  10590. var BABYLON;
  10591. (function (BABYLON) {
  10592. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10593. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10594. };
  10595. var compileRawShader = function (gl, source, type) {
  10596. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10597. gl.shaderSource(shader, source);
  10598. gl.compileShader(shader);
  10599. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10600. var log = gl.getShaderInfoLog(shader);
  10601. if (log) {
  10602. throw new Error(log);
  10603. }
  10604. }
  10605. if (!shader) {
  10606. throw new Error("Something went wrong while compile the shader.");
  10607. }
  10608. return shader;
  10609. };
  10610. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10611. var magFilter = gl.NEAREST;
  10612. var minFilter = gl.NEAREST;
  10613. switch (samplingMode) {
  10614. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10615. magFilter = gl.LINEAR;
  10616. if (generateMipMaps) {
  10617. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10618. }
  10619. else {
  10620. minFilter = gl.LINEAR;
  10621. }
  10622. break;
  10623. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10624. magFilter = gl.LINEAR;
  10625. if (generateMipMaps) {
  10626. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10627. }
  10628. else {
  10629. minFilter = gl.LINEAR;
  10630. }
  10631. break;
  10632. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10633. magFilter = gl.NEAREST;
  10634. if (generateMipMaps) {
  10635. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10636. }
  10637. else {
  10638. minFilter = gl.NEAREST;
  10639. }
  10640. break;
  10641. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10642. magFilter = gl.NEAREST;
  10643. if (generateMipMaps) {
  10644. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10645. }
  10646. else {
  10647. minFilter = gl.NEAREST;
  10648. }
  10649. break;
  10650. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10651. magFilter = gl.NEAREST;
  10652. if (generateMipMaps) {
  10653. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10654. }
  10655. else {
  10656. minFilter = gl.LINEAR;
  10657. }
  10658. break;
  10659. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10660. magFilter = gl.NEAREST;
  10661. if (generateMipMaps) {
  10662. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10663. }
  10664. else {
  10665. minFilter = gl.LINEAR;
  10666. }
  10667. break;
  10668. case BABYLON.Texture.NEAREST_LINEAR:
  10669. magFilter = gl.NEAREST;
  10670. minFilter = gl.LINEAR;
  10671. break;
  10672. case BABYLON.Texture.NEAREST_NEAREST:
  10673. magFilter = gl.NEAREST;
  10674. minFilter = gl.NEAREST;
  10675. break;
  10676. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10677. magFilter = gl.LINEAR;
  10678. if (generateMipMaps) {
  10679. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10680. }
  10681. else {
  10682. minFilter = gl.NEAREST;
  10683. }
  10684. break;
  10685. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10686. magFilter = gl.LINEAR;
  10687. if (generateMipMaps) {
  10688. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10689. }
  10690. else {
  10691. minFilter = gl.NEAREST;
  10692. }
  10693. break;
  10694. case BABYLON.Texture.LINEAR_LINEAR:
  10695. magFilter = gl.LINEAR;
  10696. minFilter = gl.LINEAR;
  10697. break;
  10698. case BABYLON.Texture.LINEAR_NEAREST:
  10699. magFilter = gl.LINEAR;
  10700. minFilter = gl.NEAREST;
  10701. break;
  10702. }
  10703. return {
  10704. min: minFilter,
  10705. mag: magFilter
  10706. };
  10707. };
  10708. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10709. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10710. var img;
  10711. var onload = function () {
  10712. loadedImages[index] = img;
  10713. loadedImages._internalCount++;
  10714. if (scene) {
  10715. scene._removePendingData(img);
  10716. }
  10717. if (loadedImages._internalCount === 6) {
  10718. onfinish(loadedImages);
  10719. }
  10720. };
  10721. var onerror = function (message, exception) {
  10722. if (scene) {
  10723. scene._removePendingData(img);
  10724. }
  10725. if (onErrorCallBack) {
  10726. onErrorCallBack(message, exception);
  10727. }
  10728. };
  10729. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10730. if (scene) {
  10731. scene._addPendingData(img);
  10732. }
  10733. };
  10734. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10735. if (onError === void 0) { onError = null; }
  10736. var loadedImages = [];
  10737. loadedImages._internalCount = 0;
  10738. for (var index = 0; index < 6; index++) {
  10739. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10740. }
  10741. };
  10742. var BufferPointer = /** @class */ (function () {
  10743. function BufferPointer() {
  10744. }
  10745. return BufferPointer;
  10746. }());
  10747. /**
  10748. * Interface for attribute information associated with buffer instanciation
  10749. */
  10750. var InstancingAttributeInfo = /** @class */ (function () {
  10751. function InstancingAttributeInfo() {
  10752. }
  10753. return InstancingAttributeInfo;
  10754. }());
  10755. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10756. /**
  10757. * Define options used to create a render target texture
  10758. */
  10759. var RenderTargetCreationOptions = /** @class */ (function () {
  10760. function RenderTargetCreationOptions() {
  10761. }
  10762. return RenderTargetCreationOptions;
  10763. }());
  10764. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10765. /**
  10766. * Define options used to create a depth texture
  10767. */
  10768. var DepthTextureCreationOptions = /** @class */ (function () {
  10769. function DepthTextureCreationOptions() {
  10770. }
  10771. return DepthTextureCreationOptions;
  10772. }());
  10773. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10774. /**
  10775. * Class used to describe the capabilities of the engine relatively to the current browser
  10776. */
  10777. var EngineCapabilities = /** @class */ (function () {
  10778. function EngineCapabilities() {
  10779. }
  10780. return EngineCapabilities;
  10781. }());
  10782. BABYLON.EngineCapabilities = EngineCapabilities;
  10783. /**
  10784. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10785. */
  10786. var Engine = /** @class */ (function () {
  10787. /**
  10788. * Creates a new engine
  10789. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10790. * @param antialias defines enable antialiasing (default: false)
  10791. * @param options defines further options to be sent to the getContext() function
  10792. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10793. */
  10794. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10795. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10796. var _this = this;
  10797. // Public members
  10798. /**
  10799. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10800. */
  10801. this.forcePOTTextures = false;
  10802. /**
  10803. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10804. */
  10805. this.isFullscreen = false;
  10806. /**
  10807. * Gets a boolean indicating if the pointer is currently locked
  10808. */
  10809. this.isPointerLock = false;
  10810. /**
  10811. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10812. */
  10813. this.cullBackFaces = true;
  10814. /**
  10815. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10816. */
  10817. this.renderEvenInBackground = true;
  10818. /**
  10819. * Gets or sets a boolean indicating that cache can be kept between frames
  10820. */
  10821. this.preventCacheWipeBetweenFrames = false;
  10822. /**
  10823. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10824. **/
  10825. this.enableOfflineSupport = false;
  10826. /**
  10827. * Gets the list of created scenes
  10828. */
  10829. this.scenes = new Array();
  10830. /**
  10831. * Gets the list of created postprocesses
  10832. */
  10833. this.postProcesses = new Array();
  10834. // Observables
  10835. /**
  10836. * Observable event triggered each time the rendering canvas is resized
  10837. */
  10838. this.onResizeObservable = new BABYLON.Observable();
  10839. /**
  10840. * Observable event triggered each time the canvas loses focus
  10841. */
  10842. this.onCanvasBlurObservable = new BABYLON.Observable();
  10843. /**
  10844. * Observable event triggered each time the canvas gains focus
  10845. */
  10846. this.onCanvasFocusObservable = new BABYLON.Observable();
  10847. /**
  10848. * Observable event triggered each time the canvas receives pointerout event
  10849. */
  10850. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10851. /**
  10852. * Observable event triggered before each texture is initialized
  10853. */
  10854. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10855. //WebVR
  10856. this._vrDisplay = undefined;
  10857. this._vrSupported = false;
  10858. this._vrExclusivePointerMode = false;
  10859. // Uniform buffers list
  10860. /**
  10861. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10862. */
  10863. this.disableUniformBuffers = false;
  10864. /** @ignore */
  10865. this._uniformBuffers = new Array();
  10866. // Observables
  10867. /**
  10868. * Observable raised when the engine begins a new frame
  10869. */
  10870. this.onBeginFrameObservable = new BABYLON.Observable();
  10871. /**
  10872. * Observable raised when the engine ends the current frame
  10873. */
  10874. this.onEndFrameObservable = new BABYLON.Observable();
  10875. /**
  10876. * Observable raised when the engine is about to compile a shader
  10877. */
  10878. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10879. /**
  10880. * Observable raised when the engine has jsut compiled a shader
  10881. */
  10882. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10883. this._windowIsBackground = false;
  10884. this._webGLVersion = 1.0;
  10885. /** @ignore */
  10886. this._badOS = false;
  10887. /** @ignore */
  10888. this._badDesktopOS = false;
  10889. /**
  10890. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10891. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  10892. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  10893. */
  10894. this.disableTextureBindingOptimization = false;
  10895. /**
  10896. * Observable signaled when VR display mode changes
  10897. */
  10898. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10899. /**
  10900. * Observable signaled when VR request present is complete
  10901. */
  10902. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10903. /**
  10904. * Observable signaled when VR request present starts
  10905. */
  10906. this.onVRRequestPresentStart = new BABYLON.Observable();
  10907. this._colorWrite = true;
  10908. /** @ignore */
  10909. this._drawCalls = new BABYLON.PerfCounter();
  10910. /** @ignore */
  10911. this._textureCollisions = new BABYLON.PerfCounter();
  10912. this._renderingQueueLaunched = false;
  10913. this._activeRenderLoops = new Array();
  10914. // Deterministic lockstepMaxSteps
  10915. this._deterministicLockstep = false;
  10916. this._lockstepMaxSteps = 4;
  10917. // Lost context
  10918. /**
  10919. * Observable signaled when a context lost event is raised
  10920. */
  10921. this.onContextLostObservable = new BABYLON.Observable();
  10922. /**
  10923. * Observable signaled when a context restored event is raised
  10924. */
  10925. this.onContextRestoredObservable = new BABYLON.Observable();
  10926. this._contextWasLost = false;
  10927. this._doNotHandleContextLost = false;
  10928. // FPS
  10929. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10930. this._fps = 60;
  10931. this._deltaTime = 0;
  10932. /**
  10933. * Turn this value on if you want to pause FPS computation when in background
  10934. */
  10935. this.disablePerformanceMonitorInBackground = false;
  10936. // States
  10937. /** @ignore */
  10938. this._depthCullingState = new BABYLON._DepthCullingState();
  10939. /** @ignore */
  10940. this._stencilState = new BABYLON._StencilState();
  10941. /** @ignore */
  10942. this._alphaState = new BABYLON._AlphaState();
  10943. /** @ignore */
  10944. this._alphaMode = Engine.ALPHA_DISABLE;
  10945. // Cache
  10946. this._internalTexturesCache = new Array();
  10947. /** @ignore */
  10948. this._activeChannel = 0;
  10949. this._currentTextureChannel = -1;
  10950. /** @ignore */
  10951. this._boundTexturesCache = {};
  10952. this._compiledEffects = {};
  10953. this._vertexAttribArraysEnabled = [];
  10954. this._uintIndicesCurrentlySet = false;
  10955. this._currentBoundBuffer = new Array();
  10956. this._currentBufferPointers = new Array();
  10957. this._currentInstanceLocations = new Array();
  10958. this._currentInstanceBuffers = new Array();
  10959. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10960. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10961. this._vaoRecordInProgress = false;
  10962. this._mustWipeVertexAttributes = false;
  10963. this._nextFreeTextureSlots = new Array();
  10964. this._maxSimultaneousTextures = 0;
  10965. this._activeRequests = new Array();
  10966. // Hardware supported Compressed Textures
  10967. this._texturesSupported = new Array();
  10968. this._onVRFullScreenTriggered = function () {
  10969. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10970. //get the old size before we change
  10971. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10972. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10973. //get the width and height, change the render size
  10974. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10975. _this.setHardwareScalingLevel(1);
  10976. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10977. }
  10978. else {
  10979. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10980. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10981. }
  10982. };
  10983. this._boundUniforms = {};
  10984. // Register promises
  10985. BABYLON.PromisePolyfill.Apply();
  10986. var canvas = null;
  10987. Engine.Instances.push(this);
  10988. if (!canvasOrContext) {
  10989. return;
  10990. }
  10991. options = options || {};
  10992. if (canvasOrContext.getContext) {
  10993. canvas = canvasOrContext;
  10994. this._renderingCanvas = canvas;
  10995. if (antialias != null) {
  10996. options.antialias = antialias;
  10997. }
  10998. if (options.deterministicLockstep === undefined) {
  10999. options.deterministicLockstep = false;
  11000. }
  11001. if (options.lockstepMaxSteps === undefined) {
  11002. options.lockstepMaxSteps = 4;
  11003. }
  11004. if (options.preserveDrawingBuffer === undefined) {
  11005. options.preserveDrawingBuffer = false;
  11006. }
  11007. if (options.audioEngine === undefined) {
  11008. options.audioEngine = true;
  11009. }
  11010. if (options.stencil === undefined) {
  11011. options.stencil = true;
  11012. }
  11013. this._deterministicLockstep = options.deterministicLockstep;
  11014. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11015. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11016. // Exceptions
  11017. if (navigator && navigator.userAgent) {
  11018. var ua = navigator.userAgent;
  11019. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11020. var exception = _a[_i];
  11021. var key = exception.key;
  11022. var targets = exception.targets;
  11023. if (ua.indexOf(key) > -1) {
  11024. if (exception.capture && exception.captureConstraint) {
  11025. var capture = exception.capture;
  11026. var constraint = exception.captureConstraint;
  11027. var regex = new RegExp(capture);
  11028. var matches = regex.exec(ua);
  11029. if (matches && matches.length > 0) {
  11030. var capturedValue = parseInt(matches[matches.length - 1]);
  11031. if (capturedValue >= constraint) {
  11032. continue;
  11033. }
  11034. }
  11035. }
  11036. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11037. var target = targets_1[_b];
  11038. switch (target) {
  11039. case "uniformBuffer":
  11040. this.disableUniformBuffers = true;
  11041. break;
  11042. case "textureBindingOptimization":
  11043. this.disableTextureBindingOptimization = true;
  11044. break;
  11045. }
  11046. }
  11047. }
  11048. }
  11049. }
  11050. // GL
  11051. if (!options.disableWebGL2Support) {
  11052. try {
  11053. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11054. if (this._gl) {
  11055. this._webGLVersion = 2.0;
  11056. }
  11057. }
  11058. catch (e) {
  11059. // Do nothing
  11060. }
  11061. }
  11062. if (!this._gl) {
  11063. if (!canvas) {
  11064. throw new Error("The provided canvas is null or undefined.");
  11065. }
  11066. try {
  11067. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11068. }
  11069. catch (e) {
  11070. throw new Error("WebGL not supported");
  11071. }
  11072. }
  11073. if (!this._gl) {
  11074. throw new Error("WebGL not supported");
  11075. }
  11076. this._onCanvasFocus = function () {
  11077. _this.onCanvasFocusObservable.notifyObservers(_this);
  11078. };
  11079. this._onCanvasBlur = function () {
  11080. _this.onCanvasBlurObservable.notifyObservers(_this);
  11081. };
  11082. canvas.addEventListener("focus", this._onCanvasFocus);
  11083. canvas.addEventListener("blur", this._onCanvasBlur);
  11084. this._onBlur = function () {
  11085. if (_this.disablePerformanceMonitorInBackground) {
  11086. _this._performanceMonitor.disable();
  11087. }
  11088. _this._windowIsBackground = true;
  11089. };
  11090. this._onFocus = function () {
  11091. if (_this.disablePerformanceMonitorInBackground) {
  11092. _this._performanceMonitor.enable();
  11093. }
  11094. _this._windowIsBackground = false;
  11095. };
  11096. this._onCanvasPointerOut = function (ev) {
  11097. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11098. };
  11099. window.addEventListener("blur", this._onBlur);
  11100. window.addEventListener("focus", this._onFocus);
  11101. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11102. // Context lost
  11103. if (!this._doNotHandleContextLost) {
  11104. this._onContextLost = function (evt) {
  11105. evt.preventDefault();
  11106. _this._contextWasLost = true;
  11107. BABYLON.Tools.Warn("WebGL context lost.");
  11108. _this.onContextLostObservable.notifyObservers(_this);
  11109. };
  11110. this._onContextRestored = function (evt) {
  11111. // Adding a timeout to avoid race condition at browser level
  11112. setTimeout(function () {
  11113. // Rebuild gl context
  11114. _this._initGLContext();
  11115. // Rebuild effects
  11116. _this._rebuildEffects();
  11117. // Rebuild textures
  11118. _this._rebuildInternalTextures();
  11119. // Rebuild buffers
  11120. _this._rebuildBuffers();
  11121. // Cache
  11122. _this.wipeCaches(true);
  11123. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11124. _this.onContextRestoredObservable.notifyObservers(_this);
  11125. _this._contextWasLost = false;
  11126. }, 0);
  11127. };
  11128. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11129. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11130. }
  11131. }
  11132. else {
  11133. this._gl = canvasOrContext;
  11134. this._renderingCanvas = this._gl.canvas;
  11135. if (this._gl.renderbufferStorageMultisample) {
  11136. this._webGLVersion = 2.0;
  11137. }
  11138. options.stencil = this._gl.getContextAttributes().stencil;
  11139. }
  11140. // Viewport
  11141. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11142. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11143. this.resize();
  11144. this._isStencilEnable = options.stencil ? true : false;
  11145. this._initGLContext();
  11146. if (canvas) {
  11147. // Fullscreen
  11148. this._onFullscreenChange = function () {
  11149. if (document.fullscreen !== undefined) {
  11150. _this.isFullscreen = document.fullscreen;
  11151. }
  11152. else if (document.mozFullScreen !== undefined) {
  11153. _this.isFullscreen = document.mozFullScreen;
  11154. }
  11155. else if (document.webkitIsFullScreen !== undefined) {
  11156. _this.isFullscreen = document.webkitIsFullScreen;
  11157. }
  11158. else if (document.msIsFullScreen !== undefined) {
  11159. _this.isFullscreen = document.msIsFullScreen;
  11160. }
  11161. // Pointer lock
  11162. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11163. canvas.requestPointerLock = canvas.requestPointerLock ||
  11164. canvas.msRequestPointerLock ||
  11165. canvas.mozRequestPointerLock ||
  11166. canvas.webkitRequestPointerLock;
  11167. if (canvas.requestPointerLock) {
  11168. canvas.requestPointerLock();
  11169. }
  11170. }
  11171. };
  11172. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11173. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11174. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11175. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11176. // Pointer lock
  11177. this._onPointerLockChange = function () {
  11178. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11179. document.webkitPointerLockElement === canvas ||
  11180. document.msPointerLockElement === canvas ||
  11181. document.pointerLockElement === canvas);
  11182. };
  11183. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11184. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11185. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11186. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11187. this._onVRDisplayPointerRestricted = function () {
  11188. if (canvas) {
  11189. canvas.requestPointerLock();
  11190. }
  11191. };
  11192. this._onVRDisplayPointerUnrestricted = function () {
  11193. document.exitPointerLock();
  11194. };
  11195. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11196. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11197. }
  11198. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11199. Engine.audioEngine = new BABYLON.AudioEngine();
  11200. }
  11201. // Prepare buffer pointers
  11202. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11203. this._currentBufferPointers[i] = new BufferPointer();
  11204. }
  11205. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11206. // Load WebVR Devices
  11207. if (options.autoEnableWebVR) {
  11208. this.initWebVR();
  11209. }
  11210. // Detect if we are running on a faulty buggy OS.
  11211. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11212. // Detect if we are running on a faulty buggy desktop OS.
  11213. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11214. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11215. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11216. }
  11217. Object.defineProperty(Engine, "LastCreatedEngine", {
  11218. /**
  11219. * Gets the latest created engine
  11220. */
  11221. get: function () {
  11222. if (Engine.Instances.length === 0) {
  11223. return null;
  11224. }
  11225. return Engine.Instances[Engine.Instances.length - 1];
  11226. },
  11227. enumerable: true,
  11228. configurable: true
  11229. });
  11230. Object.defineProperty(Engine, "LastCreatedScene", {
  11231. /**
  11232. * Gets the latest created scene
  11233. */
  11234. get: function () {
  11235. var lastCreatedEngine = Engine.LastCreatedEngine;
  11236. if (!lastCreatedEngine) {
  11237. return null;
  11238. }
  11239. if (lastCreatedEngine.scenes.length === 0) {
  11240. return null;
  11241. }
  11242. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11243. },
  11244. enumerable: true,
  11245. configurable: true
  11246. });
  11247. /**
  11248. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11249. * @param flag defines which part of the materials must be marked as dirty
  11250. * @param predicate defines a predicate used to filter which materials should be affected
  11251. */
  11252. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11253. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11254. var engine = Engine.Instances[engineIndex];
  11255. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11256. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11257. }
  11258. }
  11259. };
  11260. Object.defineProperty(Engine, "NEVER", {
  11261. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11262. get: function () {
  11263. return Engine._NEVER;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Object.defineProperty(Engine, "ALWAYS", {
  11269. /** 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 */
  11270. get: function () {
  11271. return Engine._ALWAYS;
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. Object.defineProperty(Engine, "LESS", {
  11277. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11278. get: function () {
  11279. return Engine._LESS;
  11280. },
  11281. enumerable: true,
  11282. configurable: true
  11283. });
  11284. Object.defineProperty(Engine, "EQUAL", {
  11285. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11286. get: function () {
  11287. return Engine._EQUAL;
  11288. },
  11289. enumerable: true,
  11290. configurable: true
  11291. });
  11292. Object.defineProperty(Engine, "LEQUAL", {
  11293. /** 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 */
  11294. get: function () {
  11295. return Engine._LEQUAL;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(Engine, "GREATER", {
  11301. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11302. get: function () {
  11303. return Engine._GREATER;
  11304. },
  11305. enumerable: true,
  11306. configurable: true
  11307. });
  11308. Object.defineProperty(Engine, "GEQUAL", {
  11309. /** 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 */
  11310. get: function () {
  11311. return Engine._GEQUAL;
  11312. },
  11313. enumerable: true,
  11314. configurable: true
  11315. });
  11316. Object.defineProperty(Engine, "NOTEQUAL", {
  11317. /** 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 */
  11318. get: function () {
  11319. return Engine._NOTEQUAL;
  11320. },
  11321. enumerable: true,
  11322. configurable: true
  11323. });
  11324. Object.defineProperty(Engine, "KEEP", {
  11325. /** Passed to stencilOperation to specify that stencil value must be kept */
  11326. get: function () {
  11327. return Engine._KEEP;
  11328. },
  11329. enumerable: true,
  11330. configurable: true
  11331. });
  11332. Object.defineProperty(Engine, "REPLACE", {
  11333. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11334. get: function () {
  11335. return Engine._REPLACE;
  11336. },
  11337. enumerable: true,
  11338. configurable: true
  11339. });
  11340. Object.defineProperty(Engine, "INCR", {
  11341. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11342. get: function () {
  11343. return Engine._INCR;
  11344. },
  11345. enumerable: true,
  11346. configurable: true
  11347. });
  11348. Object.defineProperty(Engine, "DECR", {
  11349. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11350. get: function () {
  11351. return Engine._DECR;
  11352. },
  11353. enumerable: true,
  11354. configurable: true
  11355. });
  11356. Object.defineProperty(Engine, "INVERT", {
  11357. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11358. get: function () {
  11359. return Engine._INVERT;
  11360. },
  11361. enumerable: true,
  11362. configurable: true
  11363. });
  11364. Object.defineProperty(Engine, "INCR_WRAP", {
  11365. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11366. get: function () {
  11367. return Engine._INCR_WRAP;
  11368. },
  11369. enumerable: true,
  11370. configurable: true
  11371. });
  11372. Object.defineProperty(Engine, "DECR_WRAP", {
  11373. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11374. get: function () {
  11375. return Engine._DECR_WRAP;
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11381. // Alpha
  11382. /** Defines that alpha blending is disabled */
  11383. get: function () {
  11384. return Engine._ALPHA_DISABLE;
  11385. },
  11386. enumerable: true,
  11387. configurable: true
  11388. });
  11389. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11390. /** Defines that alpha blending to SRC + DEST */
  11391. get: function () {
  11392. return Engine._ALPHA_ONEONE;
  11393. },
  11394. enumerable: true,
  11395. configurable: true
  11396. });
  11397. Object.defineProperty(Engine, "ALPHA_ADD", {
  11398. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11399. get: function () {
  11400. return Engine._ALPHA_ADD;
  11401. },
  11402. enumerable: true,
  11403. configurable: true
  11404. });
  11405. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11406. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11407. get: function () {
  11408. return Engine._ALPHA_COMBINE;
  11409. },
  11410. enumerable: true,
  11411. configurable: true
  11412. });
  11413. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11414. /** Defines that alpha blending to DEST - SRC * DEST */
  11415. get: function () {
  11416. return Engine._ALPHA_SUBTRACT;
  11417. },
  11418. enumerable: true,
  11419. configurable: true
  11420. });
  11421. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11422. /** Defines that alpha blending to SRC * DEST */
  11423. get: function () {
  11424. return Engine._ALPHA_MULTIPLY;
  11425. },
  11426. enumerable: true,
  11427. configurable: true
  11428. });
  11429. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11430. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11431. get: function () {
  11432. return Engine._ALPHA_MAXIMIZED;
  11433. },
  11434. enumerable: true,
  11435. configurable: true
  11436. });
  11437. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11438. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11439. get: function () {
  11440. return Engine._ALPHA_PREMULTIPLIED;
  11441. },
  11442. enumerable: true,
  11443. configurable: true
  11444. });
  11445. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11446. /**
  11447. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11448. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11449. */
  11450. get: function () {
  11451. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11452. },
  11453. enumerable: true,
  11454. configurable: true
  11455. });
  11456. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11457. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11458. get: function () {
  11459. return Engine._ALPHA_INTERPOLATE;
  11460. },
  11461. enumerable: true,
  11462. configurable: true
  11463. });
  11464. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11465. /**
  11466. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11467. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11468. */
  11469. get: function () {
  11470. return Engine._ALPHA_SCREENMODE;
  11471. },
  11472. enumerable: true,
  11473. configurable: true
  11474. });
  11475. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11476. // Delays
  11477. /** Defines that the ressource is not delayed*/
  11478. get: function () {
  11479. return Engine._DELAYLOADSTATE_NONE;
  11480. },
  11481. enumerable: true,
  11482. configurable: true
  11483. });
  11484. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11485. /** Defines that the ressource was successfully delay loaded */
  11486. get: function () {
  11487. return Engine._DELAYLOADSTATE_LOADED;
  11488. },
  11489. enumerable: true,
  11490. configurable: true
  11491. });
  11492. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11493. /** Defines that the ressource is currently delay loading */
  11494. get: function () {
  11495. return Engine._DELAYLOADSTATE_LOADING;
  11496. },
  11497. enumerable: true,
  11498. configurable: true
  11499. });
  11500. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11501. /** Defines that the ressource is delayed and has not started loading */
  11502. get: function () {
  11503. return Engine._DELAYLOADSTATE_NOTLOADED;
  11504. },
  11505. enumerable: true,
  11506. configurable: true
  11507. });
  11508. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11509. /** ALPHA */
  11510. get: function () {
  11511. return Engine._TEXTUREFORMAT_ALPHA;
  11512. },
  11513. enumerable: true,
  11514. configurable: true
  11515. });
  11516. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11517. /** LUMINANCE */
  11518. get: function () {
  11519. return Engine._TEXTUREFORMAT_LUMINANCE;
  11520. },
  11521. enumerable: true,
  11522. configurable: true
  11523. });
  11524. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11525. /**
  11526. * R32F
  11527. */
  11528. get: function () {
  11529. return Engine._TEXTUREFORMAT_R32F;
  11530. },
  11531. enumerable: true,
  11532. configurable: true
  11533. });
  11534. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11535. /**
  11536. * RG32F
  11537. */
  11538. get: function () {
  11539. return Engine._TEXTUREFORMAT_RG32F;
  11540. },
  11541. enumerable: true,
  11542. configurable: true
  11543. });
  11544. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11545. /**
  11546. * RGB32F
  11547. */
  11548. get: function () {
  11549. return Engine._TEXTUREFORMAT_RGB32F;
  11550. },
  11551. enumerable: true,
  11552. configurable: true
  11553. });
  11554. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11555. /**
  11556. * RGBA32F
  11557. */
  11558. get: function () {
  11559. return Engine._TEXTUREFORMAT_RGBA32F;
  11560. },
  11561. enumerable: true,
  11562. configurable: true
  11563. });
  11564. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11565. /** LUMINANCE_ALPHA */
  11566. get: function () {
  11567. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11568. },
  11569. enumerable: true,
  11570. configurable: true
  11571. });
  11572. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11573. /** RGB */
  11574. get: function () {
  11575. return Engine._TEXTUREFORMAT_RGB;
  11576. },
  11577. enumerable: true,
  11578. configurable: true
  11579. });
  11580. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11581. /** RGBA */
  11582. get: function () {
  11583. return Engine._TEXTUREFORMAT_RGBA;
  11584. },
  11585. enumerable: true,
  11586. configurable: true
  11587. });
  11588. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11589. /** UNSIGNED_INT */
  11590. get: function () {
  11591. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11597. /** FLOAT */
  11598. get: function () {
  11599. return Engine._TEXTURETYPE_FLOAT;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11605. /** HALF_FLOAT */
  11606. get: function () {
  11607. return Engine._TEXTURETYPE_HALF_FLOAT;
  11608. },
  11609. enumerable: true,
  11610. configurable: true
  11611. });
  11612. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11613. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11614. get: function () {
  11615. return Engine._SCALEMODE_FLOOR;
  11616. },
  11617. enumerable: true,
  11618. configurable: true
  11619. });
  11620. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11621. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11622. get: function () {
  11623. return Engine._SCALEMODE_NEAREST;
  11624. },
  11625. enumerable: true,
  11626. configurable: true
  11627. });
  11628. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11629. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11630. get: function () {
  11631. return Engine._SCALEMODE_CEILING;
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(Engine, "Version", {
  11637. /**
  11638. * Returns the current version of the framework
  11639. */
  11640. get: function () {
  11641. return "3.2.0-beta.4";
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11647. /**
  11648. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11649. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11650. */
  11651. get: function () {
  11652. return this._vrExclusivePointerMode;
  11653. },
  11654. enumerable: true,
  11655. configurable: true
  11656. });
  11657. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11658. /**
  11659. * Gets a boolean indicating that the engine supports uniform buffers
  11660. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11661. */
  11662. get: function () {
  11663. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11669. /**
  11670. * Gets a boolean indicating that only power of 2 textures are supported
  11671. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11672. */
  11673. get: function () {
  11674. return this._webGLVersion < 2 || this.forcePOTTextures;
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11680. /**
  11681. * Gets the performance monitor attached to this engine
  11682. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11683. */
  11684. get: function () {
  11685. return this._performanceMonitor;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11691. /**
  11692. * Gets the list of texture formats supported
  11693. */
  11694. get: function () {
  11695. return this._texturesSupported;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11701. /**
  11702. * Gets the list of texture formats in use
  11703. */
  11704. get: function () {
  11705. return this._textureFormatInUse;
  11706. },
  11707. enumerable: true,
  11708. configurable: true
  11709. });
  11710. Object.defineProperty(Engine.prototype, "currentViewport", {
  11711. /**
  11712. * Gets the current viewport
  11713. */
  11714. get: function () {
  11715. return this._cachedViewport;
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11721. /**
  11722. * Gets the default empty texture
  11723. */
  11724. get: function () {
  11725. if (!this._emptyTexture) {
  11726. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11727. }
  11728. return this._emptyTexture;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11734. /**
  11735. * Gets the default empty 3D texture
  11736. */
  11737. get: function () {
  11738. if (!this._emptyTexture3D) {
  11739. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11740. }
  11741. return this._emptyTexture3D;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11747. /**
  11748. * Gets the default empty cube texture
  11749. */
  11750. get: function () {
  11751. if (!this._emptyCubeTexture) {
  11752. var faceData = new Uint8Array(4);
  11753. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11754. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11755. }
  11756. return this._emptyCubeTexture;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Engine.prototype._rebuildInternalTextures = function () {
  11762. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11763. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11764. var internalTexture = currentState_1[_i];
  11765. internalTexture._rebuild();
  11766. }
  11767. };
  11768. Engine.prototype._rebuildEffects = function () {
  11769. for (var key in this._compiledEffects) {
  11770. var effect = this._compiledEffects[key];
  11771. effect._prepareEffect();
  11772. }
  11773. BABYLON.Effect.ResetCache();
  11774. };
  11775. Engine.prototype._rebuildBuffers = function () {
  11776. // Index / Vertex
  11777. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11778. var scene = _a[_i];
  11779. scene.resetCachedMaterial();
  11780. scene._rebuildGeometries();
  11781. scene._rebuildTextures();
  11782. }
  11783. // Uniforms
  11784. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11785. var uniformBuffer = _c[_b];
  11786. uniformBuffer._rebuild();
  11787. }
  11788. };
  11789. Engine.prototype._initGLContext = function () {
  11790. // Caps
  11791. this._caps = new EngineCapabilities();
  11792. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11793. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11794. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11795. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11796. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11797. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11798. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11799. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11800. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11801. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11802. // Infos
  11803. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11804. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11805. if (rendererInfo != null) {
  11806. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11807. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11808. }
  11809. if (!this._glVendor) {
  11810. this._glVendor = "Unknown vendor";
  11811. }
  11812. if (!this._glRenderer) {
  11813. this._glRenderer = "Unknown renderer";
  11814. }
  11815. // Constants
  11816. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11817. if (this._gl.RGBA16F !== 0x881A) {
  11818. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11819. }
  11820. if (this._gl.RGBA32F !== 0x8814) {
  11821. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11822. }
  11823. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11824. this._gl.DEPTH24_STENCIL8 = 35056;
  11825. }
  11826. // Extensions
  11827. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11828. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11829. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11830. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11831. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11832. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11833. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11834. 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');
  11835. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11836. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11837. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11838. this._caps.highPrecisionShaderSupported = true;
  11839. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11840. if (this._caps.timerQuery) {
  11841. if (this._webGLVersion === 1) {
  11842. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11843. }
  11844. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11845. }
  11846. // Checks if some of the format renders first to allow the use of webgl inspector.
  11847. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11848. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11849. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11850. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11851. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11852. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11853. if (this._webGLVersion > 1) {
  11854. this._gl.HALF_FLOAT_OES = 0x140B;
  11855. }
  11856. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11857. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11858. // Draw buffers
  11859. if (this._webGLVersion > 1) {
  11860. this._caps.drawBuffersExtension = true;
  11861. }
  11862. else {
  11863. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11864. if (drawBuffersExtension !== null) {
  11865. this._caps.drawBuffersExtension = true;
  11866. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11867. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11868. for (var i = 0; i < 16; i++) {
  11869. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11870. }
  11871. }
  11872. else {
  11873. this._caps.drawBuffersExtension = false;
  11874. }
  11875. }
  11876. // Depth Texture
  11877. if (this._webGLVersion > 1) {
  11878. this._caps.depthTextureExtension = true;
  11879. }
  11880. else {
  11881. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11882. if (depthTextureExtension != null) {
  11883. this._caps.depthTextureExtension = true;
  11884. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11885. }
  11886. }
  11887. // Vertex array object
  11888. if (this._webGLVersion > 1) {
  11889. this._caps.vertexArrayObject = true;
  11890. }
  11891. else {
  11892. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11893. if (vertexArrayObjectExtension != null) {
  11894. this._caps.vertexArrayObject = true;
  11895. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11896. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11897. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11898. }
  11899. else {
  11900. this._caps.vertexArrayObject = false;
  11901. }
  11902. }
  11903. // Instances count
  11904. if (this._webGLVersion > 1) {
  11905. this._caps.instancedArrays = true;
  11906. }
  11907. else {
  11908. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11909. if (instanceExtension != null) {
  11910. this._caps.instancedArrays = true;
  11911. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11912. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11913. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11914. }
  11915. else {
  11916. this._caps.instancedArrays = false;
  11917. }
  11918. }
  11919. // Intelligently add supported compressed formats in order to check for.
  11920. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11921. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11922. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11923. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11924. if (this._caps.astc)
  11925. this.texturesSupported.push('-astc.ktx');
  11926. if (this._caps.s3tc)
  11927. this.texturesSupported.push('-dxt.ktx');
  11928. if (this._caps.pvrtc)
  11929. this.texturesSupported.push('-pvrtc.ktx');
  11930. if (this._caps.etc2)
  11931. this.texturesSupported.push('-etc2.ktx');
  11932. if (this._caps.etc1)
  11933. this.texturesSupported.push('-etc1.ktx');
  11934. if (this._gl.getShaderPrecisionFormat) {
  11935. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11936. if (highp) {
  11937. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11938. }
  11939. }
  11940. // Depth buffer
  11941. this.setDepthBuffer(true);
  11942. this.setDepthFunctionToLessOrEqual();
  11943. this.setDepthWrite(true);
  11944. // Texture maps
  11945. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11946. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11947. this._nextFreeTextureSlots.push(slot);
  11948. }
  11949. };
  11950. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11951. /**
  11952. * Gets version of the current webGL context
  11953. */
  11954. get: function () {
  11955. return this._webGLVersion;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11961. /**
  11962. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11963. */
  11964. get: function () {
  11965. return this._isStencilEnable;
  11966. },
  11967. enumerable: true,
  11968. configurable: true
  11969. });
  11970. Engine.prototype._prepareWorkingCanvas = function () {
  11971. if (this._workingCanvas) {
  11972. return;
  11973. }
  11974. this._workingCanvas = document.createElement("canvas");
  11975. var context = this._workingCanvas.getContext("2d");
  11976. if (context) {
  11977. this._workingContext = context;
  11978. }
  11979. };
  11980. /**
  11981. * Reset the texture cache to empty state
  11982. */
  11983. Engine.prototype.resetTextureCache = function () {
  11984. for (var key in this._boundTexturesCache) {
  11985. var boundTexture = this._boundTexturesCache[key];
  11986. if (boundTexture) {
  11987. this._removeDesignatedSlot(boundTexture);
  11988. }
  11989. this._boundTexturesCache[key] = null;
  11990. }
  11991. if (!this.disableTextureBindingOptimization) {
  11992. this._nextFreeTextureSlots = [];
  11993. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11994. this._nextFreeTextureSlots.push(slot);
  11995. }
  11996. }
  11997. this._currentTextureChannel = -1;
  11998. };
  11999. /**
  12000. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12001. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12002. * @returns true if engine is in deterministic lock step mode
  12003. */
  12004. Engine.prototype.isDeterministicLockStep = function () {
  12005. return this._deterministicLockstep;
  12006. };
  12007. /**
  12008. * Gets the max steps when engine is running in deterministic lock step
  12009. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12010. * @returns the max steps
  12011. */
  12012. Engine.prototype.getLockstepMaxSteps = function () {
  12013. return this._lockstepMaxSteps;
  12014. };
  12015. /**
  12016. * Gets an object containing information about the current webGL context
  12017. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12018. */
  12019. Engine.prototype.getGlInfo = function () {
  12020. return {
  12021. vendor: this._glVendor,
  12022. renderer: this._glRenderer,
  12023. version: this._glVersion
  12024. };
  12025. };
  12026. /**
  12027. * Gets current aspect ratio
  12028. * @param camera defines the camera to use to get the aspect ratio
  12029. * @param useScreen defines if screen size must be used (or the current render target if any)
  12030. * @returns a number defining the aspect ratio
  12031. */
  12032. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12033. if (useScreen === void 0) { useScreen = false; }
  12034. var viewport = camera.viewport;
  12035. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12036. };
  12037. /**
  12038. * Gets the current render width
  12039. * @param useScreen defines if screen size must be used (or the current render target if any)
  12040. * @returns a number defining the current render width
  12041. */
  12042. Engine.prototype.getRenderWidth = function (useScreen) {
  12043. if (useScreen === void 0) { useScreen = false; }
  12044. if (!useScreen && this._currentRenderTarget) {
  12045. return this._currentRenderTarget.width;
  12046. }
  12047. return this._gl.drawingBufferWidth;
  12048. };
  12049. /**
  12050. * Gets the current render height
  12051. * @param useScreen defines if screen size must be used (or the current render target if any)
  12052. * @returns a number defining the current render height
  12053. */
  12054. Engine.prototype.getRenderHeight = function (useScreen) {
  12055. if (useScreen === void 0) { useScreen = false; }
  12056. if (!useScreen && this._currentRenderTarget) {
  12057. return this._currentRenderTarget.height;
  12058. }
  12059. return this._gl.drawingBufferHeight;
  12060. };
  12061. /**
  12062. * Gets the HTML canvas attached with the current webGL context
  12063. * @returns a HTML canvas
  12064. */
  12065. Engine.prototype.getRenderingCanvas = function () {
  12066. return this._renderingCanvas;
  12067. };
  12068. /**
  12069. * Gets the client rect of the HTML canvas attached with the current webGL context
  12070. * @returns a client rectanglee
  12071. */
  12072. Engine.prototype.getRenderingCanvasClientRect = function () {
  12073. if (!this._renderingCanvas) {
  12074. return null;
  12075. }
  12076. return this._renderingCanvas.getBoundingClientRect();
  12077. };
  12078. /**
  12079. * Defines the hardware scaling level.
  12080. * By default the hardware scaling level is computed from the window device ratio.
  12081. * 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.
  12082. * @param level defines the level to use
  12083. */
  12084. Engine.prototype.setHardwareScalingLevel = function (level) {
  12085. this._hardwareScalingLevel = level;
  12086. this.resize();
  12087. };
  12088. /**
  12089. * Gets the current hardware scaling level.
  12090. * By default the hardware scaling level is computed from the window device ratio.
  12091. * 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.
  12092. * @returns a number indicating the current hardware scaling level
  12093. */
  12094. Engine.prototype.getHardwareScalingLevel = function () {
  12095. return this._hardwareScalingLevel;
  12096. };
  12097. /**
  12098. * Gets the list of loaded textures
  12099. * @returns an array containing all loaded textures
  12100. */
  12101. Engine.prototype.getLoadedTexturesCache = function () {
  12102. return this._internalTexturesCache;
  12103. };
  12104. /**
  12105. * Gets the object containing all engine capabilities
  12106. * @returns the EngineCapabilities object
  12107. */
  12108. Engine.prototype.getCaps = function () {
  12109. return this._caps;
  12110. };
  12111. Object.defineProperty(Engine.prototype, "drawCalls", {
  12112. /** @ignore */
  12113. get: function () {
  12114. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12115. return 0;
  12116. },
  12117. enumerable: true,
  12118. configurable: true
  12119. });
  12120. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12121. /** @ignore */
  12122. get: function () {
  12123. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12124. return null;
  12125. },
  12126. enumerable: true,
  12127. configurable: true
  12128. });
  12129. /**
  12130. * Gets the current depth function
  12131. * @returns a number defining the depth function
  12132. */
  12133. Engine.prototype.getDepthFunction = function () {
  12134. return this._depthCullingState.depthFunc;
  12135. };
  12136. /**
  12137. * Sets the current depth function
  12138. * @param depthFunc defines the function to use
  12139. */
  12140. Engine.prototype.setDepthFunction = function (depthFunc) {
  12141. this._depthCullingState.depthFunc = depthFunc;
  12142. };
  12143. /**
  12144. * Sets the current depth function to GREATER
  12145. */
  12146. Engine.prototype.setDepthFunctionToGreater = function () {
  12147. this._depthCullingState.depthFunc = this._gl.GREATER;
  12148. };
  12149. /**
  12150. * Sets the current depth function to GEQUAL
  12151. */
  12152. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12153. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12154. };
  12155. /**
  12156. * Sets the current depth function to LESS
  12157. */
  12158. Engine.prototype.setDepthFunctionToLess = function () {
  12159. this._depthCullingState.depthFunc = this._gl.LESS;
  12160. };
  12161. /**
  12162. * Sets the current depth function to LEQUAL
  12163. */
  12164. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12165. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12166. };
  12167. /**
  12168. * Gets a boolean indicating if stencil buffer is enabled
  12169. * @returns the current stencil buffer state
  12170. */
  12171. Engine.prototype.getStencilBuffer = function () {
  12172. return this._stencilState.stencilTest;
  12173. };
  12174. /**
  12175. * Enable or disable the stencil buffer
  12176. * @param enable defines if the stencil buffer must be enabled or disabled
  12177. */
  12178. Engine.prototype.setStencilBuffer = function (enable) {
  12179. this._stencilState.stencilTest = enable;
  12180. };
  12181. /**
  12182. * Gets the current stencil mask
  12183. * @returns a number defining the new stencil mask to use
  12184. */
  12185. Engine.prototype.getStencilMask = function () {
  12186. return this._stencilState.stencilMask;
  12187. };
  12188. /**
  12189. * Sets the current stencil mask
  12190. * @param mask defines the new stencil mask to use
  12191. */
  12192. Engine.prototype.setStencilMask = function (mask) {
  12193. this._stencilState.stencilMask = mask;
  12194. };
  12195. /**
  12196. * Gets the current stencil function
  12197. * @returns a number defining the stencil function to use
  12198. */
  12199. Engine.prototype.getStencilFunction = function () {
  12200. return this._stencilState.stencilFunc;
  12201. };
  12202. /**
  12203. * Gets the current stencil reference value
  12204. * @returns a number defining the stencil reference value to use
  12205. */
  12206. Engine.prototype.getStencilFunctionReference = function () {
  12207. return this._stencilState.stencilFuncRef;
  12208. };
  12209. /**
  12210. * Gets the current stencil mask
  12211. * @returns a number defining the stencil mask to use
  12212. */
  12213. Engine.prototype.getStencilFunctionMask = function () {
  12214. return this._stencilState.stencilFuncMask;
  12215. };
  12216. /**
  12217. * Sets the current stencil function
  12218. * @param stencilFunc defines the new stencil function to use
  12219. */
  12220. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12221. this._stencilState.stencilFunc = stencilFunc;
  12222. };
  12223. /**
  12224. * Sets the current stencil reference
  12225. * @param reference defines the new stencil reference to use
  12226. */
  12227. Engine.prototype.setStencilFunctionReference = function (reference) {
  12228. this._stencilState.stencilFuncRef = reference;
  12229. };
  12230. /**
  12231. * Sets the current stencil mask
  12232. * @param mask defines the new stencil mask to use
  12233. */
  12234. Engine.prototype.setStencilFunctionMask = function (mask) {
  12235. this._stencilState.stencilFuncMask = mask;
  12236. };
  12237. /**
  12238. * Gets the current stencil operation when stencil fails
  12239. * @returns a number defining stencil operation to use when stencil fails
  12240. */
  12241. Engine.prototype.getStencilOperationFail = function () {
  12242. return this._stencilState.stencilOpStencilFail;
  12243. };
  12244. /**
  12245. * Gets the current stencil operation when depth fails
  12246. * @returns a number defining stencil operation to use when depth fails
  12247. */
  12248. Engine.prototype.getStencilOperationDepthFail = function () {
  12249. return this._stencilState.stencilOpDepthFail;
  12250. };
  12251. /**
  12252. * Gets the current stencil operation when stencil passes
  12253. * @returns a number defining stencil operation to use when stencil passes
  12254. */
  12255. Engine.prototype.getStencilOperationPass = function () {
  12256. return this._stencilState.stencilOpStencilDepthPass;
  12257. };
  12258. /**
  12259. * Sets the stencil operation to use when stencil fails
  12260. * @param operation defines the stencil operation to use when stencil fails
  12261. */
  12262. Engine.prototype.setStencilOperationFail = function (operation) {
  12263. this._stencilState.stencilOpStencilFail = operation;
  12264. };
  12265. /**
  12266. * Sets the stencil operation to use when depth fails
  12267. * @param operation defines the stencil operation to use when depth fails
  12268. */
  12269. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12270. this._stencilState.stencilOpDepthFail = operation;
  12271. };
  12272. /**
  12273. * Sets the stencil operation to use when stencil passes
  12274. * @param operation defines the stencil operation to use when stencil passes
  12275. */
  12276. Engine.prototype.setStencilOperationPass = function (operation) {
  12277. this._stencilState.stencilOpStencilDepthPass = operation;
  12278. };
  12279. /**
  12280. * Sets a boolean indicating if the dithering state is enabled or disabled
  12281. * @param value defines the dithering state
  12282. */
  12283. Engine.prototype.setDitheringState = function (value) {
  12284. if (value) {
  12285. this._gl.enable(this._gl.DITHER);
  12286. }
  12287. else {
  12288. this._gl.disable(this._gl.DITHER);
  12289. }
  12290. };
  12291. /**
  12292. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12293. * @param value defines the rasterizer state
  12294. */
  12295. Engine.prototype.setRasterizerState = function (value) {
  12296. if (value) {
  12297. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12298. }
  12299. else {
  12300. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12301. }
  12302. };
  12303. /**
  12304. * stop executing a render loop function and remove it from the execution array
  12305. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12306. */
  12307. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12308. if (!renderFunction) {
  12309. this._activeRenderLoops = [];
  12310. return;
  12311. }
  12312. var index = this._activeRenderLoops.indexOf(renderFunction);
  12313. if (index >= 0) {
  12314. this._activeRenderLoops.splice(index, 1);
  12315. }
  12316. };
  12317. /** @ignore */
  12318. Engine.prototype._renderLoop = function () {
  12319. if (!this._contextWasLost) {
  12320. var shouldRender = true;
  12321. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12322. shouldRender = false;
  12323. }
  12324. if (shouldRender) {
  12325. // Start new frame
  12326. this.beginFrame();
  12327. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12328. var renderFunction = this._activeRenderLoops[index];
  12329. renderFunction();
  12330. }
  12331. // Present
  12332. this.endFrame();
  12333. }
  12334. }
  12335. if (this._activeRenderLoops.length > 0) {
  12336. // Register new frame
  12337. var requester = null;
  12338. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12339. requester = this._vrDisplay;
  12340. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12341. }
  12342. else {
  12343. this._renderingQueueLaunched = false;
  12344. }
  12345. };
  12346. /**
  12347. * Register and execute a render loop. The engine can have more than one render function
  12348. * @param renderFunction defines the function to continuously execute
  12349. */
  12350. Engine.prototype.runRenderLoop = function (renderFunction) {
  12351. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12352. return;
  12353. }
  12354. this._activeRenderLoops.push(renderFunction);
  12355. if (!this._renderingQueueLaunched) {
  12356. this._renderingQueueLaunched = true;
  12357. this._bindedRenderFunction = this._renderLoop.bind(this);
  12358. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12359. }
  12360. };
  12361. /**
  12362. * Toggle full screen mode
  12363. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12364. * @param options defines an option object to be sent to the requestFullscreen function
  12365. */
  12366. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12367. if (this.isFullscreen) {
  12368. BABYLON.Tools.ExitFullscreen();
  12369. }
  12370. else {
  12371. this._pointerLockRequested = requestPointerLock;
  12372. if (this._renderingCanvas) {
  12373. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12374. }
  12375. }
  12376. };
  12377. /**
  12378. * Clear the current render buffer or the current render target (if any is set up)
  12379. * @param color defines the color to use
  12380. * @param backBuffer defines if the back buffer must be cleared
  12381. * @param depth defines if the depth buffer must be cleared
  12382. * @param stencil defines if the stencil buffer must be cleared
  12383. */
  12384. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12385. if (stencil === void 0) { stencil = false; }
  12386. this.applyStates();
  12387. var mode = 0;
  12388. if (backBuffer && color) {
  12389. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12390. mode |= this._gl.COLOR_BUFFER_BIT;
  12391. }
  12392. if (depth) {
  12393. this._gl.clearDepth(1.0);
  12394. mode |= this._gl.DEPTH_BUFFER_BIT;
  12395. }
  12396. if (stencil) {
  12397. this._gl.clearStencil(0);
  12398. mode |= this._gl.STENCIL_BUFFER_BIT;
  12399. }
  12400. this._gl.clear(mode);
  12401. };
  12402. /**
  12403. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12404. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12405. * @param y defines the y-coordinate of the corner of the clear rectangle
  12406. * @param width defines the width of the clear rectangle
  12407. * @param height defines the height of the clear rectangle
  12408. * @param clearColor defines the clear color
  12409. */
  12410. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12411. var gl = this._gl;
  12412. // Save state
  12413. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12414. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12415. // Change state
  12416. gl.enable(gl.SCISSOR_TEST);
  12417. gl.scissor(x, y, width, height);
  12418. // Clear
  12419. this.clear(clearColor, true, true, true);
  12420. // Restore state
  12421. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12422. if (curScissor === true) {
  12423. gl.enable(gl.SCISSOR_TEST);
  12424. }
  12425. else {
  12426. gl.disable(gl.SCISSOR_TEST);
  12427. }
  12428. };
  12429. /**
  12430. * Set the WebGL's viewport
  12431. * @param viewport defines the viewport element to be used
  12432. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12433. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12434. */
  12435. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12436. var width = requiredWidth || this.getRenderWidth();
  12437. var height = requiredHeight || this.getRenderHeight();
  12438. var x = viewport.x || 0;
  12439. var y = viewport.y || 0;
  12440. this._cachedViewport = viewport;
  12441. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12442. };
  12443. /**
  12444. * Directly set the WebGL Viewport
  12445. * @param x defines the x coordinate of the viewport (in screen space)
  12446. * @param y defines the y coordinate of the viewport (in screen space)
  12447. * @param width defines the width of the viewport (in screen space)
  12448. * @param height defines the height of the viewport (in screen space)
  12449. * @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
  12450. */
  12451. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12452. var currentViewport = this._cachedViewport;
  12453. this._cachedViewport = null;
  12454. this._gl.viewport(x, y, width, height);
  12455. return currentViewport;
  12456. };
  12457. /**
  12458. * Begin a new frame
  12459. */
  12460. Engine.prototype.beginFrame = function () {
  12461. this.onBeginFrameObservable.notifyObservers(this);
  12462. this._measureFps();
  12463. };
  12464. /**
  12465. * Enf the current frame
  12466. */
  12467. Engine.prototype.endFrame = function () {
  12468. // Force a flush in case we are using a bad OS.
  12469. if (this._badOS) {
  12470. this.flushFramebuffer();
  12471. }
  12472. // Submit frame to the vr device, if enabled
  12473. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12474. // TODO: We should only submit the frame if we read frameData successfully.
  12475. this._vrDisplay.submitFrame();
  12476. }
  12477. this.onEndFrameObservable.notifyObservers(this);
  12478. };
  12479. /**
  12480. * Resize the view according to the canvas' size
  12481. */
  12482. Engine.prototype.resize = function () {
  12483. // We're not resizing the size of the canvas while in VR mode & presenting
  12484. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12485. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12486. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12487. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12488. }
  12489. };
  12490. /**
  12491. * Force a specific size of the canvas
  12492. * @param width defines the new canvas' width
  12493. * @param height defines the new canvas' height
  12494. */
  12495. Engine.prototype.setSize = function (width, height) {
  12496. if (!this._renderingCanvas) {
  12497. return;
  12498. }
  12499. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12500. return;
  12501. }
  12502. this._renderingCanvas.width = width;
  12503. this._renderingCanvas.height = height;
  12504. for (var index = 0; index < this.scenes.length; index++) {
  12505. var scene = this.scenes[index];
  12506. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12507. var cam = scene.cameras[camIndex];
  12508. cam._currentRenderId = 0;
  12509. }
  12510. }
  12511. if (this.onResizeObservable.hasObservers) {
  12512. this.onResizeObservable.notifyObservers(this);
  12513. }
  12514. };
  12515. // WebVR functions
  12516. /**
  12517. * Gets a boolean indicating if a webVR device was detected
  12518. * @returns true if a webVR device was detected
  12519. */
  12520. Engine.prototype.isVRDevicePresent = function () {
  12521. return !!this._vrDisplay;
  12522. };
  12523. /**
  12524. * Gets the current webVR device
  12525. * @returns the current webVR device (or null)
  12526. */
  12527. Engine.prototype.getVRDevice = function () {
  12528. return this._vrDisplay;
  12529. };
  12530. /**
  12531. * Initializes a webVR display and starts listening to display change events
  12532. * The onVRDisplayChangedObservable will be notified upon these changes
  12533. * @returns The onVRDisplayChangedObservable
  12534. */
  12535. Engine.prototype.initWebVR = function () {
  12536. this.initWebVRAsync();
  12537. return this.onVRDisplayChangedObservable;
  12538. };
  12539. /**
  12540. * Initializes a webVR display and starts listening to display change events
  12541. * The onVRDisplayChangedObservable will be notified upon these changes
  12542. * @returns A promise containing a VRDisplay and if vr is supported
  12543. */
  12544. Engine.prototype.initWebVRAsync = function () {
  12545. var _this = this;
  12546. var notifyObservers = function () {
  12547. var eventArgs = {
  12548. vrDisplay: _this._vrDisplay,
  12549. vrSupported: _this._vrSupported
  12550. };
  12551. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12552. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12553. };
  12554. if (!this._onVrDisplayConnect) {
  12555. this._onVrDisplayConnect = function (event) {
  12556. _this._vrDisplay = event.display;
  12557. notifyObservers();
  12558. };
  12559. this._onVrDisplayDisconnect = function () {
  12560. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12561. _this._vrDisplay = undefined;
  12562. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12563. notifyObservers();
  12564. };
  12565. this._onVrDisplayPresentChange = function () {
  12566. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12567. };
  12568. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12569. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12570. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12571. }
  12572. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12573. this._webVRInitPromise.then(notifyObservers);
  12574. return this._webVRInitPromise;
  12575. };
  12576. /**
  12577. * Call this function to switch to webVR mode
  12578. * Will do nothing if webVR is not supported or if there is no webVR device
  12579. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12580. */
  12581. Engine.prototype.enableVR = function () {
  12582. var _this = this;
  12583. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12584. var onResolved = function () {
  12585. _this.onVRRequestPresentComplete.notifyObservers(true);
  12586. _this._onVRFullScreenTriggered();
  12587. };
  12588. var onRejected = function () {
  12589. _this.onVRRequestPresentComplete.notifyObservers(false);
  12590. };
  12591. this.onVRRequestPresentStart.notifyObservers(this);
  12592. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12593. }
  12594. };
  12595. /**
  12596. * Call this function to leave webVR mode
  12597. * Will do nothing if webVR is not supported or if there is no webVR device
  12598. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12599. */
  12600. Engine.prototype.disableVR = function () {
  12601. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12602. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12603. }
  12604. };
  12605. Engine.prototype._getVRDisplaysAsync = function () {
  12606. var _this = this;
  12607. return new Promise(function (res, rej) {
  12608. if (navigator.getVRDisplays) {
  12609. navigator.getVRDisplays().then(function (devices) {
  12610. _this._vrSupported = true;
  12611. // note that devices may actually be an empty array. This is fine;
  12612. // we expect this._vrDisplay to be undefined in this case.
  12613. _this._vrDisplay = devices[0];
  12614. res({
  12615. vrDisplay: _this._vrDisplay,
  12616. vrSupported: _this._vrSupported
  12617. });
  12618. });
  12619. }
  12620. else {
  12621. _this._vrDisplay = undefined;
  12622. _this._vrSupported = false;
  12623. res({
  12624. vrDisplay: _this._vrDisplay,
  12625. vrSupported: _this._vrSupported
  12626. });
  12627. }
  12628. });
  12629. };
  12630. /**
  12631. * Binds the frame buffer to the specified texture.
  12632. * @param texture The texture to render to or null for the default canvas
  12633. * @param faceIndex The face of the texture to render to in case of cube texture
  12634. * @param requiredWidth The width of the target to render to
  12635. * @param requiredHeight The height of the target to render to
  12636. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12637. * @param depthStencilTexture The depth stencil texture to use to render
  12638. */
  12639. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12640. if (this._currentRenderTarget) {
  12641. this.unBindFramebuffer(this._currentRenderTarget);
  12642. }
  12643. this._currentRenderTarget = texture;
  12644. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12645. var gl = this._gl;
  12646. if (texture.isCube) {
  12647. if (faceIndex === undefined) {
  12648. faceIndex = 0;
  12649. }
  12650. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12651. if (depthStencilTexture) {
  12652. if (depthStencilTexture._generateStencilBuffer) {
  12653. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12654. }
  12655. else {
  12656. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12657. }
  12658. }
  12659. }
  12660. if (this._cachedViewport && !forceFullscreenViewport) {
  12661. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12662. }
  12663. else {
  12664. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12665. }
  12666. this.wipeCaches();
  12667. };
  12668. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12669. if (this._currentFramebuffer !== framebuffer) {
  12670. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12671. this._currentFramebuffer = framebuffer;
  12672. }
  12673. };
  12674. /**
  12675. * Unbind the current render target texture from the webGL context
  12676. * @param texture defines the render target texture to unbind
  12677. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12678. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12679. */
  12680. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12681. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12682. this._currentRenderTarget = null;
  12683. // If MSAA, we need to bitblt back to main texture
  12684. var gl = this._gl;
  12685. if (texture._MSAAFramebuffer) {
  12686. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12687. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12688. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12689. }
  12690. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12691. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12692. gl.generateMipmap(gl.TEXTURE_2D);
  12693. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12694. }
  12695. if (onBeforeUnbind) {
  12696. if (texture._MSAAFramebuffer) {
  12697. // Bind the correct framebuffer
  12698. this.bindUnboundFramebuffer(texture._framebuffer);
  12699. }
  12700. onBeforeUnbind();
  12701. }
  12702. this.bindUnboundFramebuffer(null);
  12703. };
  12704. /**
  12705. * Unbind a list of render target textures from the webGL context
  12706. * This is used only when drawBuffer extension or webGL2 are active
  12707. * @param textures defines the render target textures to unbind
  12708. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12709. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12710. */
  12711. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12712. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12713. this._currentRenderTarget = null;
  12714. // If MSAA, we need to bitblt back to main texture
  12715. var gl = this._gl;
  12716. if (textures[0]._MSAAFramebuffer) {
  12717. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12718. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12719. var attachments = textures[0]._attachments;
  12720. if (!attachments) {
  12721. attachments = new Array(textures.length);
  12722. textures[0]._attachments = attachments;
  12723. }
  12724. for (var i = 0; i < textures.length; i++) {
  12725. var texture = textures[i];
  12726. for (var j = 0; j < attachments.length; j++) {
  12727. attachments[j] = gl.NONE;
  12728. }
  12729. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12730. gl.readBuffer(attachments[i]);
  12731. gl.drawBuffers(attachments);
  12732. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12733. }
  12734. for (var i = 0; i < attachments.length; i++) {
  12735. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12736. }
  12737. gl.drawBuffers(attachments);
  12738. }
  12739. for (var i = 0; i < textures.length; i++) {
  12740. var texture = textures[i];
  12741. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12742. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12743. gl.generateMipmap(gl.TEXTURE_2D);
  12744. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12745. }
  12746. }
  12747. if (onBeforeUnbind) {
  12748. if (textures[0]._MSAAFramebuffer) {
  12749. // Bind the correct framebuffer
  12750. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12751. }
  12752. onBeforeUnbind();
  12753. }
  12754. this.bindUnboundFramebuffer(null);
  12755. };
  12756. /**
  12757. * Force the mipmap generation for the given render target texture
  12758. * @param texture defines the render target texture to use
  12759. */
  12760. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12761. if (texture.generateMipMaps) {
  12762. var gl = this._gl;
  12763. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12764. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12765. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12766. }
  12767. };
  12768. /**
  12769. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12770. */
  12771. Engine.prototype.flushFramebuffer = function () {
  12772. this._gl.flush();
  12773. };
  12774. /**
  12775. * Unbind the current render target and bind the default framebuffer
  12776. */
  12777. Engine.prototype.restoreDefaultFramebuffer = function () {
  12778. if (this._currentRenderTarget) {
  12779. this.unBindFramebuffer(this._currentRenderTarget);
  12780. }
  12781. else {
  12782. this.bindUnboundFramebuffer(null);
  12783. }
  12784. if (this._cachedViewport) {
  12785. this.setViewport(this._cachedViewport);
  12786. }
  12787. this.wipeCaches();
  12788. };
  12789. // UBOs
  12790. /**
  12791. * Create an uniform buffer
  12792. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12793. * @param elements defines the content of the uniform buffer
  12794. * @returns the webGL uniform buffer
  12795. */
  12796. Engine.prototype.createUniformBuffer = function (elements) {
  12797. var ubo = this._gl.createBuffer();
  12798. if (!ubo) {
  12799. throw new Error("Unable to create uniform buffer");
  12800. }
  12801. this.bindUniformBuffer(ubo);
  12802. if (elements instanceof Float32Array) {
  12803. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12804. }
  12805. else {
  12806. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12807. }
  12808. this.bindUniformBuffer(null);
  12809. ubo.references = 1;
  12810. return ubo;
  12811. };
  12812. /**
  12813. * Create a dynamic uniform buffer
  12814. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12815. * @param elements defines the content of the uniform buffer
  12816. * @returns the webGL uniform buffer
  12817. */
  12818. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12819. var ubo = this._gl.createBuffer();
  12820. if (!ubo) {
  12821. throw new Error("Unable to create dynamic uniform buffer");
  12822. }
  12823. this.bindUniformBuffer(ubo);
  12824. if (elements instanceof Float32Array) {
  12825. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12826. }
  12827. else {
  12828. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12829. }
  12830. this.bindUniformBuffer(null);
  12831. ubo.references = 1;
  12832. return ubo;
  12833. };
  12834. /**
  12835. * Update an existing uniform buffer
  12836. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12837. * @param uniformBuffer defines the target uniform buffer
  12838. * @param elements defines the content to update
  12839. * @param offset defines the offset in the uniform buffer where update should start
  12840. * @param count defines the size of the data to update
  12841. */
  12842. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12843. this.bindUniformBuffer(uniformBuffer);
  12844. if (offset === undefined) {
  12845. offset = 0;
  12846. }
  12847. if (count === undefined) {
  12848. if (elements instanceof Float32Array) {
  12849. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12850. }
  12851. else {
  12852. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12853. }
  12854. }
  12855. else {
  12856. if (elements instanceof Float32Array) {
  12857. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12858. }
  12859. else {
  12860. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12861. }
  12862. }
  12863. this.bindUniformBuffer(null);
  12864. };
  12865. // VBOs
  12866. Engine.prototype._resetVertexBufferBinding = function () {
  12867. this.bindArrayBuffer(null);
  12868. this._cachedVertexBuffers = null;
  12869. };
  12870. /**
  12871. * Creates a vertex buffer
  12872. * @param data the data for the vertex buffer
  12873. * @returns the new WebGL static buffer
  12874. */
  12875. Engine.prototype.createVertexBuffer = function (data) {
  12876. var vbo = this._gl.createBuffer();
  12877. if (!vbo) {
  12878. throw new Error("Unable to create vertex buffer");
  12879. }
  12880. this.bindArrayBuffer(vbo);
  12881. if (data instanceof Array) {
  12882. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12883. }
  12884. else {
  12885. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12886. }
  12887. this._resetVertexBufferBinding();
  12888. vbo.references = 1;
  12889. return vbo;
  12890. };
  12891. /**
  12892. * Creates a dynamic vertex buffer
  12893. * @param data the data for the dynamic vertex buffer
  12894. * @returns the new WebGL dynamic buffer
  12895. */
  12896. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12897. var vbo = this._gl.createBuffer();
  12898. if (!vbo) {
  12899. throw new Error("Unable to create dynamic vertex buffer");
  12900. }
  12901. this.bindArrayBuffer(vbo);
  12902. if (data instanceof Array) {
  12903. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12904. }
  12905. else {
  12906. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12907. }
  12908. this._resetVertexBufferBinding();
  12909. vbo.references = 1;
  12910. return vbo;
  12911. };
  12912. /**
  12913. * Update a dynamic index buffer
  12914. * @param indexBuffer defines the target index buffer
  12915. * @param indices defines the data to update
  12916. * @param offset defines the offset in the target index buffer where update should start
  12917. */
  12918. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12919. if (offset === void 0) { offset = 0; }
  12920. // Force cache update
  12921. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12922. this.bindIndexBuffer(indexBuffer);
  12923. var arrayBuffer;
  12924. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12925. arrayBuffer = indices;
  12926. }
  12927. else {
  12928. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12929. }
  12930. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12931. this._resetIndexBufferBinding();
  12932. };
  12933. /**
  12934. * Updates a dynamic vertex buffer.
  12935. * @param vertexBuffer the vertex buffer to update
  12936. * @param data the data used to update the vertex buffer
  12937. * @param byteOffset the byte offset of the data
  12938. * @param byteLength the byte length of the data
  12939. */
  12940. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12941. this.bindArrayBuffer(vertexBuffer);
  12942. if (byteOffset === undefined) {
  12943. byteOffset = 0;
  12944. }
  12945. if (byteLength === undefined) {
  12946. if (data instanceof Array) {
  12947. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12948. }
  12949. else {
  12950. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12951. }
  12952. }
  12953. else {
  12954. if (data instanceof Array) {
  12955. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12956. }
  12957. else {
  12958. if (data instanceof ArrayBuffer) {
  12959. data = new Uint8Array(data, byteOffset, byteLength);
  12960. }
  12961. else {
  12962. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12963. }
  12964. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12965. }
  12966. }
  12967. this._resetVertexBufferBinding();
  12968. };
  12969. Engine.prototype._resetIndexBufferBinding = function () {
  12970. this.bindIndexBuffer(null);
  12971. this._cachedIndexBuffer = null;
  12972. };
  12973. /**
  12974. * Creates a new index buffer
  12975. * @param indices defines the content of the index buffer
  12976. * @param updatable defines if the index buffer must be updatable
  12977. * @returns a new webGL buffer
  12978. */
  12979. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12980. var vbo = this._gl.createBuffer();
  12981. if (!vbo) {
  12982. throw new Error("Unable to create index buffer");
  12983. }
  12984. this.bindIndexBuffer(vbo);
  12985. // Check for 32 bits indices
  12986. var arrayBuffer;
  12987. var need32Bits = false;
  12988. if (indices instanceof Uint16Array) {
  12989. arrayBuffer = indices;
  12990. }
  12991. else {
  12992. //check 32 bit support
  12993. if (this._caps.uintIndices) {
  12994. if (indices instanceof Uint32Array) {
  12995. arrayBuffer = indices;
  12996. need32Bits = true;
  12997. }
  12998. else {
  12999. //number[] or Int32Array, check if 32 bit is necessary
  13000. for (var index = 0; index < indices.length; index++) {
  13001. if (indices[index] > 65535) {
  13002. need32Bits = true;
  13003. break;
  13004. }
  13005. }
  13006. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13007. }
  13008. }
  13009. else {
  13010. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13011. arrayBuffer = new Uint16Array(indices);
  13012. }
  13013. }
  13014. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13015. this._resetIndexBufferBinding();
  13016. vbo.references = 1;
  13017. vbo.is32Bits = need32Bits;
  13018. return vbo;
  13019. };
  13020. /**
  13021. * Bind a webGL buffer to the webGL context
  13022. * @param buffer defines the buffer to bind
  13023. */
  13024. Engine.prototype.bindArrayBuffer = function (buffer) {
  13025. if (!this._vaoRecordInProgress) {
  13026. this._unbindVertexArrayObject();
  13027. }
  13028. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13029. };
  13030. /**
  13031. * Bind an uniform buffer to the current webGL context
  13032. * @param buffer defines the buffer to bind
  13033. */
  13034. Engine.prototype.bindUniformBuffer = function (buffer) {
  13035. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13036. };
  13037. /**
  13038. * Bind a buffer to the current webGL context at a given location
  13039. * @param buffer defines the buffer to bind
  13040. * @param location defines the index where to bind the buffer
  13041. */
  13042. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13043. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13044. };
  13045. /**
  13046. * Bind a specific block at a given index in a specific shader program
  13047. * @param shaderProgram defines the shader program
  13048. * @param blockName defines the block name
  13049. * @param index defines the index where to bind the block
  13050. */
  13051. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13052. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13053. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13054. };
  13055. ;
  13056. Engine.prototype.bindIndexBuffer = function (buffer) {
  13057. if (!this._vaoRecordInProgress) {
  13058. this._unbindVertexArrayObject();
  13059. }
  13060. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13061. };
  13062. Engine.prototype.bindBuffer = function (buffer, target) {
  13063. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13064. this._gl.bindBuffer(target, buffer);
  13065. this._currentBoundBuffer[target] = buffer;
  13066. }
  13067. };
  13068. /**
  13069. * update the bound buffer with the given data
  13070. * @param data defines the data to update
  13071. */
  13072. Engine.prototype.updateArrayBuffer = function (data) {
  13073. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13074. };
  13075. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13076. var pointer = this._currentBufferPointers[indx];
  13077. var changed = false;
  13078. if (!pointer.active) {
  13079. changed = true;
  13080. pointer.active = true;
  13081. pointer.index = indx;
  13082. pointer.size = size;
  13083. pointer.type = type;
  13084. pointer.normalized = normalized;
  13085. pointer.stride = stride;
  13086. pointer.offset = offset;
  13087. pointer.buffer = buffer;
  13088. }
  13089. else {
  13090. if (pointer.buffer !== buffer) {
  13091. pointer.buffer = buffer;
  13092. changed = true;
  13093. }
  13094. if (pointer.size !== size) {
  13095. pointer.size = size;
  13096. changed = true;
  13097. }
  13098. if (pointer.type !== type) {
  13099. pointer.type = type;
  13100. changed = true;
  13101. }
  13102. if (pointer.normalized !== normalized) {
  13103. pointer.normalized = normalized;
  13104. changed = true;
  13105. }
  13106. if (pointer.stride !== stride) {
  13107. pointer.stride = stride;
  13108. changed = true;
  13109. }
  13110. if (pointer.offset !== offset) {
  13111. pointer.offset = offset;
  13112. changed = true;
  13113. }
  13114. }
  13115. if (changed || this._vaoRecordInProgress) {
  13116. this.bindArrayBuffer(buffer);
  13117. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13118. }
  13119. };
  13120. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13121. if (indexBuffer == null) {
  13122. return;
  13123. }
  13124. if (this._cachedIndexBuffer !== indexBuffer) {
  13125. this._cachedIndexBuffer = indexBuffer;
  13126. this.bindIndexBuffer(indexBuffer);
  13127. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13128. }
  13129. };
  13130. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13131. var attributes = effect.getAttributesNames();
  13132. if (!this._vaoRecordInProgress) {
  13133. this._unbindVertexArrayObject();
  13134. }
  13135. this.unbindAllAttributes();
  13136. for (var index = 0; index < attributes.length; index++) {
  13137. var order = effect.getAttributeLocation(index);
  13138. if (order >= 0) {
  13139. var vertexBuffer = vertexBuffers[attributes[index]];
  13140. if (!vertexBuffer) {
  13141. continue;
  13142. }
  13143. this._gl.enableVertexAttribArray(order);
  13144. if (!this._vaoRecordInProgress) {
  13145. this._vertexAttribArraysEnabled[order] = true;
  13146. }
  13147. var buffer = vertexBuffer.getBuffer();
  13148. if (buffer) {
  13149. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13150. if (vertexBuffer.getIsInstanced()) {
  13151. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13152. if (!this._vaoRecordInProgress) {
  13153. this._currentInstanceLocations.push(order);
  13154. this._currentInstanceBuffers.push(buffer);
  13155. }
  13156. }
  13157. }
  13158. }
  13159. }
  13160. };
  13161. /**
  13162. * Records a vertex array object
  13163. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13164. * @param vertexBuffers defines the list of vertex buffers to store
  13165. * @param indexBuffer defines the index buffer to store
  13166. * @param effect defines the effect to store
  13167. * @returns the new vertex array object
  13168. */
  13169. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13170. var vao = this._gl.createVertexArray();
  13171. this._vaoRecordInProgress = true;
  13172. this._gl.bindVertexArray(vao);
  13173. this._mustWipeVertexAttributes = true;
  13174. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13175. this.bindIndexBuffer(indexBuffer);
  13176. this._vaoRecordInProgress = false;
  13177. this._gl.bindVertexArray(null);
  13178. return vao;
  13179. };
  13180. /**
  13181. * Bind a specific vertex array object
  13182. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13183. * @param vertexArrayObject defines the vertex array object to bind
  13184. * @param indexBuffer defines the index buffer to bind
  13185. */
  13186. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13187. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13188. this._cachedVertexArrayObject = vertexArrayObject;
  13189. this._gl.bindVertexArray(vertexArrayObject);
  13190. this._cachedVertexBuffers = null;
  13191. this._cachedIndexBuffer = null;
  13192. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13193. this._mustWipeVertexAttributes = true;
  13194. }
  13195. };
  13196. /**
  13197. * Bind webGl buffers directly to the webGL context
  13198. * @param vertexBuffer defines the vertex buffer to bind
  13199. * @param indexBuffer defines the index buffer to bind
  13200. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13201. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13202. * @param effect defines the effect associated with the vertex buffer
  13203. */
  13204. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13205. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13206. this._cachedVertexBuffers = vertexBuffer;
  13207. this._cachedEffectForVertexBuffers = effect;
  13208. var attributesCount = effect.getAttributesCount();
  13209. this._unbindVertexArrayObject();
  13210. this.unbindAllAttributes();
  13211. var offset = 0;
  13212. for (var index = 0; index < attributesCount; index++) {
  13213. if (index < vertexDeclaration.length) {
  13214. var order = effect.getAttributeLocation(index);
  13215. if (order >= 0) {
  13216. this._gl.enableVertexAttribArray(order);
  13217. this._vertexAttribArraysEnabled[order] = true;
  13218. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13219. }
  13220. offset += vertexDeclaration[index] * 4;
  13221. }
  13222. }
  13223. }
  13224. this._bindIndexBufferWithCache(indexBuffer);
  13225. };
  13226. Engine.prototype._unbindVertexArrayObject = function () {
  13227. if (!this._cachedVertexArrayObject) {
  13228. return;
  13229. }
  13230. this._cachedVertexArrayObject = null;
  13231. this._gl.bindVertexArray(null);
  13232. };
  13233. /**
  13234. * Bind a list of vertex buffers to the webGL context
  13235. * @param vertexBuffers defines the list of vertex buffers to bind
  13236. * @param indexBuffer defines the index buffer to bind
  13237. * @param effect defines the effect associated with the vertex buffers
  13238. */
  13239. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13240. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13241. this._cachedVertexBuffers = vertexBuffers;
  13242. this._cachedEffectForVertexBuffers = effect;
  13243. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13244. }
  13245. this._bindIndexBufferWithCache(indexBuffer);
  13246. };
  13247. /**
  13248. * Unbind all instance attributes
  13249. */
  13250. Engine.prototype.unbindInstanceAttributes = function () {
  13251. var boundBuffer;
  13252. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13253. var instancesBuffer = this._currentInstanceBuffers[i];
  13254. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13255. boundBuffer = instancesBuffer;
  13256. this.bindArrayBuffer(instancesBuffer);
  13257. }
  13258. var offsetLocation = this._currentInstanceLocations[i];
  13259. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13260. }
  13261. this._currentInstanceBuffers.length = 0;
  13262. this._currentInstanceLocations.length = 0;
  13263. };
  13264. /**
  13265. * Release and free the memory of a vertex array object
  13266. * @param vao defines the vertex array object to delete
  13267. */
  13268. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13269. this._gl.deleteVertexArray(vao);
  13270. };
  13271. /** @ignore */
  13272. Engine.prototype._releaseBuffer = function (buffer) {
  13273. buffer.references--;
  13274. if (buffer.references === 0) {
  13275. this._gl.deleteBuffer(buffer);
  13276. return true;
  13277. }
  13278. return false;
  13279. };
  13280. /**
  13281. * Creates a webGL buffer to use with instanciation
  13282. * @param capacity defines the size of the buffer
  13283. * @returns the webGL buffer
  13284. */
  13285. Engine.prototype.createInstancesBuffer = function (capacity) {
  13286. var buffer = this._gl.createBuffer();
  13287. if (!buffer) {
  13288. throw new Error("Unable to create instance buffer");
  13289. }
  13290. buffer.capacity = capacity;
  13291. this.bindArrayBuffer(buffer);
  13292. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13293. return buffer;
  13294. };
  13295. /**
  13296. * Delete a webGL buffer used with instanciation
  13297. * @param buffer defines the webGL buffer to delete
  13298. */
  13299. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13300. this._gl.deleteBuffer(buffer);
  13301. };
  13302. /**
  13303. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13304. * @param instancesBuffer defines the webGL buffer to update and bind
  13305. * @param data defines the data to store in the buffer
  13306. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13307. */
  13308. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13309. this.bindArrayBuffer(instancesBuffer);
  13310. if (data) {
  13311. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13312. }
  13313. if (offsetLocations[0].index !== undefined) {
  13314. var stride = 0;
  13315. for (var i = 0; i < offsetLocations.length; i++) {
  13316. var ai = offsetLocations[i];
  13317. stride += ai.attributeSize * 4;
  13318. }
  13319. for (var i = 0; i < offsetLocations.length; i++) {
  13320. var ai = offsetLocations[i];
  13321. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13322. this._gl.enableVertexAttribArray(ai.index);
  13323. this._vertexAttribArraysEnabled[ai.index] = true;
  13324. }
  13325. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13326. this._gl.vertexAttribDivisor(ai.index, 1);
  13327. this._currentInstanceLocations.push(ai.index);
  13328. this._currentInstanceBuffers.push(instancesBuffer);
  13329. }
  13330. }
  13331. else {
  13332. for (var index = 0; index < 4; index++) {
  13333. var offsetLocation = offsetLocations[index];
  13334. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13335. this._gl.enableVertexAttribArray(offsetLocation);
  13336. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13337. }
  13338. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13339. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13340. this._currentInstanceLocations.push(offsetLocation);
  13341. this._currentInstanceBuffers.push(instancesBuffer);
  13342. }
  13343. }
  13344. };
  13345. /**
  13346. * Apply all cached states (depth, culling, stencil and alpha)
  13347. */
  13348. Engine.prototype.applyStates = function () {
  13349. this._depthCullingState.apply(this._gl);
  13350. this._stencilState.apply(this._gl);
  13351. this._alphaState.apply(this._gl);
  13352. };
  13353. /**
  13354. * Send a draw order
  13355. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13356. * @param indexStart defines the starting index
  13357. * @param indexCount defines the number of index to draw
  13358. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13359. */
  13360. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13361. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13362. };
  13363. /**
  13364. * Draw a list of points
  13365. * @param verticesStart defines the index of first vertex to draw
  13366. * @param verticesCount defines the count of vertices to draw
  13367. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13368. */
  13369. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13370. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13371. };
  13372. /**
  13373. * Draw a list of unindexed primitives
  13374. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13375. * @param verticesStart defines the index of first vertex to draw
  13376. * @param verticesCount defines the count of vertices to draw
  13377. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13378. */
  13379. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13380. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13381. };
  13382. /**
  13383. * Draw a list of indexed primitives
  13384. * @param fillMode defines the primitive to use
  13385. * @param indexStart defines the starting index
  13386. * @param indexCount defines the number of index to draw
  13387. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13388. */
  13389. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13390. // Apply states
  13391. this.applyStates();
  13392. this._drawCalls.addCount(1, false);
  13393. // Render
  13394. var drawMode = this._drawMode(fillMode);
  13395. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13396. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13397. if (instancesCount) {
  13398. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13399. }
  13400. else {
  13401. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13402. }
  13403. };
  13404. /**
  13405. * Draw a list of unindexed primitives
  13406. * @param fillMode defines the primitive to use
  13407. * @param verticesStart defines the index of first vertex to draw
  13408. * @param verticesCount defines the count of vertices to draw
  13409. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13410. */
  13411. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13412. // Apply states
  13413. this.applyStates();
  13414. this._drawCalls.addCount(1, false);
  13415. var drawMode = this._drawMode(fillMode);
  13416. if (instancesCount) {
  13417. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13418. }
  13419. else {
  13420. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13421. }
  13422. };
  13423. Engine.prototype._drawMode = function (fillMode) {
  13424. switch (fillMode) {
  13425. // Triangle views
  13426. case BABYLON.Material.TriangleFillMode:
  13427. return this._gl.TRIANGLES;
  13428. case BABYLON.Material.PointFillMode:
  13429. return this._gl.POINTS;
  13430. case BABYLON.Material.WireFrameFillMode:
  13431. return this._gl.LINES;
  13432. // Draw modes
  13433. case BABYLON.Material.PointListDrawMode:
  13434. return this._gl.POINTS;
  13435. case BABYLON.Material.LineListDrawMode:
  13436. return this._gl.LINES;
  13437. case BABYLON.Material.LineLoopDrawMode:
  13438. return this._gl.LINE_LOOP;
  13439. case BABYLON.Material.LineStripDrawMode:
  13440. return this._gl.LINE_STRIP;
  13441. case BABYLON.Material.TriangleStripDrawMode:
  13442. return this._gl.TRIANGLE_STRIP;
  13443. case BABYLON.Material.TriangleFanDrawMode:
  13444. return this._gl.TRIANGLE_FAN;
  13445. default:
  13446. return this._gl.TRIANGLES;
  13447. }
  13448. };
  13449. // Shaders
  13450. /** @ignore */
  13451. Engine.prototype._releaseEffect = function (effect) {
  13452. if (this._compiledEffects[effect._key]) {
  13453. delete this._compiledEffects[effect._key];
  13454. this._deleteProgram(effect.getProgram());
  13455. }
  13456. };
  13457. /** @ignore */
  13458. Engine.prototype._deleteProgram = function (program) {
  13459. if (program) {
  13460. program.__SPECTOR_rebuildProgram = null;
  13461. if (program.transformFeedback) {
  13462. this.deleteTransformFeedback(program.transformFeedback);
  13463. program.transformFeedback = null;
  13464. }
  13465. this._gl.deleteProgram(program);
  13466. }
  13467. };
  13468. /**
  13469. * Create a new effect (used to store vertex/fragment shaders)
  13470. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13471. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13472. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13473. * @param samplers defines an array of string used to represent textures
  13474. * @param defines defines the string containing the defines to use to compile the shaders
  13475. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13476. * @param onCompiled defines a function to call when the effect creation is successful
  13477. * @param onError defines a function to call when the effect creation has failed
  13478. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13479. * @returns the new Effect
  13480. */
  13481. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13482. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13483. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13484. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13485. if (this._compiledEffects[name]) {
  13486. var compiledEffect = this._compiledEffects[name];
  13487. if (onCompiled && compiledEffect.isReady()) {
  13488. onCompiled(compiledEffect);
  13489. }
  13490. return compiledEffect;
  13491. }
  13492. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13493. effect._key = name;
  13494. this._compiledEffects[name] = effect;
  13495. return effect;
  13496. };
  13497. /**
  13498. * Create an effect to use with particle systems
  13499. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13500. * @param uniformsNames defines a list of attribute names
  13501. * @param samplers defines an array of string used to represent textures
  13502. * @param defines defines the string containing the defines to use to compile the shaders
  13503. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13504. * @param onCompiled defines a function to call when the effect creation is successful
  13505. * @param onError defines a function to call when the effect creation has failed
  13506. * @returns the new Effect
  13507. */
  13508. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13509. if (uniformsNames === void 0) { uniformsNames = []; }
  13510. if (samplers === void 0) { samplers = []; }
  13511. if (defines === void 0) { defines = ""; }
  13512. return this.createEffect({
  13513. vertex: "particles",
  13514. fragmentElement: fragmentName
  13515. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13516. };
  13517. /**
  13518. * Directly creates a webGL program
  13519. * @param vertexCode defines the vertex shader code to use
  13520. * @param fragmentCode defines the fragment shader code to use
  13521. * @param context defines the webGL context to use (if not set, the current one will be used)
  13522. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13523. * @returns the new webGL program
  13524. */
  13525. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13526. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13527. context = context || this._gl;
  13528. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13529. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13530. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13531. };
  13532. /**
  13533. * Creates a webGL program
  13534. * @param vertexCode defines the vertex shader code to use
  13535. * @param fragmentCode defines the fragment shader code to use
  13536. * @param defines defines the string containing the defines to use to compile the shaders
  13537. * @param context defines the webGL context to use (if not set, the current one will be used)
  13538. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13539. * @returns the new webGL program
  13540. */
  13541. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13542. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13543. context = context || this._gl;
  13544. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13545. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13546. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13547. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13548. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13549. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13550. return program;
  13551. };
  13552. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13553. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13554. var shaderProgram = context.createProgram();
  13555. if (!shaderProgram) {
  13556. throw new Error("Unable to create program");
  13557. }
  13558. context.attachShader(shaderProgram, vertexShader);
  13559. context.attachShader(shaderProgram, fragmentShader);
  13560. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13561. var transformFeedback = this.createTransformFeedback();
  13562. this.bindTransformFeedback(transformFeedback);
  13563. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13564. shaderProgram.transformFeedback = transformFeedback;
  13565. }
  13566. context.linkProgram(shaderProgram);
  13567. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13568. this.bindTransformFeedback(null);
  13569. }
  13570. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13571. if (!linked) {
  13572. context.validateProgram(shaderProgram);
  13573. var error = context.getProgramInfoLog(shaderProgram);
  13574. if (error) {
  13575. throw new Error(error);
  13576. }
  13577. }
  13578. context.deleteShader(vertexShader);
  13579. context.deleteShader(fragmentShader);
  13580. return shaderProgram;
  13581. };
  13582. /**
  13583. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13584. * @param shaderProgram defines the webGL program to use
  13585. * @param uniformsNames defines the list of uniform names
  13586. * @returns an array of webGL uniform locations
  13587. */
  13588. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13589. var results = new Array();
  13590. for (var index = 0; index < uniformsNames.length; index++) {
  13591. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13592. }
  13593. return results;
  13594. };
  13595. /**
  13596. * Gets the lsit of active attributes for a given webGL program
  13597. * @param shaderProgram defines the webGL program to use
  13598. * @param attributesNames defines the list of attribute names to get
  13599. * @returns an array of indices indicating the offset of each attribute
  13600. */
  13601. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13602. var results = [];
  13603. for (var index = 0; index < attributesNames.length; index++) {
  13604. try {
  13605. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13606. }
  13607. catch (e) {
  13608. results.push(-1);
  13609. }
  13610. }
  13611. return results;
  13612. };
  13613. /**
  13614. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13615. * @param effect defines the effect to activate
  13616. */
  13617. Engine.prototype.enableEffect = function (effect) {
  13618. if (!effect) {
  13619. return;
  13620. }
  13621. // Use program
  13622. this.bindSamplers(effect);
  13623. this._currentEffect = effect;
  13624. if (effect.onBind) {
  13625. effect.onBind(effect);
  13626. }
  13627. effect.onBindObservable.notifyObservers(effect);
  13628. };
  13629. /**
  13630. * Set the value of an uniform to an array of int32
  13631. * @param uniform defines the webGL uniform location where to store the value
  13632. * @param array defines the array of int32 to store
  13633. */
  13634. Engine.prototype.setIntArray = function (uniform, array) {
  13635. if (!uniform)
  13636. return;
  13637. this._gl.uniform1iv(uniform, array);
  13638. };
  13639. /**
  13640. * Set the value of an uniform to an array of int32 (stored as vec2)
  13641. * @param uniform defines the webGL uniform location where to store the value
  13642. * @param array defines the array of int32 to store
  13643. */
  13644. Engine.prototype.setIntArray2 = function (uniform, array) {
  13645. if (!uniform || array.length % 2 !== 0)
  13646. return;
  13647. this._gl.uniform2iv(uniform, array);
  13648. };
  13649. /**
  13650. * Set the value of an uniform to an array of int32 (stored as vec3)
  13651. * @param uniform defines the webGL uniform location where to store the value
  13652. * @param array defines the array of int32 to store
  13653. */
  13654. Engine.prototype.setIntArray3 = function (uniform, array) {
  13655. if (!uniform || array.length % 3 !== 0)
  13656. return;
  13657. this._gl.uniform3iv(uniform, array);
  13658. };
  13659. /**
  13660. * Set the value of an uniform to an array of int32 (stored as vec4)
  13661. * @param uniform defines the webGL uniform location where to store the value
  13662. * @param array defines the array of int32 to store
  13663. */
  13664. Engine.prototype.setIntArray4 = function (uniform, array) {
  13665. if (!uniform || array.length % 4 !== 0)
  13666. return;
  13667. this._gl.uniform4iv(uniform, array);
  13668. };
  13669. /**
  13670. * Set the value of an uniform to an array of float32
  13671. * @param uniform defines the webGL uniform location where to store the value
  13672. * @param array defines the array of float32 to store
  13673. */
  13674. Engine.prototype.setFloatArray = function (uniform, array) {
  13675. if (!uniform)
  13676. return;
  13677. this._gl.uniform1fv(uniform, array);
  13678. };
  13679. /**
  13680. * Set the value of an uniform to an array of float32 (stored as vec2)
  13681. * @param uniform defines the webGL uniform location where to store the value
  13682. * @param array defines the array of float32 to store
  13683. */
  13684. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13685. if (!uniform || array.length % 2 !== 0)
  13686. return;
  13687. this._gl.uniform2fv(uniform, array);
  13688. };
  13689. /**
  13690. * Set the value of an uniform to an array of float32 (stored as vec3)
  13691. * @param uniform defines the webGL uniform location where to store the value
  13692. * @param array defines the array of float32 to store
  13693. */
  13694. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13695. if (!uniform || array.length % 3 !== 0)
  13696. return;
  13697. this._gl.uniform3fv(uniform, array);
  13698. };
  13699. /**
  13700. * Set the value of an uniform to an array of float32 (stored as vec4)
  13701. * @param uniform defines the webGL uniform location where to store the value
  13702. * @param array defines the array of float32 to store
  13703. */
  13704. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13705. if (!uniform || array.length % 4 !== 0)
  13706. return;
  13707. this._gl.uniform4fv(uniform, array);
  13708. };
  13709. /**
  13710. * Set the value of an uniform to an array of number
  13711. * @param uniform defines the webGL uniform location where to store the value
  13712. * @param array defines the array of number to store
  13713. */
  13714. Engine.prototype.setArray = function (uniform, array) {
  13715. if (!uniform)
  13716. return;
  13717. this._gl.uniform1fv(uniform, array);
  13718. };
  13719. /**
  13720. * Set the value of an uniform to an array of number (stored as vec2)
  13721. * @param uniform defines the webGL uniform location where to store the value
  13722. * @param array defines the array of number to store
  13723. */
  13724. Engine.prototype.setArray2 = function (uniform, array) {
  13725. if (!uniform || array.length % 2 !== 0)
  13726. return;
  13727. this._gl.uniform2fv(uniform, array);
  13728. };
  13729. /**
  13730. * Set the value of an uniform to an array of number (stored as vec3)
  13731. * @param uniform defines the webGL uniform location where to store the value
  13732. * @param array defines the array of number to store
  13733. */
  13734. Engine.prototype.setArray3 = function (uniform, array) {
  13735. if (!uniform || array.length % 3 !== 0)
  13736. return;
  13737. this._gl.uniform3fv(uniform, array);
  13738. };
  13739. /**
  13740. * Set the value of an uniform to an array of number (stored as vec4)
  13741. * @param uniform defines the webGL uniform location where to store the value
  13742. * @param array defines the array of number to store
  13743. */
  13744. Engine.prototype.setArray4 = function (uniform, array) {
  13745. if (!uniform || array.length % 4 !== 0)
  13746. return;
  13747. this._gl.uniform4fv(uniform, array);
  13748. };
  13749. /**
  13750. * Set the value of an uniform to an array of float32 (stored as matrices)
  13751. * @param uniform defines the webGL uniform location where to store the value
  13752. * @param matrices defines the array of float32 to store
  13753. */
  13754. Engine.prototype.setMatrices = function (uniform, matrices) {
  13755. if (!uniform)
  13756. return;
  13757. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13758. };
  13759. /**
  13760. * Set the value of an uniform to a matrix
  13761. * @param uniform defines the webGL uniform location where to store the value
  13762. * @param matrix defines the matrix to store
  13763. */
  13764. Engine.prototype.setMatrix = function (uniform, matrix) {
  13765. if (!uniform)
  13766. return;
  13767. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13768. };
  13769. /**
  13770. * Set the value of an uniform to a matrix (3x3)
  13771. * @param uniform defines the webGL uniform location where to store the value
  13772. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13773. */
  13774. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13775. if (!uniform)
  13776. return;
  13777. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13778. };
  13779. /**
  13780. * Set the value of an uniform to a matrix (2x2)
  13781. * @param uniform defines the webGL uniform location where to store the value
  13782. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13783. */
  13784. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13785. if (!uniform)
  13786. return;
  13787. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13788. };
  13789. /**
  13790. * Set the value of an uniform to a number (int)
  13791. * @param uniform defines the webGL uniform location where to store the value
  13792. * @param value defines the int number to store
  13793. */
  13794. Engine.prototype.setInt = function (uniform, value) {
  13795. if (!uniform)
  13796. return;
  13797. this._gl.uniform1i(uniform, value);
  13798. };
  13799. /**
  13800. * Set the value of an uniform to a number (float)
  13801. * @param uniform defines the webGL uniform location where to store the value
  13802. * @param value defines the float number to store
  13803. */
  13804. Engine.prototype.setFloat = function (uniform, value) {
  13805. if (!uniform)
  13806. return;
  13807. this._gl.uniform1f(uniform, value);
  13808. };
  13809. /**
  13810. * Set the value of an uniform to a vec2
  13811. * @param uniform defines the webGL uniform location where to store the value
  13812. * @param x defines the 1st component of the value
  13813. * @param y defines the 2nd component of the value
  13814. */
  13815. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13816. if (!uniform)
  13817. return;
  13818. this._gl.uniform2f(uniform, x, y);
  13819. };
  13820. /**
  13821. * Set the value of an uniform to a vec3
  13822. * @param uniform defines the webGL uniform location where to store the value
  13823. * @param x defines the 1st component of the value
  13824. * @param y defines the 2nd component of the value
  13825. * @param z defines the 3rd component of the value
  13826. */
  13827. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13828. if (!uniform)
  13829. return;
  13830. this._gl.uniform3f(uniform, x, y, z);
  13831. };
  13832. /**
  13833. * Set the value of an uniform to a boolean
  13834. * @param uniform defines the webGL uniform location where to store the value
  13835. * @param bool defines the boolean to store
  13836. */
  13837. Engine.prototype.setBool = function (uniform, bool) {
  13838. if (!uniform)
  13839. return;
  13840. this._gl.uniform1i(uniform, bool);
  13841. };
  13842. /**
  13843. * Set the value of an uniform to a vec4
  13844. * @param uniform defines the webGL uniform location where to store the value
  13845. * @param x defines the 1st component of the value
  13846. * @param y defines the 2nd component of the value
  13847. * @param z defines the 3rd component of the value
  13848. * @param w defines the 4th component of the value
  13849. */
  13850. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13851. if (!uniform)
  13852. return;
  13853. this._gl.uniform4f(uniform, x, y, z, w);
  13854. };
  13855. /**
  13856. * Set the value of an uniform to a Color3
  13857. * @param uniform defines the webGL uniform location where to store the value
  13858. * @param color3 defines the color to store
  13859. */
  13860. Engine.prototype.setColor3 = function (uniform, color3) {
  13861. if (!uniform)
  13862. return;
  13863. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13864. };
  13865. /**
  13866. * Set the value of an uniform to a Color3 and an alpha value
  13867. * @param uniform defines the webGL uniform location where to store the value
  13868. * @param color3 defines the color to store
  13869. * @param alpha defines the alpha component to store
  13870. */
  13871. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13872. if (!uniform)
  13873. return;
  13874. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13875. };
  13876. /**
  13877. * Sets a Color4 on a uniform variable
  13878. * @param uniform defines the uniform location
  13879. * @param color4 defines the value to be set
  13880. */
  13881. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13882. if (!uniform)
  13883. return;
  13884. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13885. };
  13886. // States
  13887. /**
  13888. * Set various states to the webGL context
  13889. * @param culling defines backface culling state
  13890. * @param zOffset defines the value to apply to zOffset (0 by default)
  13891. * @param force defines if states must be applied even if cache is up to date
  13892. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13893. */
  13894. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13895. if (zOffset === void 0) { zOffset = 0; }
  13896. if (reverseSide === void 0) { reverseSide = false; }
  13897. // Culling
  13898. if (this._depthCullingState.cull !== culling || force) {
  13899. this._depthCullingState.cull = culling;
  13900. }
  13901. // Cull face
  13902. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13903. if (this._depthCullingState.cullFace !== cullFace || force) {
  13904. this._depthCullingState.cullFace = cullFace;
  13905. }
  13906. // Z offset
  13907. this.setZOffset(zOffset);
  13908. // Front face
  13909. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13910. if (this._depthCullingState.frontFace !== frontFace || force) {
  13911. this._depthCullingState.frontFace = frontFace;
  13912. }
  13913. };
  13914. /**
  13915. * Set the z offset to apply to current rendering
  13916. * @param value defines the offset to apply
  13917. */
  13918. Engine.prototype.setZOffset = function (value) {
  13919. this._depthCullingState.zOffset = value;
  13920. };
  13921. /**
  13922. * Gets the current value of the zOffset
  13923. * @returns the current zOffset state
  13924. */
  13925. Engine.prototype.getZOffset = function () {
  13926. return this._depthCullingState.zOffset;
  13927. };
  13928. /**
  13929. * Enable or disable depth buffering
  13930. * @param enable defines the state to set
  13931. */
  13932. Engine.prototype.setDepthBuffer = function (enable) {
  13933. this._depthCullingState.depthTest = enable;
  13934. };
  13935. /**
  13936. * Gets a boolean indicating if depth writing is enabled
  13937. * @returns the current depth writing state
  13938. */
  13939. Engine.prototype.getDepthWrite = function () {
  13940. return this._depthCullingState.depthMask;
  13941. };
  13942. /**
  13943. * Enable or disable depth writing
  13944. * @param enable defines the state to set
  13945. */
  13946. Engine.prototype.setDepthWrite = function (enable) {
  13947. this._depthCullingState.depthMask = enable;
  13948. };
  13949. /**
  13950. * Enable or disable color writing
  13951. * @param enable defines the state to set
  13952. */
  13953. Engine.prototype.setColorWrite = function (enable) {
  13954. this._gl.colorMask(enable, enable, enable, enable);
  13955. this._colorWrite = enable;
  13956. };
  13957. /**
  13958. * Gets a boolean indicating if color writing is enabled
  13959. * @returns the current color writing state
  13960. */
  13961. Engine.prototype.getColorWrite = function () {
  13962. return this._colorWrite;
  13963. };
  13964. /**
  13965. * Sets alpha constants used by some alpha blending modes
  13966. * @param r defines the red component
  13967. * @param g defines the green component
  13968. * @param b defines the blue component
  13969. * @param a defines the alpha component
  13970. */
  13971. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13972. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13973. };
  13974. /**
  13975. * Sets the current alpha mode
  13976. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  13977. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  13978. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  13979. */
  13980. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13981. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13982. if (this._alphaMode === mode) {
  13983. return;
  13984. }
  13985. switch (mode) {
  13986. case Engine.ALPHA_DISABLE:
  13987. this._alphaState.alphaBlend = false;
  13988. break;
  13989. case Engine.ALPHA_PREMULTIPLIED:
  13990. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13991. this._alphaState.alphaBlend = true;
  13992. break;
  13993. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13994. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13995. this._alphaState.alphaBlend = true;
  13996. break;
  13997. case Engine.ALPHA_COMBINE:
  13998. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13999. this._alphaState.alphaBlend = true;
  14000. break;
  14001. case Engine.ALPHA_ONEONE:
  14002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14003. this._alphaState.alphaBlend = true;
  14004. break;
  14005. case Engine.ALPHA_ADD:
  14006. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14007. this._alphaState.alphaBlend = true;
  14008. break;
  14009. case Engine.ALPHA_SUBTRACT:
  14010. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14011. this._alphaState.alphaBlend = true;
  14012. break;
  14013. case Engine.ALPHA_MULTIPLY:
  14014. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14015. this._alphaState.alphaBlend = true;
  14016. break;
  14017. case Engine.ALPHA_MAXIMIZED:
  14018. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14019. this._alphaState.alphaBlend = true;
  14020. break;
  14021. case Engine.ALPHA_INTERPOLATE:
  14022. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14023. this._alphaState.alphaBlend = true;
  14024. break;
  14025. case Engine.ALPHA_SCREENMODE:
  14026. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14027. this._alphaState.alphaBlend = true;
  14028. break;
  14029. }
  14030. if (!noDepthWriteChange) {
  14031. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14032. }
  14033. this._alphaMode = mode;
  14034. };
  14035. /**
  14036. * Gets the current alpha mode
  14037. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14038. * @returns the current alpha mode
  14039. */
  14040. Engine.prototype.getAlphaMode = function () {
  14041. return this._alphaMode;
  14042. };
  14043. // Textures
  14044. /**
  14045. * Force the entire cache to be cleared
  14046. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14047. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14048. */
  14049. Engine.prototype.wipeCaches = function (bruteForce) {
  14050. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14051. return;
  14052. }
  14053. this._currentEffect = null;
  14054. if (bruteForce) {
  14055. this.resetTextureCache();
  14056. this._currentProgram = null;
  14057. this._stencilState.reset();
  14058. this._depthCullingState.reset();
  14059. this.setDepthFunctionToLessOrEqual();
  14060. this._alphaState.reset();
  14061. }
  14062. this._resetVertexBufferBinding();
  14063. this._cachedIndexBuffer = null;
  14064. this._cachedEffectForVertexBuffers = null;
  14065. this._unbindVertexArrayObject();
  14066. this.bindIndexBuffer(null);
  14067. };
  14068. /**
  14069. * Set the compressed texture format to use, based on the formats you have, and the formats
  14070. * supported by the hardware / browser.
  14071. *
  14072. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14073. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14074. * to API arguments needed to compressed textures. This puts the burden on the container
  14075. * generator to house the arcane code for determining these for current & future formats.
  14076. *
  14077. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14078. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14079. *
  14080. * Note: The result of this call is not taken into account when a texture is base64.
  14081. *
  14082. * @param formatsAvailable defines the list of those format families you have created
  14083. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14084. *
  14085. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14086. * @returns The extension selected.
  14087. */
  14088. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14089. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14090. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14091. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14092. return this._textureFormatInUse = this._texturesSupported[i];
  14093. }
  14094. }
  14095. }
  14096. // actively set format to nothing, to allow this to be called more than once
  14097. // and possibly fail the 2nd time
  14098. this._textureFormatInUse = null;
  14099. return null;
  14100. };
  14101. /** @ignore */
  14102. Engine.prototype._createTexture = function () {
  14103. var texture = this._gl.createTexture();
  14104. if (!texture) {
  14105. throw new Error("Unable to create texture");
  14106. }
  14107. return texture;
  14108. };
  14109. /**
  14110. * Usually called from BABYLON.Texture.ts.
  14111. * Passed information to create a WebGLTexture
  14112. * @param urlArg defines a value which contains one of the following:
  14113. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14114. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14115. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14116. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14117. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14118. * @param scene needed for loading to the correct scene
  14119. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14120. * @param onLoad optional callback to be called upon successful completion
  14121. * @param onError optional callback to be called upon failure
  14122. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14123. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14124. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14125. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14126. */
  14127. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14128. var _this = this;
  14129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14130. if (onLoad === void 0) { onLoad = null; }
  14131. if (onError === void 0) { onError = null; }
  14132. if (buffer === void 0) { buffer = null; }
  14133. if (fallback === void 0) { fallback = null; }
  14134. if (format === void 0) { format = null; }
  14135. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14136. var fromData = url.substr(0, 5) === "data:";
  14137. var fromBlob = url.substr(0, 5) === "blob:";
  14138. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14139. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14140. // establish the file extension, if possible
  14141. var lastDot = url.lastIndexOf('.');
  14142. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14143. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14144. var isTGA = (extension.indexOf(".tga") === 0);
  14145. // determine if a ktx file should be substituted
  14146. var isKTX = false;
  14147. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14148. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14149. isKTX = true;
  14150. }
  14151. if (scene) {
  14152. scene._addPendingData(texture);
  14153. }
  14154. texture.url = url;
  14155. texture.generateMipMaps = !noMipmap;
  14156. texture.samplingMode = samplingMode;
  14157. texture.invertY = invertY;
  14158. if (!this._doNotHandleContextLost) {
  14159. // Keep a link to the buffer only if we plan to handle context lost
  14160. texture._buffer = buffer;
  14161. }
  14162. var onLoadObserver = null;
  14163. if (onLoad && !fallback) {
  14164. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14165. }
  14166. if (!fallback)
  14167. this._internalTexturesCache.push(texture);
  14168. var onerror = function (message, exception) {
  14169. if (scene) {
  14170. scene._removePendingData(texture);
  14171. }
  14172. if (onLoadObserver) {
  14173. texture.onLoadedObservable.remove(onLoadObserver);
  14174. }
  14175. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14176. if (isKTX) {
  14177. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14178. }
  14179. else if (BABYLON.Tools.UseFallbackTexture) {
  14180. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14181. }
  14182. if (onError) {
  14183. onError(message || "Unknown error", exception);
  14184. }
  14185. };
  14186. var callback = null;
  14187. // processing for non-image formats
  14188. if (isKTX || isTGA || isDDS) {
  14189. if (isKTX) {
  14190. callback = function (data) {
  14191. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14192. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14193. ktx.uploadLevels(_this._gl, !noMipmap);
  14194. return false;
  14195. }, samplingMode);
  14196. };
  14197. }
  14198. else if (isTGA) {
  14199. callback = function (arrayBuffer) {
  14200. var data = new Uint8Array(arrayBuffer);
  14201. var header = BABYLON.TGATools.GetTGAHeader(data);
  14202. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14203. BABYLON.TGATools.UploadContent(_this._gl, data);
  14204. return false;
  14205. }, samplingMode);
  14206. };
  14207. }
  14208. else if (isDDS) {
  14209. callback = function (data) {
  14210. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14211. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14212. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14213. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14214. return false;
  14215. }, samplingMode);
  14216. };
  14217. }
  14218. if (!buffer) {
  14219. this._loadFile(url, function (data) {
  14220. if (callback) {
  14221. callback(data);
  14222. }
  14223. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14224. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14225. });
  14226. }
  14227. else {
  14228. if (callback) {
  14229. callback(buffer);
  14230. }
  14231. }
  14232. // image format processing
  14233. }
  14234. else {
  14235. var onload = function (img) {
  14236. if (fromBlob && !_this._doNotHandleContextLost) {
  14237. // We need to store the image if we need to rebuild the texture
  14238. // in case of a webgl context lost
  14239. texture._buffer = img;
  14240. }
  14241. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14242. var gl = _this._gl;
  14243. var isPot = (img.width === potWidth && img.height === potHeight);
  14244. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14245. if (isPot) {
  14246. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14247. return false;
  14248. }
  14249. // Using shaders to rescale because canvas.drawImage is lossy
  14250. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14251. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14252. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14257. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14258. _this._releaseTexture(source);
  14259. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14260. continuationCallback();
  14261. });
  14262. return true;
  14263. }, samplingMode);
  14264. };
  14265. if (!fromData || isBase64)
  14266. if (buffer instanceof HTMLImageElement) {
  14267. onload(buffer);
  14268. }
  14269. else {
  14270. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14271. }
  14272. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14273. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14274. else
  14275. onload(buffer);
  14276. }
  14277. return texture;
  14278. };
  14279. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14280. var _this = this;
  14281. var rtt = this.createRenderTargetTexture({
  14282. width: destination.width,
  14283. height: destination.height,
  14284. }, {
  14285. generateMipMaps: false,
  14286. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14287. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14288. generateDepthBuffer: false,
  14289. generateStencilBuffer: false
  14290. });
  14291. if (!this._rescalePostProcess) {
  14292. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14293. }
  14294. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14295. _this._rescalePostProcess.onApply = function (effect) {
  14296. effect._bindTexture("textureSampler", source);
  14297. };
  14298. var hostingScene = scene;
  14299. if (!hostingScene) {
  14300. hostingScene = _this.scenes[_this.scenes.length - 1];
  14301. }
  14302. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14303. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14304. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14305. _this.unBindFramebuffer(rtt);
  14306. _this._releaseTexture(rtt);
  14307. if (onComplete) {
  14308. onComplete();
  14309. }
  14310. });
  14311. };
  14312. /**
  14313. * Update a raw texture
  14314. * @param texture defines the texture to update
  14315. * @param data defines the data to store in the texture
  14316. * @param format defines the format of the data
  14317. * @param invertY defines if data must be stored with Y axis inverted
  14318. * @param compression defines the compression used (null by default)
  14319. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14320. */
  14321. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14322. if (compression === void 0) { compression = null; }
  14323. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14324. if (!texture) {
  14325. return;
  14326. }
  14327. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14328. var internalFormat = this._getInternalFormat(format);
  14329. var textureType = this._getWebGLTextureType(type);
  14330. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14331. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14332. if (!this._doNotHandleContextLost) {
  14333. texture._bufferView = data;
  14334. texture.format = format;
  14335. texture.type = type;
  14336. texture.invertY = invertY;
  14337. texture._compression = compression;
  14338. }
  14339. if (texture.width % 4 !== 0) {
  14340. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14341. }
  14342. if (compression && data) {
  14343. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14344. }
  14345. else {
  14346. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14347. }
  14348. if (texture.generateMipMaps) {
  14349. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14350. }
  14351. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14352. // this.resetTextureCache();
  14353. texture.isReady = true;
  14354. };
  14355. /**
  14356. * Creates a raw texture
  14357. * @param data defines the data to store in the texture
  14358. * @param width defines the width of the texture
  14359. * @param height defines the height of the texture
  14360. * @param format defines the format of the data
  14361. * @param generateMipMaps defines if the engine should generate the mip levels
  14362. * @param invertY defines if data must be stored with Y axis inverted
  14363. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14364. * @param compression defines the compression used (null by default)
  14365. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14366. * @returns the raw texture inside an InternalTexture
  14367. */
  14368. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14369. if (compression === void 0) { compression = null; }
  14370. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14371. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14372. texture.baseWidth = width;
  14373. texture.baseHeight = height;
  14374. texture.width = width;
  14375. texture.height = height;
  14376. texture.format = format;
  14377. texture.generateMipMaps = generateMipMaps;
  14378. texture.samplingMode = samplingMode;
  14379. texture.invertY = invertY;
  14380. texture._compression = compression;
  14381. texture.type = type;
  14382. if (!this._doNotHandleContextLost) {
  14383. texture._bufferView = data;
  14384. }
  14385. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14386. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14387. // Filters
  14388. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14389. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14390. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14391. if (generateMipMaps) {
  14392. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14393. }
  14394. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14395. this._internalTexturesCache.push(texture);
  14396. return texture;
  14397. };
  14398. /**
  14399. * Creates a dynamic texture
  14400. * @param width defines the width of the texture
  14401. * @param height defines the height of the texture
  14402. * @param generateMipMaps defines if the engine should generate the mip levels
  14403. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14404. * @returns the dynamic texture inside an InternalTexture
  14405. */
  14406. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14407. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14408. texture.baseWidth = width;
  14409. texture.baseHeight = height;
  14410. if (generateMipMaps) {
  14411. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14412. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14413. }
  14414. // this.resetTextureCache();
  14415. texture.width = width;
  14416. texture.height = height;
  14417. texture.isReady = false;
  14418. texture.generateMipMaps = generateMipMaps;
  14419. texture.samplingMode = samplingMode;
  14420. this.updateTextureSamplingMode(samplingMode, texture);
  14421. this._internalTexturesCache.push(texture);
  14422. return texture;
  14423. };
  14424. /**
  14425. * Update the sampling mode of a given texture
  14426. * @param samplingMode defines the required sampling mode
  14427. * @param texture defines the texture to update
  14428. */
  14429. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14430. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14431. if (texture.isCube) {
  14432. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14433. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14434. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14435. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14436. }
  14437. else if (texture.is3D) {
  14438. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14439. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14440. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14441. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14442. }
  14443. else {
  14444. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14445. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14446. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14447. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14448. }
  14449. texture.samplingMode = samplingMode;
  14450. };
  14451. /**
  14452. * Update the content of a dynamic texture
  14453. * @param texture defines the texture to update
  14454. * @param canvas defines the canvas containing the source
  14455. * @param invertY defines if data must be stored with Y axis inverted
  14456. * @param premulAlpha defines if alpha is stored as premultiplied
  14457. * @param format defines the format of the data
  14458. */
  14459. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14460. if (premulAlpha === void 0) { premulAlpha = false; }
  14461. if (!texture) {
  14462. return;
  14463. }
  14464. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14465. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14466. if (premulAlpha) {
  14467. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14468. }
  14469. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14470. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14471. if (texture.generateMipMaps) {
  14472. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14473. }
  14474. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14475. if (premulAlpha) {
  14476. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14477. }
  14478. texture.isReady = true;
  14479. };
  14480. /**
  14481. * Update a video texture
  14482. * @param texture defines the texture to update
  14483. * @param video defines the video element to use
  14484. * @param invertY defines if data must be stored with Y axis inverted
  14485. */
  14486. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14487. if (!texture || texture._isDisabled) {
  14488. return;
  14489. }
  14490. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14491. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14492. try {
  14493. // Testing video texture support
  14494. if (this._videoTextureSupported === undefined) {
  14495. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14496. if (this._gl.getError() !== 0) {
  14497. this._videoTextureSupported = false;
  14498. }
  14499. else {
  14500. this._videoTextureSupported = true;
  14501. }
  14502. }
  14503. // Copy video through the current working canvas if video texture is not supported
  14504. if (!this._videoTextureSupported) {
  14505. if (!texture._workingCanvas) {
  14506. texture._workingCanvas = document.createElement("canvas");
  14507. var context = texture._workingCanvas.getContext("2d");
  14508. if (!context) {
  14509. throw new Error("Unable to get 2d context");
  14510. }
  14511. texture._workingContext = context;
  14512. texture._workingCanvas.width = texture.width;
  14513. texture._workingCanvas.height = texture.height;
  14514. }
  14515. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14516. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14517. }
  14518. else {
  14519. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14520. }
  14521. if (texture.generateMipMaps) {
  14522. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14523. }
  14524. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14525. // this.resetTextureCache();
  14526. texture.isReady = true;
  14527. }
  14528. catch (ex) {
  14529. // Something unexpected
  14530. // Let's disable the texture
  14531. texture._isDisabled = true;
  14532. }
  14533. };
  14534. /**
  14535. * Updates a depth texture Comparison Mode and Function.
  14536. * If the comparison Function is equal to 0, the mode will be set to none.
  14537. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14538. * @param texture The texture to set the comparison function for
  14539. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14540. */
  14541. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14542. if (this.webGLVersion === 1) {
  14543. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14544. return;
  14545. }
  14546. var gl = this._gl;
  14547. if (texture.isCube) {
  14548. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14549. if (comparisonFunction === 0) {
  14550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14552. }
  14553. else {
  14554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14556. }
  14557. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14558. }
  14559. else {
  14560. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14561. if (comparisonFunction === 0) {
  14562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14564. }
  14565. else {
  14566. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14568. }
  14569. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14570. }
  14571. texture._comparisonFunction = comparisonFunction;
  14572. };
  14573. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14574. var width = size.width || size;
  14575. var height = size.height || size;
  14576. internalTexture.baseWidth = width;
  14577. internalTexture.baseHeight = height;
  14578. internalTexture.width = width;
  14579. internalTexture.height = height;
  14580. internalTexture.isReady = true;
  14581. internalTexture.samples = 1;
  14582. internalTexture.generateMipMaps = false;
  14583. internalTexture._generateDepthBuffer = true;
  14584. internalTexture._generateStencilBuffer = generateStencil;
  14585. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14586. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14587. internalTexture._comparisonFunction = comparisonFunction;
  14588. var gl = this._gl;
  14589. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14590. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14591. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14592. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14593. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14594. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14595. if (comparisonFunction === 0) {
  14596. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14597. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14598. }
  14599. else {
  14600. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14601. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14602. }
  14603. };
  14604. /**
  14605. * Creates a depth stencil texture.
  14606. * This is only available in WebGL 2 or with the depth texture extension available.
  14607. * @param size The size of face edge in the texture.
  14608. * @param options The options defining the texture.
  14609. * @returns The texture
  14610. */
  14611. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14612. if (options.isCube) {
  14613. var width = size.width || size;
  14614. return this._createDepthStencilCubeTexture(width, options);
  14615. }
  14616. else {
  14617. return this._createDepthStencilTexture(size, options);
  14618. }
  14619. };
  14620. /**
  14621. * Creates a depth stencil texture.
  14622. * This is only available in WebGL 2 or with the depth texture extension available.
  14623. * @param size The size of face edge in the texture.
  14624. * @param options The options defining the texture.
  14625. * @returns The texture
  14626. */
  14627. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14628. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14629. if (!this._caps.depthTextureExtension) {
  14630. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14631. return internalTexture;
  14632. }
  14633. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14634. var gl = this._gl;
  14635. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14636. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14637. if (this.webGLVersion > 1) {
  14638. if (internalOptions.generateStencil) {
  14639. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14640. }
  14641. else {
  14642. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14643. }
  14644. }
  14645. else {
  14646. if (internalOptions.generateStencil) {
  14647. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14648. }
  14649. else {
  14650. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14651. }
  14652. }
  14653. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14654. return internalTexture;
  14655. };
  14656. /**
  14657. * Creates a depth stencil cube texture.
  14658. * This is only available in WebGL 2.
  14659. * @param size The size of face edge in the cube texture.
  14660. * @param options The options defining the cube texture.
  14661. * @returns The cube texture
  14662. */
  14663. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14664. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14665. internalTexture.isCube = true;
  14666. if (this.webGLVersion === 1) {
  14667. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14668. return internalTexture;
  14669. }
  14670. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14671. var gl = this._gl;
  14672. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14673. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14674. // Create the depth/stencil buffer
  14675. for (var face = 0; face < 6; face++) {
  14676. if (internalOptions.generateStencil) {
  14677. 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);
  14678. }
  14679. else {
  14680. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14681. }
  14682. }
  14683. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14684. return internalTexture;
  14685. };
  14686. /**
  14687. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14688. * @param renderTarget The render target to set the frame buffer for
  14689. */
  14690. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14691. // Create the framebuffer
  14692. var internalTexture = renderTarget.getInternalTexture();
  14693. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14694. return;
  14695. }
  14696. var gl = this._gl;
  14697. var depthStencilTexture = renderTarget.depthStencilTexture;
  14698. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14699. if (depthStencilTexture.isCube) {
  14700. if (depthStencilTexture._generateStencilBuffer) {
  14701. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14702. }
  14703. else {
  14704. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14705. }
  14706. }
  14707. else {
  14708. if (depthStencilTexture._generateStencilBuffer) {
  14709. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14710. }
  14711. else {
  14712. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14713. }
  14714. }
  14715. this.bindUnboundFramebuffer(null);
  14716. };
  14717. /**
  14718. * Creates a new render target texture
  14719. * @param size defines the size of the texture
  14720. * @param options defines the options used to create the texture
  14721. * @returns a new render target texture stored in an InternalTexture
  14722. */
  14723. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14724. var fullOptions = new RenderTargetCreationOptions();
  14725. if (options !== undefined && typeof options === "object") {
  14726. fullOptions.generateMipMaps = options.generateMipMaps;
  14727. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14728. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14729. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14730. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14731. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14732. }
  14733. else {
  14734. fullOptions.generateMipMaps = options;
  14735. fullOptions.generateDepthBuffer = true;
  14736. fullOptions.generateStencilBuffer = false;
  14737. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14738. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14739. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14740. }
  14741. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14742. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14743. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14744. }
  14745. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14746. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14747. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14748. }
  14749. var gl = this._gl;
  14750. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14751. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14752. var width = size.width || size;
  14753. var height = size.height || size;
  14754. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14755. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14756. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14757. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14758. }
  14759. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14760. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14763. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14764. // Create the framebuffer
  14765. var framebuffer = gl.createFramebuffer();
  14766. this.bindUnboundFramebuffer(framebuffer);
  14767. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14768. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14769. if (fullOptions.generateMipMaps) {
  14770. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14771. }
  14772. // Unbind
  14773. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14774. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14775. this.bindUnboundFramebuffer(null);
  14776. texture._framebuffer = framebuffer;
  14777. texture.baseWidth = width;
  14778. texture.baseHeight = height;
  14779. texture.width = width;
  14780. texture.height = height;
  14781. texture.isReady = true;
  14782. texture.samples = 1;
  14783. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14784. texture.samplingMode = fullOptions.samplingMode;
  14785. texture.type = fullOptions.type;
  14786. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14787. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14788. // this.resetTextureCache();
  14789. this._internalTexturesCache.push(texture);
  14790. return texture;
  14791. };
  14792. /**
  14793. * Create a multi render target texture
  14794. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14795. * @param size defines the size of the texture
  14796. * @param options defines the creation options
  14797. * @returns the cube texture as an InternalTexture
  14798. */
  14799. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14800. var generateMipMaps = false;
  14801. var generateDepthBuffer = true;
  14802. var generateStencilBuffer = false;
  14803. var generateDepthTexture = false;
  14804. var textureCount = 1;
  14805. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14806. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14807. var types = new Array();
  14808. var samplingModes = new Array();
  14809. if (options !== undefined) {
  14810. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14811. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14812. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14813. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14814. textureCount = options.textureCount || 1;
  14815. if (options.types) {
  14816. types = options.types;
  14817. }
  14818. if (options.samplingModes) {
  14819. samplingModes = options.samplingModes;
  14820. }
  14821. }
  14822. var gl = this._gl;
  14823. // Create the framebuffer
  14824. var framebuffer = gl.createFramebuffer();
  14825. this.bindUnboundFramebuffer(framebuffer);
  14826. var width = size.width || size;
  14827. var height = size.height || size;
  14828. var textures = [];
  14829. var attachments = [];
  14830. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14831. for (var i = 0; i < textureCount; i++) {
  14832. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14833. var type = types[i] || defaultType;
  14834. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14835. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14836. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14837. }
  14838. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14839. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14840. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14841. }
  14842. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14843. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14844. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14845. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14846. }
  14847. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14848. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14849. textures.push(texture);
  14850. attachments.push(attachment);
  14851. gl.activeTexture(gl["TEXTURE" + i]);
  14852. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14857. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14858. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14859. if (generateMipMaps) {
  14860. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14861. }
  14862. // Unbind
  14863. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14864. texture._framebuffer = framebuffer;
  14865. texture._depthStencilBuffer = depthStencilBuffer;
  14866. texture.baseWidth = width;
  14867. texture.baseHeight = height;
  14868. texture.width = width;
  14869. texture.height = height;
  14870. texture.isReady = true;
  14871. texture.samples = 1;
  14872. texture.generateMipMaps = generateMipMaps;
  14873. texture.samplingMode = samplingMode;
  14874. texture.type = type;
  14875. texture._generateDepthBuffer = generateDepthBuffer;
  14876. texture._generateStencilBuffer = generateStencilBuffer;
  14877. texture._attachments = attachments;
  14878. this._internalTexturesCache.push(texture);
  14879. }
  14880. if (generateDepthTexture && this._caps.depthTextureExtension) {
  14881. // Depth texture
  14882. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14883. gl.activeTexture(gl.TEXTURE0);
  14884. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  14885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14886. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14889. 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);
  14890. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  14891. depthTexture._framebuffer = framebuffer;
  14892. depthTexture.baseWidth = width;
  14893. depthTexture.baseHeight = height;
  14894. depthTexture.width = width;
  14895. depthTexture.height = height;
  14896. depthTexture.isReady = true;
  14897. depthTexture.samples = 1;
  14898. depthTexture.generateMipMaps = generateMipMaps;
  14899. depthTexture.samplingMode = gl.NEAREST;
  14900. depthTexture._generateDepthBuffer = generateDepthBuffer;
  14901. depthTexture._generateStencilBuffer = generateStencilBuffer;
  14902. textures.push(depthTexture);
  14903. this._internalTexturesCache.push(depthTexture);
  14904. }
  14905. gl.drawBuffers(attachments);
  14906. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14907. this.bindUnboundFramebuffer(null);
  14908. this.resetTextureCache();
  14909. return textures;
  14910. };
  14911. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  14912. if (samples === void 0) { samples = 1; }
  14913. var depthStencilBuffer = null;
  14914. var gl = this._gl;
  14915. // Create the depth/stencil buffer
  14916. if (generateStencilBuffer) {
  14917. depthStencilBuffer = gl.createRenderbuffer();
  14918. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14919. if (samples > 1) {
  14920. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  14921. }
  14922. else {
  14923. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  14924. }
  14925. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14926. }
  14927. else if (generateDepthBuffer) {
  14928. depthStencilBuffer = gl.createRenderbuffer();
  14929. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14930. if (samples > 1) {
  14931. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  14932. }
  14933. else {
  14934. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  14935. }
  14936. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14937. }
  14938. return depthStencilBuffer;
  14939. };
  14940. /**
  14941. * Updates the sample count of a render target texture
  14942. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14943. * @param texture defines the texture to update
  14944. * @param samples defines the sample count to set
  14945. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14946. */
  14947. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  14948. if (this.webGLVersion < 2 || !texture) {
  14949. return 1;
  14950. }
  14951. if (texture.samples === samples) {
  14952. return samples;
  14953. }
  14954. var gl = this._gl;
  14955. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14956. // Dispose previous render buffers
  14957. if (texture._depthStencilBuffer) {
  14958. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14959. texture._depthStencilBuffer = null;
  14960. }
  14961. if (texture._MSAAFramebuffer) {
  14962. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14963. texture._MSAAFramebuffer = null;
  14964. }
  14965. if (texture._MSAARenderBuffer) {
  14966. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14967. texture._MSAARenderBuffer = null;
  14968. }
  14969. if (samples > 1) {
  14970. var framebuffer = gl.createFramebuffer();
  14971. if (!framebuffer) {
  14972. throw new Error("Unable to create multi sampled framebuffer");
  14973. }
  14974. texture._MSAAFramebuffer = framebuffer;
  14975. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  14976. var colorRenderbuffer = gl.createRenderbuffer();
  14977. if (!colorRenderbuffer) {
  14978. throw new Error("Unable to create multi sampled framebuffer");
  14979. }
  14980. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14981. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14982. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  14983. texture._MSAARenderBuffer = colorRenderbuffer;
  14984. }
  14985. else {
  14986. this.bindUnboundFramebuffer(texture._framebuffer);
  14987. }
  14988. texture.samples = samples;
  14989. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  14990. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14991. this.bindUnboundFramebuffer(null);
  14992. return samples;
  14993. };
  14994. /**
  14995. * Update the sample count for a given multiple render target texture
  14996. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14997. * @param textures defines the textures to update
  14998. * @param samples defines the sample count to set
  14999. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15000. */
  15001. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15002. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15003. return 1;
  15004. }
  15005. if (textures[0].samples === samples) {
  15006. return samples;
  15007. }
  15008. var gl = this._gl;
  15009. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15010. // Dispose previous render buffers
  15011. if (textures[0]._depthStencilBuffer) {
  15012. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15013. textures[0]._depthStencilBuffer = null;
  15014. }
  15015. if (textures[0]._MSAAFramebuffer) {
  15016. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15017. textures[0]._MSAAFramebuffer = null;
  15018. }
  15019. for (var i = 0; i < textures.length; i++) {
  15020. if (textures[i]._MSAARenderBuffer) {
  15021. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15022. textures[i]._MSAARenderBuffer = null;
  15023. }
  15024. }
  15025. if (samples > 1) {
  15026. var framebuffer = gl.createFramebuffer();
  15027. if (!framebuffer) {
  15028. throw new Error("Unable to create multi sampled framebuffer");
  15029. }
  15030. this.bindUnboundFramebuffer(framebuffer);
  15031. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15032. var attachments = [];
  15033. for (var i = 0; i < textures.length; i++) {
  15034. var texture = textures[i];
  15035. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15036. var colorRenderbuffer = gl.createRenderbuffer();
  15037. if (!colorRenderbuffer) {
  15038. throw new Error("Unable to create multi sampled framebuffer");
  15039. }
  15040. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15041. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15042. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15043. texture._MSAAFramebuffer = framebuffer;
  15044. texture._MSAARenderBuffer = colorRenderbuffer;
  15045. texture.samples = samples;
  15046. texture._depthStencilBuffer = depthStencilBuffer;
  15047. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15048. attachments.push(attachment);
  15049. }
  15050. gl.drawBuffers(attachments);
  15051. }
  15052. else {
  15053. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15054. }
  15055. this.bindUnboundFramebuffer(null);
  15056. return samples;
  15057. };
  15058. /** @ignore */
  15059. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15060. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15061. };
  15062. /** @ignore */
  15063. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15064. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15065. };
  15066. /**
  15067. * Creates a new render target cube texture
  15068. * @param size defines the size of the texture
  15069. * @param options defines the options used to create the texture
  15070. * @returns a new render target cube texture stored in an InternalTexture
  15071. */
  15072. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15073. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15074. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15075. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15076. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15077. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15078. }
  15079. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15080. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15081. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15082. }
  15083. var gl = this._gl;
  15084. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15085. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15086. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15087. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15088. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15089. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15090. }
  15091. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15092. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15093. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15095. for (var face = 0; face < 6; face++) {
  15096. 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);
  15097. }
  15098. // Create the framebuffer
  15099. var framebuffer = gl.createFramebuffer();
  15100. this.bindUnboundFramebuffer(framebuffer);
  15101. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15102. // MipMaps
  15103. if (fullOptions.generateMipMaps) {
  15104. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15105. }
  15106. // Unbind
  15107. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15108. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15109. this.bindUnboundFramebuffer(null);
  15110. texture._framebuffer = framebuffer;
  15111. texture.width = size;
  15112. texture.height = size;
  15113. texture.isReady = true;
  15114. texture.isCube = true;
  15115. texture.samples = 1;
  15116. texture.generateMipMaps = fullOptions.generateMipMaps;
  15117. texture.samplingMode = fullOptions.samplingMode;
  15118. texture.type = fullOptions.type;
  15119. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15120. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15121. this._internalTexturesCache.push(texture);
  15122. return texture;
  15123. };
  15124. /**
  15125. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15126. * @param rootUrl defines the url where the file to load is located
  15127. * @param scene defines the current scene
  15128. * @param scale defines scale to apply to the mip map selection
  15129. * @param offset defines offset to apply to the mip map selection
  15130. * @param onLoad defines an optional callback raised when the texture is loaded
  15131. * @param onError defines an optional callback raised if there is an issue to load the texture
  15132. * @param format defines the format of the data
  15133. * @param forcedExtension defines the extension to use to pick the right loader
  15134. * @returns the cube texture as an InternalTexture
  15135. */
  15136. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15137. var _this = this;
  15138. if (onLoad === void 0) { onLoad = null; }
  15139. if (onError === void 0) { onError = null; }
  15140. if (forcedExtension === void 0) { forcedExtension = null; }
  15141. var callback = function (loadData) {
  15142. if (!loadData) {
  15143. if (onLoad) {
  15144. onLoad(null);
  15145. }
  15146. return;
  15147. }
  15148. var texture = loadData.texture;
  15149. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15150. texture._lodGenerationScale = scale;
  15151. texture._lodGenerationOffset = offset;
  15152. if (_this._caps.textureLOD) {
  15153. // Do not add extra process if texture lod is supported.
  15154. if (onLoad) {
  15155. onLoad(texture);
  15156. }
  15157. return;
  15158. }
  15159. var mipSlices = 3;
  15160. var gl = _this._gl;
  15161. var width = loadData.width;
  15162. if (!width) {
  15163. return;
  15164. }
  15165. var textures = [];
  15166. for (var i = 0; i < mipSlices; i++) {
  15167. //compute LOD from even spacing in smoothness (matching shader calculation)
  15168. var smoothness = i / (mipSlices - 1);
  15169. var roughness = 1 - smoothness;
  15170. var minLODIndex = offset; // roughness = 0
  15171. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15172. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15173. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15174. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15175. glTextureFromLod.isCube = true;
  15176. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15177. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15178. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15179. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15180. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15181. if (loadData.isDDS) {
  15182. var info = loadData.info;
  15183. var data = loadData.data;
  15184. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15185. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15186. }
  15187. else {
  15188. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15189. }
  15190. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15191. // Wrap in a base texture for easy binding.
  15192. var lodTexture = new BABYLON.BaseTexture(scene);
  15193. lodTexture.isCube = true;
  15194. lodTexture._texture = glTextureFromLod;
  15195. glTextureFromLod.isReady = true;
  15196. textures.push(lodTexture);
  15197. }
  15198. texture._lodTextureHigh = textures[2];
  15199. texture._lodTextureMid = textures[1];
  15200. texture._lodTextureLow = textures[0];
  15201. if (onLoad) {
  15202. onLoad(texture);
  15203. }
  15204. };
  15205. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15206. };
  15207. /**
  15208. * Creates a cube texture
  15209. * @param rootUrl defines the url where the files to load is located
  15210. * @param scene defines the current scene
  15211. * @param files defines the list of files to load (1 per face)
  15212. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15213. * @param onLoad defines an optional callback raised when the texture is loaded
  15214. * @param onError defines an optional callback raised if there is an issue to load the texture
  15215. * @param format defines the format of the data
  15216. * @param forcedExtension defines the extension to use to pick the right loader
  15217. * @returns the cube texture as an InternalTexture
  15218. */
  15219. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15220. var _this = this;
  15221. if (onLoad === void 0) { onLoad = null; }
  15222. if (onError === void 0) { onError = null; }
  15223. if (forcedExtension === void 0) { forcedExtension = null; }
  15224. var gl = this._gl;
  15225. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15226. texture.isCube = true;
  15227. texture.url = rootUrl;
  15228. texture.generateMipMaps = !noMipmap;
  15229. if (!this._doNotHandleContextLost) {
  15230. texture._extension = forcedExtension;
  15231. texture._files = files;
  15232. }
  15233. var isKTX = false;
  15234. var isDDS = false;
  15235. var lastDot = rootUrl.lastIndexOf('.');
  15236. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15237. if (this._textureFormatInUse) {
  15238. extension = this._textureFormatInUse;
  15239. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15240. isKTX = true;
  15241. }
  15242. else {
  15243. isDDS = (extension === ".dds");
  15244. }
  15245. var onerror = function (request, exception) {
  15246. if (onError && request) {
  15247. onError(request.status + " " + request.statusText, exception);
  15248. }
  15249. };
  15250. if (isKTX) {
  15251. this._loadFile(rootUrl, function (data) {
  15252. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15253. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15254. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15255. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15256. ktx.uploadLevels(_this._gl, !noMipmap);
  15257. _this.setCubeMapTextureParams(gl, loadMipmap);
  15258. texture.width = ktx.pixelWidth;
  15259. texture.height = ktx.pixelHeight;
  15260. texture.isReady = true;
  15261. }, undefined, undefined, true, onerror);
  15262. }
  15263. else if (isDDS) {
  15264. if (files && files.length === 6) {
  15265. this._cascadeLoadFiles(scene, function (imgs) {
  15266. var info;
  15267. var loadMipmap = false;
  15268. var width = 0;
  15269. for (var index = 0; index < imgs.length; index++) {
  15270. var data = imgs[index];
  15271. info = BABYLON.DDSTools.GetDDSInfo(data);
  15272. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15273. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15274. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15275. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15276. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15277. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15278. }
  15279. texture.width = info.width;
  15280. texture.height = info.height;
  15281. texture.type = info.textureType;
  15282. width = info.width;
  15283. }
  15284. _this.setCubeMapTextureParams(gl, loadMipmap);
  15285. texture.isReady = true;
  15286. if (onLoad) {
  15287. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15288. }
  15289. }, files, onError);
  15290. }
  15291. else {
  15292. this._loadFile(rootUrl, function (data) {
  15293. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15294. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15295. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15296. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15297. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15298. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15299. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15300. }
  15301. _this.setCubeMapTextureParams(gl, loadMipmap);
  15302. texture.width = info.width;
  15303. texture.height = info.height;
  15304. texture.isReady = true;
  15305. texture.type = info.textureType;
  15306. if (onLoad) {
  15307. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15308. }
  15309. }, undefined, undefined, true, onerror);
  15310. }
  15311. }
  15312. else {
  15313. if (!files) {
  15314. throw new Error("Cannot load cubemap because files were not defined");
  15315. }
  15316. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15317. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15318. var height = width;
  15319. _this._prepareWorkingCanvas();
  15320. if (!_this._workingCanvas || !_this._workingContext) {
  15321. return;
  15322. }
  15323. _this._workingCanvas.width = width;
  15324. _this._workingCanvas.height = height;
  15325. var faces = [
  15326. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15327. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15328. ];
  15329. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15330. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15331. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15332. for (var index = 0; index < faces.length; index++) {
  15333. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15334. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15335. }
  15336. if (!noMipmap) {
  15337. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15338. }
  15339. _this.setCubeMapTextureParams(gl, !noMipmap);
  15340. texture.width = width;
  15341. texture.height = height;
  15342. texture.isReady = true;
  15343. if (format) {
  15344. texture.format = format;
  15345. }
  15346. texture.onLoadedObservable.notifyObservers(texture);
  15347. texture.onLoadedObservable.clear();
  15348. if (onLoad) {
  15349. onLoad();
  15350. }
  15351. }, files, onError);
  15352. }
  15353. this._internalTexturesCache.push(texture);
  15354. return texture;
  15355. };
  15356. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15357. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15360. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15361. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15362. // this.resetTextureCache();
  15363. };
  15364. /**
  15365. * Update a raw cube texture
  15366. * @param texture defines the texture to udpdate
  15367. * @param data defines the data to store
  15368. * @param format defines the data format
  15369. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15370. * @param invertY defines if data must be stored with Y axis inverted
  15371. * @param compression defines the compression used (null by default)
  15372. * @param level defines which level of the texture to update
  15373. */
  15374. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15375. if (compression === void 0) { compression = null; }
  15376. if (level === void 0) { level = 0; }
  15377. texture._bufferViewArray = data;
  15378. texture.format = format;
  15379. texture.type = type;
  15380. texture.invertY = invertY;
  15381. texture._compression = compression;
  15382. var gl = this._gl;
  15383. var textureType = this._getWebGLTextureType(type);
  15384. var internalFormat = this._getInternalFormat(format);
  15385. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15386. var needConversion = false;
  15387. if (internalFormat === gl.RGB) {
  15388. internalFormat = gl.RGBA;
  15389. needConversion = true;
  15390. }
  15391. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15392. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15393. if (texture.width % 4 !== 0) {
  15394. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15395. }
  15396. // Data are known to be in +X +Y +Z -X -Y -Z
  15397. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15398. var faceData = data[faceIndex];
  15399. if (compression) {
  15400. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15401. }
  15402. else {
  15403. if (needConversion) {
  15404. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15405. }
  15406. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15407. }
  15408. }
  15409. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15410. if (isPot && texture.generateMipMaps && level === 0) {
  15411. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15412. }
  15413. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15414. // this.resetTextureCache();
  15415. texture.isReady = true;
  15416. };
  15417. /**
  15418. * Creates a new raw cube texture
  15419. * @param data defines the array of data to use to create each face
  15420. * @param size defines the size of the textures
  15421. * @param format defines the format of the data
  15422. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15423. * @param generateMipMaps defines if the engine should generate the mip levels
  15424. * @param invertY defines if data must be stored with Y axis inverted
  15425. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15426. * @param compression defines the compression used (null by default)
  15427. * @returns the cube texture as an InternalTexture
  15428. */
  15429. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15430. if (compression === void 0) { compression = null; }
  15431. var gl = this._gl;
  15432. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15433. texture.isCube = true;
  15434. texture.generateMipMaps = generateMipMaps;
  15435. texture.format = format;
  15436. texture.type = type;
  15437. if (!this._doNotHandleContextLost) {
  15438. texture._bufferViewArray = data;
  15439. }
  15440. var textureType = this._getWebGLTextureType(type);
  15441. var internalFormat = this._getInternalFormat(format);
  15442. if (internalFormat === gl.RGB) {
  15443. internalFormat = gl.RGBA;
  15444. }
  15445. var width = size;
  15446. var height = width;
  15447. texture.width = width;
  15448. texture.height = height;
  15449. // Double check on POT to generate Mips.
  15450. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15451. if (!isPot) {
  15452. generateMipMaps = false;
  15453. }
  15454. // Upload data if needed. The texture won't be ready until then.
  15455. if (data) {
  15456. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15457. }
  15458. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15459. // Filters
  15460. if (data && generateMipMaps) {
  15461. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15462. }
  15463. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15466. }
  15467. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15468. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15470. }
  15471. else {
  15472. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15473. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15474. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15475. }
  15476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15478. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15479. return texture;
  15480. };
  15481. /**
  15482. * Creates a new raw cube texture from a specified url
  15483. * @param url defines the url where the data is located
  15484. * @param scene defines the current scene
  15485. * @param size defines the size of the textures
  15486. * @param format defines the format of the data
  15487. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15488. * @param noMipmap defines if the engine should avoid generating the mip levels
  15489. * @param callback defines a callback used to extract texture data from loaded data
  15490. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15491. * @param onLoad defines a callback called when texture is loaded
  15492. * @param onError defines a callback called if there is an error
  15493. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15494. * @param invertY defines if data must be stored with Y axis inverted
  15495. * @returns the cube texture as an InternalTexture
  15496. */
  15497. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15498. var _this = this;
  15499. if (onLoad === void 0) { onLoad = null; }
  15500. if (onError === void 0) { onError = null; }
  15501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15502. if (invertY === void 0) { invertY = false; }
  15503. var gl = this._gl;
  15504. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15505. scene._addPendingData(texture);
  15506. texture.url = url;
  15507. this._internalTexturesCache.push(texture);
  15508. var onerror = function (request, exception) {
  15509. scene._removePendingData(texture);
  15510. if (onError && request) {
  15511. onError(request.status + " " + request.statusText, exception);
  15512. }
  15513. };
  15514. var internalCallback = function (data) {
  15515. var width = texture.width;
  15516. var faceDataArrays = callback(data);
  15517. if (!faceDataArrays) {
  15518. return;
  15519. }
  15520. if (mipmapGenerator) {
  15521. var textureType = _this._getWebGLTextureType(type);
  15522. var internalFormat = _this._getInternalFormat(format);
  15523. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15524. var needConversion = false;
  15525. if (internalFormat === gl.RGB) {
  15526. internalFormat = gl.RGBA;
  15527. needConversion = true;
  15528. }
  15529. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15530. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15531. var mipData = mipmapGenerator(faceDataArrays);
  15532. for (var level = 0; level < mipData.length; level++) {
  15533. var mipSize = width >> level;
  15534. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15535. var mipFaceData = mipData[level][faceIndex];
  15536. if (needConversion) {
  15537. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15538. }
  15539. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15540. }
  15541. }
  15542. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15543. }
  15544. else {
  15545. texture.generateMipMaps = !noMipmap;
  15546. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15547. }
  15548. texture.isReady = true;
  15549. // this.resetTextureCache();
  15550. scene._removePendingData(texture);
  15551. if (onLoad) {
  15552. onLoad();
  15553. }
  15554. };
  15555. this._loadFile(url, function (data) {
  15556. internalCallback(data);
  15557. }, undefined, scene.database, true, onerror);
  15558. return texture;
  15559. };
  15560. ;
  15561. /**
  15562. * Update a raw 3D texture
  15563. * @param texture defines the texture to update
  15564. * @param data defines the data to store
  15565. * @param format defines the data format
  15566. * @param invertY defines if data must be stored with Y axis inverted
  15567. * @param compression defines the used compression (can be null)
  15568. */
  15569. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15570. if (compression === void 0) { compression = null; }
  15571. var internalFormat = this._getInternalFormat(format);
  15572. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15573. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15574. if (!this._doNotHandleContextLost) {
  15575. texture._bufferView = data;
  15576. texture.format = format;
  15577. texture.invertY = invertY;
  15578. texture._compression = compression;
  15579. }
  15580. if (texture.width % 4 !== 0) {
  15581. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15582. }
  15583. if (compression && data) {
  15584. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15585. }
  15586. else {
  15587. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15588. }
  15589. if (texture.generateMipMaps) {
  15590. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15591. }
  15592. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15593. // this.resetTextureCache();
  15594. texture.isReady = true;
  15595. };
  15596. /**
  15597. * Creates a new raw 3D texture
  15598. * @param data defines the data used to create the texture
  15599. * @param width defines the width of the texture
  15600. * @param height defines the height of the texture
  15601. * @param depth defines the depth of the texture
  15602. * @param format defines the format of the texture
  15603. * @param generateMipMaps defines if the engine must generate mip levels
  15604. * @param invertY defines if data must be stored with Y axis inverted
  15605. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15606. * @param compression defines the compressed used (can be null)
  15607. * @returns a new raw 3D texture (stored in an InternalTexture)
  15608. */
  15609. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15610. if (compression === void 0) { compression = null; }
  15611. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15612. texture.baseWidth = width;
  15613. texture.baseHeight = height;
  15614. texture.baseDepth = depth;
  15615. texture.width = width;
  15616. texture.height = height;
  15617. texture.depth = depth;
  15618. texture.format = format;
  15619. texture.generateMipMaps = generateMipMaps;
  15620. texture.samplingMode = samplingMode;
  15621. texture.is3D = true;
  15622. if (!this._doNotHandleContextLost) {
  15623. texture._bufferView = data;
  15624. }
  15625. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15626. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15627. // Filters
  15628. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15629. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15630. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15631. if (generateMipMaps) {
  15632. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15633. }
  15634. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15635. this._internalTexturesCache.push(texture);
  15636. return texture;
  15637. };
  15638. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15639. var gl = this._gl;
  15640. if (!gl) {
  15641. return;
  15642. }
  15643. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15646. if (!noMipmap && !isCompressed) {
  15647. gl.generateMipmap(gl.TEXTURE_2D);
  15648. }
  15649. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15650. // this.resetTextureCache();
  15651. if (scene) {
  15652. scene._removePendingData(texture);
  15653. }
  15654. texture.onLoadedObservable.notifyObservers(texture);
  15655. texture.onLoadedObservable.clear();
  15656. };
  15657. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15658. var _this = this;
  15659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15660. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15661. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15662. var gl = this._gl;
  15663. if (!gl) {
  15664. return;
  15665. }
  15666. if (!texture._webGLTexture) {
  15667. // this.resetTextureCache();
  15668. if (scene) {
  15669. scene._removePendingData(texture);
  15670. }
  15671. return;
  15672. }
  15673. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15674. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15675. texture.baseWidth = width;
  15676. texture.baseHeight = height;
  15677. texture.width = potWidth;
  15678. texture.height = potHeight;
  15679. texture.isReady = true;
  15680. if (processFunction(potWidth, potHeight, function () {
  15681. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15682. })) {
  15683. // Returning as texture needs extra async steps
  15684. return;
  15685. }
  15686. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15687. };
  15688. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15689. // Create new RGBA data container.
  15690. var rgbaData;
  15691. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15692. rgbaData = new Float32Array(width * height * 4);
  15693. }
  15694. else {
  15695. rgbaData = new Uint32Array(width * height * 4);
  15696. }
  15697. // Convert each pixel.
  15698. for (var x = 0; x < width; x++) {
  15699. for (var y = 0; y < height; y++) {
  15700. var index = (y * width + x) * 3;
  15701. var newIndex = (y * width + x) * 4;
  15702. // Map Old Value to new value.
  15703. rgbaData[newIndex + 0] = rgbData[index + 0];
  15704. rgbaData[newIndex + 1] = rgbData[index + 1];
  15705. rgbaData[newIndex + 2] = rgbData[index + 2];
  15706. // Add fully opaque alpha channel.
  15707. rgbaData[newIndex + 3] = 1;
  15708. }
  15709. }
  15710. return rgbaData;
  15711. };
  15712. /** @ignore */
  15713. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15714. var gl = this._gl;
  15715. if (texture._framebuffer) {
  15716. gl.deleteFramebuffer(texture._framebuffer);
  15717. texture._framebuffer = null;
  15718. }
  15719. if (texture._depthStencilBuffer) {
  15720. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15721. texture._depthStencilBuffer = null;
  15722. }
  15723. if (texture._MSAAFramebuffer) {
  15724. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15725. texture._MSAAFramebuffer = null;
  15726. }
  15727. if (texture._MSAARenderBuffer) {
  15728. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15729. texture._MSAARenderBuffer = null;
  15730. }
  15731. };
  15732. /** @ignore */
  15733. Engine.prototype._releaseTexture = function (texture) {
  15734. var gl = this._gl;
  15735. this._releaseFramebufferObjects(texture);
  15736. gl.deleteTexture(texture._webGLTexture);
  15737. // Unbind channels
  15738. this.unbindAllTextures();
  15739. var index = this._internalTexturesCache.indexOf(texture);
  15740. if (index !== -1) {
  15741. this._internalTexturesCache.splice(index, 1);
  15742. }
  15743. // Integrated fixed lod samplers.
  15744. if (texture._lodTextureHigh) {
  15745. texture._lodTextureHigh.dispose();
  15746. }
  15747. if (texture._lodTextureMid) {
  15748. texture._lodTextureMid.dispose();
  15749. }
  15750. if (texture._lodTextureLow) {
  15751. texture._lodTextureLow.dispose();
  15752. }
  15753. // Set output texture of post process to null if the texture has been released/disposed
  15754. this.scenes.forEach(function (scene) {
  15755. scene.postProcesses.forEach(function (postProcess) {
  15756. if (postProcess._outputTexture == texture) {
  15757. postProcess._outputTexture = null;
  15758. }
  15759. });
  15760. scene.cameras.forEach(function (camera) {
  15761. camera._postProcesses.forEach(function (postProcess) {
  15762. if (postProcess) {
  15763. if (postProcess._outputTexture == texture) {
  15764. postProcess._outputTexture = null;
  15765. }
  15766. }
  15767. });
  15768. });
  15769. });
  15770. };
  15771. Engine.prototype.setProgram = function (program) {
  15772. if (this._currentProgram !== program) {
  15773. this._gl.useProgram(program);
  15774. this._currentProgram = program;
  15775. }
  15776. };
  15777. /**
  15778. * Binds an effect to the webGL context
  15779. * @param effect defines the effect to bind
  15780. */
  15781. Engine.prototype.bindSamplers = function (effect) {
  15782. this.setProgram(effect.getProgram());
  15783. var samplers = effect.getSamplers();
  15784. for (var index = 0; index < samplers.length; index++) {
  15785. var uniform = effect.getUniform(samplers[index]);
  15786. if (uniform) {
  15787. this._boundUniforms[index] = uniform;
  15788. }
  15789. }
  15790. this._currentEffect = null;
  15791. };
  15792. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15793. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15794. return;
  15795. }
  15796. // Remove
  15797. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15798. // Bind last to it
  15799. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15800. // Bind to dummy
  15801. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15802. };
  15803. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15804. if (!internalTexture) {
  15805. return -1;
  15806. }
  15807. internalTexture._initialSlot = channel;
  15808. if (this.disableTextureBindingOptimization) {
  15809. if (channel !== internalTexture._designatedSlot) {
  15810. this._textureCollisions.addCount(1, false);
  15811. }
  15812. }
  15813. else {
  15814. if (channel !== internalTexture._designatedSlot) {
  15815. if (internalTexture._designatedSlot > -1) {
  15816. return internalTexture._designatedSlot;
  15817. }
  15818. else {
  15819. // No slot for this texture, let's pick a new one (if we find a free slot)
  15820. if (this._nextFreeTextureSlots.length) {
  15821. return this._nextFreeTextureSlots[0];
  15822. }
  15823. // We need to recycle the oldest bound texture, sorry.
  15824. this._textureCollisions.addCount(1, false);
  15825. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15826. }
  15827. }
  15828. }
  15829. return channel;
  15830. };
  15831. Engine.prototype._linkTrackers = function (previous, next) {
  15832. previous.next = next;
  15833. next.previous = previous;
  15834. };
  15835. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15836. var currentSlot = internalTexture._designatedSlot;
  15837. if (currentSlot === -1) {
  15838. return -1;
  15839. }
  15840. internalTexture._designatedSlot = -1;
  15841. if (this.disableTextureBindingOptimization) {
  15842. return -1;
  15843. }
  15844. // Remove from bound list
  15845. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15846. // Free the slot
  15847. this._boundTexturesCache[currentSlot] = null;
  15848. this._nextFreeTextureSlots.push(currentSlot);
  15849. return currentSlot;
  15850. };
  15851. Engine.prototype._activateCurrentTexture = function () {
  15852. if (this._currentTextureChannel !== this._activeChannel) {
  15853. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15854. this._currentTextureChannel = this._activeChannel;
  15855. }
  15856. };
  15857. /** @ignore */
  15858. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  15859. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15860. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15861. this._activeChannel = texture._designatedSlot;
  15862. }
  15863. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15864. var isTextureForRendering = texture && texture._initialSlot > -1;
  15865. if (currentTextureBound !== texture) {
  15866. if (currentTextureBound) {
  15867. this._removeDesignatedSlot(currentTextureBound);
  15868. }
  15869. this._activateCurrentTexture();
  15870. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  15871. this._boundTexturesCache[this._activeChannel] = texture;
  15872. if (texture) {
  15873. if (!this.disableTextureBindingOptimization) {
  15874. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  15875. if (slotIndex > -1) {
  15876. this._nextFreeTextureSlots.splice(slotIndex, 1);
  15877. }
  15878. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  15879. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  15880. }
  15881. texture._designatedSlot = this._activeChannel;
  15882. }
  15883. }
  15884. else if (forTextureDataUpdate) {
  15885. this._activateCurrentTexture();
  15886. }
  15887. if (isTextureForRendering && !forTextureDataUpdate) {
  15888. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  15889. }
  15890. };
  15891. /** @ignore */
  15892. Engine.prototype._bindTexture = function (channel, texture) {
  15893. if (channel < 0) {
  15894. return;
  15895. }
  15896. if (texture) {
  15897. channel = this._getCorrectTextureChannel(channel, texture);
  15898. }
  15899. this._activeChannel = channel;
  15900. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  15901. };
  15902. /**
  15903. * Sets a texture to the webGL context from a postprocess
  15904. * @param channel defines the channel to use
  15905. * @param postProcess defines the source postprocess
  15906. */
  15907. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  15908. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  15909. };
  15910. /**
  15911. * Binds the output of the passed in post process to the texture channel specified
  15912. * @param channel The channel the texture should be bound to
  15913. * @param postProcess The post process which's output should be bound
  15914. */
  15915. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  15916. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  15917. };
  15918. /**
  15919. * Unbind all textures from the webGL context
  15920. */
  15921. Engine.prototype.unbindAllTextures = function () {
  15922. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  15923. this._activeChannel = channel;
  15924. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15925. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15926. if (this.webGLVersion > 1) {
  15927. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15928. }
  15929. }
  15930. };
  15931. /**
  15932. * Sets a texture to the according uniform.
  15933. * @param channel The texture channel
  15934. * @param uniform The uniform to set
  15935. * @param texture The texture to apply
  15936. */
  15937. Engine.prototype.setTexture = function (channel, uniform, texture) {
  15938. if (channel < 0) {
  15939. return;
  15940. }
  15941. if (uniform) {
  15942. this._boundUniforms[channel] = uniform;
  15943. }
  15944. this._setTexture(channel, texture);
  15945. };
  15946. /**
  15947. * Sets a depth stencil texture from a render target to the according uniform.
  15948. * @param channel The texture channel
  15949. * @param uniform The uniform to set
  15950. * @param texture The render target texture containing the depth stencil texture to apply
  15951. */
  15952. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  15953. if (channel < 0) {
  15954. return;
  15955. }
  15956. if (uniform) {
  15957. this._boundUniforms[channel] = uniform;
  15958. }
  15959. if (!texture || !texture.depthStencilTexture) {
  15960. this._setTexture(channel, null);
  15961. }
  15962. else {
  15963. this._setTexture(channel, texture, false, true);
  15964. }
  15965. };
  15966. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  15967. var uniform = this._boundUniforms[sourceSlot];
  15968. if (uniform._currentState === destination) {
  15969. return;
  15970. }
  15971. this._gl.uniform1i(uniform, destination);
  15972. uniform._currentState = destination;
  15973. };
  15974. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  15975. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  15976. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  15977. // Not ready?
  15978. if (!texture) {
  15979. if (this._boundTexturesCache[channel] != null) {
  15980. this._activeChannel = channel;
  15981. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15982. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15983. if (this.webGLVersion > 1) {
  15984. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15985. }
  15986. }
  15987. return false;
  15988. }
  15989. // Video
  15990. if (texture.video) {
  15991. this._activeChannel = channel;
  15992. texture.update();
  15993. }
  15994. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  15995. texture.delayLoad();
  15996. return false;
  15997. }
  15998. var internalTexture;
  15999. if (depthStencilTexture) {
  16000. internalTexture = texture.depthStencilTexture;
  16001. }
  16002. else if (texture.isReady()) {
  16003. internalTexture = texture.getInternalTexture();
  16004. }
  16005. else if (texture.isCube) {
  16006. internalTexture = this.emptyCubeTexture;
  16007. }
  16008. else if (texture.is3D) {
  16009. internalTexture = this.emptyTexture3D;
  16010. }
  16011. else {
  16012. internalTexture = this.emptyTexture;
  16013. }
  16014. if (!isPartOfTextureArray) {
  16015. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16016. }
  16017. if (this._boundTexturesCache[channel] === internalTexture) {
  16018. this._moveBoundTextureOnTop(internalTexture);
  16019. if (!isPartOfTextureArray) {
  16020. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16021. }
  16022. return false;
  16023. }
  16024. this._activeChannel = channel;
  16025. if (internalTexture && internalTexture.is3D) {
  16026. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16027. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16028. internalTexture._cachedWrapU = texture.wrapU;
  16029. switch (texture.wrapU) {
  16030. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16031. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  16032. break;
  16033. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16034. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  16035. break;
  16036. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16037. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  16038. break;
  16039. }
  16040. }
  16041. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16042. internalTexture._cachedWrapV = texture.wrapV;
  16043. switch (texture.wrapV) {
  16044. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16045. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  16046. break;
  16047. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16048. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  16049. break;
  16050. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16051. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  16052. break;
  16053. }
  16054. }
  16055. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16056. internalTexture._cachedWrapR = texture.wrapR;
  16057. switch (texture.wrapR) {
  16058. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16059. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  16060. break;
  16061. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16062. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  16063. break;
  16064. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16065. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  16066. break;
  16067. }
  16068. }
  16069. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16070. }
  16071. else if (internalTexture && internalTexture.isCube) {
  16072. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16073. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16074. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16075. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16076. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16077. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  16078. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16079. }
  16080. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16081. }
  16082. else {
  16083. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16084. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16085. internalTexture._cachedWrapU = texture.wrapU;
  16086. switch (texture.wrapU) {
  16087. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16088. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  16089. break;
  16090. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16091. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  16092. break;
  16093. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16094. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  16095. break;
  16096. }
  16097. }
  16098. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16099. internalTexture._cachedWrapV = texture.wrapV;
  16100. switch (texture.wrapV) {
  16101. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16102. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  16103. break;
  16104. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16105. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  16106. break;
  16107. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16108. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  16109. break;
  16110. }
  16111. }
  16112. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16113. }
  16114. return true;
  16115. };
  16116. /**
  16117. * Sets an array of texture to the webGL context
  16118. * @param channel defines the channel where the texture array must be set
  16119. * @param uniform defines the associated uniform location
  16120. * @param textures defines the array of textures to bind
  16121. */
  16122. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16123. if (channel < 0 || !uniform) {
  16124. return;
  16125. }
  16126. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16127. this._textureUnits = new Int32Array(textures.length);
  16128. }
  16129. for (var i = 0; i < textures.length; i++) {
  16130. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16131. }
  16132. this._gl.uniform1iv(uniform, this._textureUnits);
  16133. for (var index = 0; index < textures.length; index++) {
  16134. this._setTexture(this._textureUnits[index], textures[index], true);
  16135. }
  16136. };
  16137. /** @ignore */
  16138. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  16139. var internalTexture = texture.getInternalTexture();
  16140. if (!internalTexture) {
  16141. return;
  16142. }
  16143. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16144. var value = texture.anisotropicFilteringLevel;
  16145. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16146. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16147. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16148. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16149. }
  16150. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16151. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  16152. internalTexture._cachedAnisotropicFilteringLevel = value;
  16153. }
  16154. };
  16155. /**
  16156. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16157. * @param x defines the x coordinate of the rectangle where pixels must be read
  16158. * @param y defines the y coordinate of the rectangle where pixels must be read
  16159. * @param width defines the width of the rectangle where pixels must be read
  16160. * @param height defines the height of the rectangle where pixels must be read
  16161. * @returns a Uint8Array containing RGBA colors
  16162. */
  16163. Engine.prototype.readPixels = function (x, y, width, height) {
  16164. var data = new Uint8Array(height * width * 4);
  16165. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16166. return data;
  16167. };
  16168. /**
  16169. * Add an externaly attached data from its key.
  16170. * This method call will fail and return false, if such key already exists.
  16171. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16172. * @param key the unique key that identifies the data
  16173. * @param data the data object to associate to the key for this Engine instance
  16174. * @return true if no such key were already present and the data was added successfully, false otherwise
  16175. */
  16176. Engine.prototype.addExternalData = function (key, data) {
  16177. if (!this._externalData) {
  16178. this._externalData = new BABYLON.StringDictionary();
  16179. }
  16180. return this._externalData.add(key, data);
  16181. };
  16182. /**
  16183. * Get an externaly attached data from its key
  16184. * @param key the unique key that identifies the data
  16185. * @return the associated data, if present (can be null), or undefined if not present
  16186. */
  16187. Engine.prototype.getExternalData = function (key) {
  16188. if (!this._externalData) {
  16189. this._externalData = new BABYLON.StringDictionary();
  16190. }
  16191. return this._externalData.get(key);
  16192. };
  16193. /**
  16194. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16195. * @param key the unique key that identifies the data
  16196. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16197. * @return the associated data, can be null if the factory returned null.
  16198. */
  16199. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16200. if (!this._externalData) {
  16201. this._externalData = new BABYLON.StringDictionary();
  16202. }
  16203. return this._externalData.getOrAddWithFactory(key, factory);
  16204. };
  16205. /**
  16206. * Remove an externaly attached data from the Engine instance
  16207. * @param key the unique key that identifies the data
  16208. * @return true if the data was successfully removed, false if it doesn't exist
  16209. */
  16210. Engine.prototype.removeExternalData = function (key) {
  16211. if (!this._externalData) {
  16212. this._externalData = new BABYLON.StringDictionary();
  16213. }
  16214. return this._externalData.remove(key);
  16215. };
  16216. /**
  16217. * Unbind all vertex attributes from the webGL context
  16218. */
  16219. Engine.prototype.unbindAllAttributes = function () {
  16220. if (this._mustWipeVertexAttributes) {
  16221. this._mustWipeVertexAttributes = false;
  16222. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16223. this._gl.disableVertexAttribArray(i);
  16224. this._vertexAttribArraysEnabled[i] = false;
  16225. this._currentBufferPointers[i].active = false;
  16226. }
  16227. return;
  16228. }
  16229. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16230. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16231. continue;
  16232. }
  16233. this._gl.disableVertexAttribArray(i);
  16234. this._vertexAttribArraysEnabled[i] = false;
  16235. this._currentBufferPointers[i].active = false;
  16236. }
  16237. };
  16238. /**
  16239. * 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
  16240. */
  16241. Engine.prototype.releaseEffects = function () {
  16242. for (var name in this._compiledEffects) {
  16243. this._deleteProgram(this._compiledEffects[name]._program);
  16244. }
  16245. this._compiledEffects = {};
  16246. };
  16247. /**
  16248. * Dispose and release all associated resources
  16249. */
  16250. Engine.prototype.dispose = function () {
  16251. this.hideLoadingUI();
  16252. this.stopRenderLoop();
  16253. // Release postProcesses
  16254. while (this.postProcesses.length) {
  16255. this.postProcesses[0].dispose();
  16256. }
  16257. // Empty texture
  16258. if (this._emptyTexture) {
  16259. this._releaseTexture(this._emptyTexture);
  16260. this._emptyTexture = null;
  16261. }
  16262. if (this._emptyCubeTexture) {
  16263. this._releaseTexture(this._emptyCubeTexture);
  16264. this._emptyCubeTexture = null;
  16265. }
  16266. // Rescale PP
  16267. if (this._rescalePostProcess) {
  16268. this._rescalePostProcess.dispose();
  16269. }
  16270. // Release scenes
  16271. while (this.scenes.length) {
  16272. this.scenes[0].dispose();
  16273. }
  16274. // Release audio engine
  16275. if (Engine.audioEngine) {
  16276. Engine.audioEngine.dispose();
  16277. }
  16278. // Release effects
  16279. this.releaseEffects();
  16280. // Unbind
  16281. this.unbindAllAttributes();
  16282. this._boundUniforms = [];
  16283. if (this._dummyFramebuffer) {
  16284. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16285. }
  16286. //WebVR
  16287. this.disableVR();
  16288. // Events
  16289. if (BABYLON.Tools.IsWindowObjectExist()) {
  16290. window.removeEventListener("blur", this._onBlur);
  16291. window.removeEventListener("focus", this._onFocus);
  16292. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16293. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16294. if (this._renderingCanvas) {
  16295. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16296. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16297. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16298. if (!this._doNotHandleContextLost) {
  16299. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16300. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16301. }
  16302. }
  16303. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16304. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16305. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16306. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16307. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16308. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16309. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16310. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16311. if (this._onVrDisplayConnect) {
  16312. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16313. if (this._onVrDisplayDisconnect) {
  16314. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16315. }
  16316. if (this._onVrDisplayPresentChange) {
  16317. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16318. }
  16319. this._onVrDisplayConnect = null;
  16320. this._onVrDisplayDisconnect = null;
  16321. }
  16322. }
  16323. // Remove from Instances
  16324. var index = Engine.Instances.indexOf(this);
  16325. if (index >= 0) {
  16326. Engine.Instances.splice(index, 1);
  16327. }
  16328. this._workingCanvas = null;
  16329. this._workingContext = null;
  16330. this._currentBufferPointers = [];
  16331. this._renderingCanvas = null;
  16332. this._currentProgram = null;
  16333. this._bindedRenderFunction = null;
  16334. this.onResizeObservable.clear();
  16335. this.onCanvasBlurObservable.clear();
  16336. this.onCanvasFocusObservable.clear();
  16337. this.onCanvasPointerOutObservable.clear();
  16338. this.onBeginFrameObservable.clear();
  16339. this.onEndFrameObservable.clear();
  16340. BABYLON.Effect.ResetCache();
  16341. // Abort active requests
  16342. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16343. var request = _a[_i];
  16344. request.abort();
  16345. }
  16346. };
  16347. // Loading screen
  16348. /**
  16349. * Display the loading screen
  16350. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16351. */
  16352. Engine.prototype.displayLoadingUI = function () {
  16353. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16354. return;
  16355. }
  16356. var loadingScreen = this.loadingScreen;
  16357. if (loadingScreen) {
  16358. loadingScreen.displayLoadingUI();
  16359. }
  16360. };
  16361. /**
  16362. * Hide the loading screen
  16363. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16364. */
  16365. Engine.prototype.hideLoadingUI = function () {
  16366. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16367. return;
  16368. }
  16369. var loadingScreen = this.loadingScreen;
  16370. if (loadingScreen) {
  16371. loadingScreen.hideLoadingUI();
  16372. }
  16373. };
  16374. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16375. /**
  16376. * Gets the current loading screen object
  16377. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16378. */
  16379. get: function () {
  16380. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16381. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16382. return this._loadingScreen;
  16383. },
  16384. /**
  16385. * Sets the current loading screen object
  16386. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16387. */
  16388. set: function (loadingScreen) {
  16389. this._loadingScreen = loadingScreen;
  16390. },
  16391. enumerable: true,
  16392. configurable: true
  16393. });
  16394. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16395. /**
  16396. * Sets the current loading screen text
  16397. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16398. */
  16399. set: function (text) {
  16400. this.loadingScreen.loadingUIText = text;
  16401. },
  16402. enumerable: true,
  16403. configurable: true
  16404. });
  16405. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16406. /**
  16407. * Sets the current loading screen background color
  16408. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16409. */
  16410. set: function (color) {
  16411. this.loadingScreen.loadingUIBackgroundColor = color;
  16412. },
  16413. enumerable: true,
  16414. configurable: true
  16415. });
  16416. /**
  16417. * Attach a new callback raised when context lost event is fired
  16418. * @param callback defines the callback to call
  16419. */
  16420. Engine.prototype.attachContextLostEvent = function (callback) {
  16421. if (this._renderingCanvas) {
  16422. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16423. }
  16424. };
  16425. /**
  16426. * Attach a new callback raised when context restored event is fired
  16427. * @param callback defines the callback to call
  16428. */
  16429. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16430. if (this._renderingCanvas) {
  16431. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16432. }
  16433. };
  16434. /**
  16435. * Gets the source code of the vertex shader associated with a specific webGL program
  16436. * @param program defines the program to use
  16437. * @returns a string containing the source code of the vertex shader associated with the program
  16438. */
  16439. Engine.prototype.getVertexShaderSource = function (program) {
  16440. var shaders = this._gl.getAttachedShaders(program);
  16441. if (!shaders) {
  16442. return null;
  16443. }
  16444. return this._gl.getShaderSource(shaders[0]);
  16445. };
  16446. /**
  16447. * Gets the source code of the fragment shader associated with a specific webGL program
  16448. * @param program defines the program to use
  16449. * @returns a string containing the source code of the fragment shader associated with the program
  16450. */
  16451. Engine.prototype.getFragmentShaderSource = function (program) {
  16452. var shaders = this._gl.getAttachedShaders(program);
  16453. if (!shaders) {
  16454. return null;
  16455. }
  16456. return this._gl.getShaderSource(shaders[1]);
  16457. };
  16458. /**
  16459. * Get the current error code of the webGL context
  16460. * @returns the error code
  16461. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16462. */
  16463. Engine.prototype.getError = function () {
  16464. return this._gl.getError();
  16465. };
  16466. // FPS
  16467. /**
  16468. * Gets the current framerate
  16469. * @returns a number representing the framerate
  16470. */
  16471. Engine.prototype.getFps = function () {
  16472. return this._fps;
  16473. };
  16474. /**
  16475. * Gets the time spent between current and previous frame
  16476. * @returns a number representing the delta time in ms
  16477. */
  16478. Engine.prototype.getDeltaTime = function () {
  16479. return this._deltaTime;
  16480. };
  16481. Engine.prototype._measureFps = function () {
  16482. this._performanceMonitor.sampleFrame();
  16483. this._fps = this._performanceMonitor.averageFPS;
  16484. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16485. };
  16486. /** @ignore */
  16487. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16488. if (faceIndex === void 0) { faceIndex = -1; }
  16489. var gl = this._gl;
  16490. if (!this._dummyFramebuffer) {
  16491. var dummy = gl.createFramebuffer();
  16492. if (!dummy) {
  16493. throw new Error("Unable to create dummy framebuffer");
  16494. }
  16495. this._dummyFramebuffer = dummy;
  16496. }
  16497. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16498. if (faceIndex > -1) {
  16499. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16500. }
  16501. else {
  16502. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16503. }
  16504. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16505. var buffer;
  16506. switch (readType) {
  16507. case gl.UNSIGNED_BYTE:
  16508. buffer = new Uint8Array(4 * width * height);
  16509. readType = gl.UNSIGNED_BYTE;
  16510. break;
  16511. default:
  16512. buffer = new Float32Array(4 * width * height);
  16513. readType = gl.FLOAT;
  16514. break;
  16515. }
  16516. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16517. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16518. return buffer;
  16519. };
  16520. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16521. if (this._webGLVersion > 1) {
  16522. return this._caps.colorBufferFloat;
  16523. }
  16524. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16525. };
  16526. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16527. if (this._webGLVersion > 1) {
  16528. return this._caps.colorBufferFloat;
  16529. }
  16530. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16531. };
  16532. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16533. Engine.prototype._canRenderToFramebuffer = function (type) {
  16534. var gl = this._gl;
  16535. //clear existing errors
  16536. while (gl.getError() !== gl.NO_ERROR) { }
  16537. var successful = true;
  16538. var texture = gl.createTexture();
  16539. gl.bindTexture(gl.TEXTURE_2D, texture);
  16540. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16542. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16543. var fb = gl.createFramebuffer();
  16544. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16545. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16546. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16547. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16548. successful = successful && (gl.getError() === gl.NO_ERROR);
  16549. //try render by clearing frame buffer's color buffer
  16550. if (successful) {
  16551. gl.clear(gl.COLOR_BUFFER_BIT);
  16552. successful = successful && (gl.getError() === gl.NO_ERROR);
  16553. }
  16554. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16555. if (successful) {
  16556. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16557. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16558. var readFormat = gl.RGBA;
  16559. var readType = gl.UNSIGNED_BYTE;
  16560. var buffer = new Uint8Array(4);
  16561. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16562. successful = successful && (gl.getError() === gl.NO_ERROR);
  16563. }
  16564. //clean up
  16565. gl.deleteTexture(texture);
  16566. gl.deleteFramebuffer(fb);
  16567. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16568. //clear accumulated errors
  16569. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16570. return successful;
  16571. };
  16572. /** @ignore */
  16573. Engine.prototype._getWebGLTextureType = function (type) {
  16574. if (type === Engine.TEXTURETYPE_FLOAT) {
  16575. return this._gl.FLOAT;
  16576. }
  16577. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16578. // Add Half Float Constant.
  16579. return this._gl.HALF_FLOAT_OES;
  16580. }
  16581. return this._gl.UNSIGNED_BYTE;
  16582. };
  16583. ;
  16584. Engine.prototype._getInternalFormat = function (format) {
  16585. var internalFormat = this._gl.RGBA;
  16586. switch (format) {
  16587. case Engine.TEXTUREFORMAT_ALPHA:
  16588. internalFormat = this._gl.ALPHA;
  16589. break;
  16590. case Engine.TEXTUREFORMAT_LUMINANCE:
  16591. internalFormat = this._gl.LUMINANCE;
  16592. break;
  16593. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16594. internalFormat = this._gl.LUMINANCE_ALPHA;
  16595. break;
  16596. case Engine.TEXTUREFORMAT_RGB:
  16597. case Engine.TEXTUREFORMAT_RGB32F:
  16598. internalFormat = this._gl.RGB;
  16599. break;
  16600. case Engine.TEXTUREFORMAT_RGBA:
  16601. case Engine.TEXTUREFORMAT_RGBA32F:
  16602. internalFormat = this._gl.RGBA;
  16603. break;
  16604. case Engine.TEXTUREFORMAT_R32F:
  16605. internalFormat = this._gl.RED;
  16606. break;
  16607. case Engine.TEXTUREFORMAT_RG32F:
  16608. internalFormat = this._gl.RG;
  16609. break;
  16610. }
  16611. return internalFormat;
  16612. };
  16613. /** @ignore */
  16614. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16615. if (this._webGLVersion === 1) {
  16616. if (format) {
  16617. switch (format) {
  16618. case Engine.TEXTUREFORMAT_LUMINANCE:
  16619. return this._gl.LUMINANCE;
  16620. }
  16621. }
  16622. return this._gl.RGBA;
  16623. }
  16624. if (type === Engine.TEXTURETYPE_FLOAT) {
  16625. if (format) {
  16626. switch (format) {
  16627. case Engine.TEXTUREFORMAT_R32F:
  16628. return this._gl.R32F;
  16629. case Engine.TEXTUREFORMAT_RG32F:
  16630. return this._gl.RG32F;
  16631. case Engine.TEXTUREFORMAT_RGB32F:
  16632. return this._gl.RGB32F;
  16633. }
  16634. }
  16635. return this._gl.RGBA32F;
  16636. }
  16637. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16638. return this._gl.RGBA16F;
  16639. }
  16640. if (format) {
  16641. switch (format) {
  16642. case Engine.TEXTUREFORMAT_LUMINANCE:
  16643. return this._gl.LUMINANCE;
  16644. }
  16645. }
  16646. return this._gl.RGBA;
  16647. };
  16648. ;
  16649. /** @ignore */
  16650. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16651. if (type === Engine.TEXTURETYPE_FLOAT) {
  16652. return this._gl.RGBA32F;
  16653. }
  16654. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16655. return this._gl.RGBA16F;
  16656. }
  16657. return this._gl.RGBA8;
  16658. };
  16659. ;
  16660. /**
  16661. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16662. * @return the new query
  16663. */
  16664. Engine.prototype.createQuery = function () {
  16665. return this._gl.createQuery();
  16666. };
  16667. /**
  16668. * Delete and release a webGL query
  16669. * @param query defines the query to delete
  16670. * @return the current engine
  16671. */
  16672. Engine.prototype.deleteQuery = function (query) {
  16673. this._gl.deleteQuery(query);
  16674. return this;
  16675. };
  16676. /**
  16677. * Check if a given query has resolved and got its value
  16678. * @param query defines the query to check
  16679. * @returns true if the query got its value
  16680. */
  16681. Engine.prototype.isQueryResultAvailable = function (query) {
  16682. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16683. };
  16684. /**
  16685. * Gets the value of a given query
  16686. * @param query defines the query to check
  16687. * @returns the value of the query
  16688. */
  16689. Engine.prototype.getQueryResult = function (query) {
  16690. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16691. };
  16692. /**
  16693. * Initiates an occlusion query
  16694. * @param algorithmType defines the algorithm to use
  16695. * @param query defines the query to use
  16696. * @returns the current engine
  16697. * @see http://doc.babylonjs.com/features/occlusionquery
  16698. */
  16699. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16700. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16701. this._gl.beginQuery(glAlgorithm, query);
  16702. return this;
  16703. };
  16704. /**
  16705. * Ends an occlusion query
  16706. * @see http://doc.babylonjs.com/features/occlusionquery
  16707. * @param algorithmType defines the algorithm to use
  16708. * @returns the current engine
  16709. */
  16710. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16711. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16712. this._gl.endQuery(glAlgorithm);
  16713. return this;
  16714. };
  16715. /* Time queries */
  16716. Engine.prototype._createTimeQuery = function () {
  16717. var timerQuery = this._caps.timerQuery;
  16718. if (timerQuery.createQueryEXT) {
  16719. return timerQuery.createQueryEXT();
  16720. }
  16721. return this.createQuery();
  16722. };
  16723. Engine.prototype._deleteTimeQuery = function (query) {
  16724. var timerQuery = this._caps.timerQuery;
  16725. if (timerQuery.deleteQueryEXT) {
  16726. timerQuery.deleteQueryEXT(query);
  16727. return;
  16728. }
  16729. this.deleteQuery(query);
  16730. };
  16731. Engine.prototype._getTimeQueryResult = function (query) {
  16732. var timerQuery = this._caps.timerQuery;
  16733. if (timerQuery.getQueryObjectEXT) {
  16734. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16735. }
  16736. return this.getQueryResult(query);
  16737. };
  16738. Engine.prototype._getTimeQueryAvailability = function (query) {
  16739. var timerQuery = this._caps.timerQuery;
  16740. if (timerQuery.getQueryObjectEXT) {
  16741. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16742. }
  16743. return this.isQueryResultAvailable(query);
  16744. };
  16745. /**
  16746. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16747. * Please note that only one query can be issued at a time
  16748. * @returns a time token used to track the time span
  16749. */
  16750. Engine.prototype.startTimeQuery = function () {
  16751. var timerQuery = this._caps.timerQuery;
  16752. if (!timerQuery) {
  16753. return null;
  16754. }
  16755. var token = new BABYLON._TimeToken();
  16756. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16757. if (this._caps.canUseTimestampForTimerQuery) {
  16758. token._startTimeQuery = this._createTimeQuery();
  16759. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16760. }
  16761. else {
  16762. if (this._currentNonTimestampToken) {
  16763. return this._currentNonTimestampToken;
  16764. }
  16765. token._timeElapsedQuery = this._createTimeQuery();
  16766. if (timerQuery.beginQueryEXT) {
  16767. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16768. }
  16769. else {
  16770. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16771. }
  16772. this._currentNonTimestampToken = token;
  16773. }
  16774. return token;
  16775. };
  16776. /**
  16777. * Ends a time query
  16778. * @param token defines the token used to measure the time span
  16779. * @returns the time spent (in ns)
  16780. */
  16781. Engine.prototype.endTimeQuery = function (token) {
  16782. var timerQuery = this._caps.timerQuery;
  16783. if (!timerQuery || !token) {
  16784. return -1;
  16785. }
  16786. if (this._caps.canUseTimestampForTimerQuery) {
  16787. if (!token._startTimeQuery) {
  16788. return -1;
  16789. }
  16790. if (!token._endTimeQuery) {
  16791. token._endTimeQuery = this._createTimeQuery();
  16792. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16793. }
  16794. }
  16795. else if (!token._timeElapsedQueryEnded) {
  16796. if (!token._timeElapsedQuery) {
  16797. return -1;
  16798. }
  16799. if (timerQuery.endQueryEXT) {
  16800. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16801. }
  16802. else {
  16803. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16804. }
  16805. token._timeElapsedQueryEnded = true;
  16806. }
  16807. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16808. var available = false;
  16809. if (token._endTimeQuery) {
  16810. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16811. }
  16812. else if (token._timeElapsedQuery) {
  16813. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16814. }
  16815. if (available && !disjoint) {
  16816. var result = 0;
  16817. if (this._caps.canUseTimestampForTimerQuery) {
  16818. if (!token._startTimeQuery || !token._endTimeQuery) {
  16819. return -1;
  16820. }
  16821. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16822. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16823. result = timeEnd - timeStart;
  16824. this._deleteTimeQuery(token._startTimeQuery);
  16825. this._deleteTimeQuery(token._endTimeQuery);
  16826. token._startTimeQuery = null;
  16827. token._endTimeQuery = null;
  16828. }
  16829. else {
  16830. if (!token._timeElapsedQuery) {
  16831. return -1;
  16832. }
  16833. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16834. this._deleteTimeQuery(token._timeElapsedQuery);
  16835. token._timeElapsedQuery = null;
  16836. token._timeElapsedQueryEnded = false;
  16837. this._currentNonTimestampToken = null;
  16838. }
  16839. return result;
  16840. }
  16841. return -1;
  16842. };
  16843. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16844. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16845. };
  16846. // Transform feedback
  16847. /**
  16848. * Creates a webGL transform feedback object
  16849. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16850. * @returns the webGL transform feedback object
  16851. */
  16852. Engine.prototype.createTransformFeedback = function () {
  16853. return this._gl.createTransformFeedback();
  16854. };
  16855. /**
  16856. * Delete a webGL transform feedback object
  16857. * @param value defines the webGL transform feedback object to delete
  16858. */
  16859. Engine.prototype.deleteTransformFeedback = function (value) {
  16860. this._gl.deleteTransformFeedback(value);
  16861. };
  16862. /**
  16863. * Bind a webGL transform feedback object to the webgl context
  16864. * @param value defines the webGL transform feedback object to bind
  16865. */
  16866. Engine.prototype.bindTransformFeedback = function (value) {
  16867. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16868. };
  16869. /**
  16870. * Begins a transform feedback operation
  16871. * @param usePoints defines if points or triangles must be used
  16872. */
  16873. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16874. if (usePoints === void 0) { usePoints = true; }
  16875. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16876. };
  16877. /**
  16878. * Ends a transform feedback operation
  16879. */
  16880. Engine.prototype.endTransformFeedback = function () {
  16881. this._gl.endTransformFeedback();
  16882. };
  16883. /**
  16884. * Specify the varyings to use with transform feedback
  16885. * @param program defines the associated webGL program
  16886. * @param value defines the list of strings representing the varying names
  16887. */
  16888. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  16889. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  16890. };
  16891. /**
  16892. * Bind a webGL buffer for a transform feedback operation
  16893. * @param value defines the webGL buffer to bind
  16894. */
  16895. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  16896. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  16897. };
  16898. /** @ignore */
  16899. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16900. var _this = this;
  16901. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16902. this._activeRequests.push(request);
  16903. request.onCompleteObservable.add(function (request) {
  16904. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16905. });
  16906. return request;
  16907. };
  16908. /** @ignore */
  16909. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16910. var _this = this;
  16911. return new Promise(function (resolve, reject) {
  16912. _this._loadFile(url, function (data) {
  16913. resolve(data);
  16914. }, undefined, database, useArrayBuffer, function (request, exception) {
  16915. reject(exception);
  16916. });
  16917. });
  16918. };
  16919. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16920. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16921. var onload = function (data) {
  16922. loadedFiles[index] = data;
  16923. loadedFiles._internalCount++;
  16924. if (loadedFiles._internalCount === 6) {
  16925. onfinish(loadedFiles);
  16926. }
  16927. };
  16928. var onerror = function (request, exception) {
  16929. if (onErrorCallBack && request) {
  16930. onErrorCallBack(request.status + " " + request.statusText, exception);
  16931. }
  16932. };
  16933. this._loadFile(url, onload, undefined, undefined, true, onerror);
  16934. };
  16935. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  16936. if (onError === void 0) { onError = null; }
  16937. var loadedFiles = [];
  16938. loadedFiles._internalCount = 0;
  16939. for (var index = 0; index < 6; index++) {
  16940. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  16941. }
  16942. };
  16943. // Statics
  16944. /**
  16945. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  16946. * @returns true if the engine can be created
  16947. * @ignoreNaming
  16948. */
  16949. Engine.isSupported = function () {
  16950. try {
  16951. var tempcanvas = document.createElement("canvas");
  16952. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  16953. return gl != null && !!window.WebGLRenderingContext;
  16954. }
  16955. catch (e) {
  16956. return false;
  16957. }
  16958. };
  16959. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  16960. Engine.ExceptionList = [
  16961. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  16962. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16963. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16964. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16965. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16966. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  16967. ];
  16968. /** Gets the list of created engines */
  16969. Engine.Instances = new Array();
  16970. // Const statics
  16971. Engine._ALPHA_DISABLE = 0;
  16972. Engine._ALPHA_ADD = 1;
  16973. Engine._ALPHA_COMBINE = 2;
  16974. Engine._ALPHA_SUBTRACT = 3;
  16975. Engine._ALPHA_MULTIPLY = 4;
  16976. Engine._ALPHA_MAXIMIZED = 5;
  16977. Engine._ALPHA_ONEONE = 6;
  16978. Engine._ALPHA_PREMULTIPLIED = 7;
  16979. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  16980. Engine._ALPHA_INTERPOLATE = 9;
  16981. Engine._ALPHA_SCREENMODE = 10;
  16982. Engine._DELAYLOADSTATE_NONE = 0;
  16983. Engine._DELAYLOADSTATE_LOADED = 1;
  16984. Engine._DELAYLOADSTATE_LOADING = 2;
  16985. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  16986. Engine._TEXTUREFORMAT_ALPHA = 0;
  16987. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  16988. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  16989. Engine._TEXTUREFORMAT_RGB = 4;
  16990. Engine._TEXTUREFORMAT_RGBA = 5;
  16991. Engine._TEXTUREFORMAT_R32F = 6;
  16992. Engine._TEXTUREFORMAT_RG32F = 7;
  16993. Engine._TEXTUREFORMAT_RGB32F = 8;
  16994. Engine._TEXTUREFORMAT_RGBA32F = 9;
  16995. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  16996. Engine._TEXTURETYPE_FLOAT = 1;
  16997. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  16998. // Depht or Stencil test Constants.
  16999. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17000. 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.
  17001. 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.
  17002. 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.
  17003. 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.
  17004. 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.
  17005. 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.
  17006. 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.
  17007. // Stencil Actions Constants.
  17008. Engine._KEEP = 0x1E00;
  17009. Engine._REPLACE = 0x1E01;
  17010. Engine._INCR = 0x1E02;
  17011. Engine._DECR = 0x1E03;
  17012. Engine._INVERT = 0x150A;
  17013. Engine._INCR_WRAP = 0x8507;
  17014. Engine._DECR_WRAP = 0x8508;
  17015. // Texture rescaling mode
  17016. Engine._SCALEMODE_FLOOR = 1;
  17017. Engine._SCALEMODE_NEAREST = 2;
  17018. Engine._SCALEMODE_CEILING = 3;
  17019. // Updatable statics so stick with vars here
  17020. /**
  17021. * Gets or sets the epsilon value used by collision engine
  17022. */
  17023. Engine.CollisionsEpsilon = 0.001;
  17024. /**
  17025. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17026. */
  17027. Engine.CodeRepository = "src/";
  17028. /**
  17029. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17030. */
  17031. Engine.ShadersRepository = "src/Shaders/";
  17032. return Engine;
  17033. }());
  17034. BABYLON.Engine = Engine;
  17035. })(BABYLON || (BABYLON = {}));
  17036. //# sourceMappingURL=babylon.engine.js.map
  17037. "use strict";
  17038. var BABYLON;
  17039. (function (BABYLON) {
  17040. /**
  17041. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17042. */
  17043. var Node = /** @class */ (function () {
  17044. /**
  17045. * Creates a new Node
  17046. * @param {string} name - the name and id to be given to this node
  17047. * @param {BABYLON.Scene} the scene this node will be added to
  17048. */
  17049. function Node(name, scene) {
  17050. if (scene === void 0) { scene = null; }
  17051. /**
  17052. * Gets or sets a string used to store user defined state for the node
  17053. */
  17054. this.state = "";
  17055. /**
  17056. * Gets or sets an object used to store user defined information for the node
  17057. */
  17058. this.metadata = null;
  17059. /**
  17060. * Gets or sets a boolean used to define if the node must be serialized
  17061. */
  17062. this.doNotSerialize = false;
  17063. /** @ignore */
  17064. this._isDisposed = false;
  17065. /**
  17066. * Gets a list of Animations associated with the node
  17067. */
  17068. this.animations = new Array();
  17069. this._ranges = {};
  17070. this._isEnabled = true;
  17071. this._isReady = true;
  17072. /** @ignore */
  17073. this._currentRenderId = -1;
  17074. this._parentRenderId = -1;
  17075. this._childRenderId = -1;
  17076. this._animationPropertiesOverride = null;
  17077. /**
  17078. * An event triggered when the mesh is disposed
  17079. */
  17080. this.onDisposeObservable = new BABYLON.Observable();
  17081. // Behaviors
  17082. this._behaviors = new Array();
  17083. this.name = name;
  17084. this.id = name;
  17085. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17086. this.uniqueId = this._scene.getUniqueId();
  17087. this._initCache();
  17088. }
  17089. /**
  17090. * Gets a boolean indicating if the node has been disposed
  17091. * @returns true if the node was disposed
  17092. */
  17093. Node.prototype.isDisposed = function () {
  17094. return this._isDisposed;
  17095. };
  17096. Object.defineProperty(Node.prototype, "parent", {
  17097. get: function () {
  17098. return this._parentNode;
  17099. },
  17100. /**
  17101. * Gets or sets the parent of the node
  17102. */
  17103. set: function (parent) {
  17104. if (this._parentNode === parent) {
  17105. return;
  17106. }
  17107. // Remove self from list of children of parent
  17108. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17109. var index = this._parentNode._children.indexOf(this);
  17110. if (index !== -1) {
  17111. this._parentNode._children.splice(index, 1);
  17112. }
  17113. }
  17114. // Store new parent
  17115. this._parentNode = parent;
  17116. // Add as child to new parent
  17117. if (this._parentNode) {
  17118. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17119. this._parentNode._children = new Array();
  17120. }
  17121. this._parentNode._children.push(this);
  17122. }
  17123. },
  17124. enumerable: true,
  17125. configurable: true
  17126. });
  17127. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17128. /**
  17129. * Gets or sets the animation properties override
  17130. */
  17131. get: function () {
  17132. return this._animationPropertiesOverride;
  17133. },
  17134. set: function (value) {
  17135. this._animationPropertiesOverride = value;
  17136. },
  17137. enumerable: true,
  17138. configurable: true
  17139. });
  17140. /**
  17141. * Gets a string idenfifying the name of the class
  17142. * @returns "Node" string
  17143. */
  17144. Node.prototype.getClassName = function () {
  17145. return "Node";
  17146. };
  17147. Object.defineProperty(Node.prototype, "onDispose", {
  17148. /**
  17149. * Sets a callback that will be raised when the node will be disposed
  17150. */
  17151. set: function (callback) {
  17152. if (this._onDisposeObserver) {
  17153. this.onDisposeObservable.remove(this._onDisposeObserver);
  17154. }
  17155. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17156. },
  17157. enumerable: true,
  17158. configurable: true
  17159. });
  17160. /**
  17161. * Gets the scene of the node
  17162. * @returns a {BABYLON.Scene}
  17163. */
  17164. Node.prototype.getScene = function () {
  17165. return this._scene;
  17166. };
  17167. /**
  17168. * Gets the engine of the node
  17169. * @returns a {BABYLON.Engine}
  17170. */
  17171. Node.prototype.getEngine = function () {
  17172. return this._scene.getEngine();
  17173. };
  17174. /**
  17175. * Attach a behavior to the node
  17176. * @see http://doc.babylonjs.com/features/behaviour
  17177. * @param behavior defines the behavior to attach
  17178. * @returns the current Node
  17179. */
  17180. Node.prototype.addBehavior = function (behavior) {
  17181. var _this = this;
  17182. var index = this._behaviors.indexOf(behavior);
  17183. if (index !== -1) {
  17184. return this;
  17185. }
  17186. behavior.init();
  17187. if (this._scene.isLoading) {
  17188. // We defer the attach when the scene will be loaded
  17189. var observer = this._scene.onDataLoadedObservable.add(function () {
  17190. behavior.attach(_this);
  17191. setTimeout(function () {
  17192. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17193. _this._scene.onDataLoadedObservable.remove(observer);
  17194. }, 0);
  17195. });
  17196. }
  17197. else {
  17198. behavior.attach(this);
  17199. }
  17200. this._behaviors.push(behavior);
  17201. return this;
  17202. };
  17203. /**
  17204. * Remove an attached behavior
  17205. * @see http://doc.babylonjs.com/features/behaviour
  17206. * @param behavior defines the behavior to attach
  17207. * @returns the current Node
  17208. */
  17209. Node.prototype.removeBehavior = function (behavior) {
  17210. var index = this._behaviors.indexOf(behavior);
  17211. if (index === -1) {
  17212. return this;
  17213. }
  17214. this._behaviors[index].detach();
  17215. this._behaviors.splice(index, 1);
  17216. return this;
  17217. };
  17218. Object.defineProperty(Node.prototype, "behaviors", {
  17219. /**
  17220. * Gets the list of attached behaviors
  17221. * @see http://doc.babylonjs.com/features/behaviour
  17222. */
  17223. get: function () {
  17224. return this._behaviors;
  17225. },
  17226. enumerable: true,
  17227. configurable: true
  17228. });
  17229. /**
  17230. * Gets an attached behavior by name
  17231. * @param name defines the name of the behavior to look for
  17232. * @see http://doc.babylonjs.com/features/behaviour
  17233. * @returns null if behavior was not found else the requested behavior
  17234. */
  17235. Node.prototype.getBehaviorByName = function (name) {
  17236. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17237. var behavior = _a[_i];
  17238. if (behavior.name === name) {
  17239. return behavior;
  17240. }
  17241. }
  17242. return null;
  17243. };
  17244. /**
  17245. * Returns the world matrix of the node
  17246. * @returns a matrix containing the node's world matrix
  17247. */
  17248. Node.prototype.getWorldMatrix = function () {
  17249. return BABYLON.Matrix.Identity();
  17250. };
  17251. // override it in derived class if you add new variables to the cache
  17252. // and call the parent class method
  17253. /** @ignore */
  17254. Node.prototype._initCache = function () {
  17255. this._cache = {};
  17256. this._cache.parent = undefined;
  17257. };
  17258. /** @ignore */
  17259. Node.prototype.updateCache = function (force) {
  17260. if (!force && this.isSynchronized())
  17261. return;
  17262. this._cache.parent = this.parent;
  17263. this._updateCache();
  17264. };
  17265. // override it in derived class if you add new variables to the cache
  17266. // and call the parent class method if !ignoreParentClass
  17267. /** @ignore */
  17268. Node.prototype._updateCache = function (ignoreParentClass) {
  17269. };
  17270. // override it in derived class if you add new variables to the cache
  17271. /** @ignore */
  17272. Node.prototype._isSynchronized = function () {
  17273. return true;
  17274. };
  17275. /** @ignore */
  17276. Node.prototype._markSyncedWithParent = function () {
  17277. if (this.parent) {
  17278. this._parentRenderId = this.parent._childRenderId;
  17279. }
  17280. };
  17281. /** @ignore */
  17282. Node.prototype.isSynchronizedWithParent = function () {
  17283. if (!this.parent) {
  17284. return true;
  17285. }
  17286. if (this._parentRenderId !== this.parent._childRenderId) {
  17287. return false;
  17288. }
  17289. return this.parent.isSynchronized();
  17290. };
  17291. /** @ignore */
  17292. Node.prototype.isSynchronized = function (updateCache) {
  17293. var check = this.hasNewParent();
  17294. check = check || !this.isSynchronizedWithParent();
  17295. check = check || !this._isSynchronized();
  17296. if (updateCache)
  17297. this.updateCache(true);
  17298. return !check;
  17299. };
  17300. /** @ignore */
  17301. Node.prototype.hasNewParent = function (update) {
  17302. if (this._cache.parent === this.parent)
  17303. return false;
  17304. if (update)
  17305. this._cache.parent = this.parent;
  17306. return true;
  17307. };
  17308. /**
  17309. * Is this node ready to be used/rendered
  17310. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17311. * @return true if the node is ready
  17312. */
  17313. Node.prototype.isReady = function (completeCheck) {
  17314. if (completeCheck === void 0) { completeCheck = false; }
  17315. return this._isReady;
  17316. };
  17317. /**
  17318. * Is this node enabled?
  17319. * 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
  17320. * @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
  17321. * @return whether this node (and its parent) is enabled
  17322. */
  17323. Node.prototype.isEnabled = function (checkAncestors) {
  17324. if (checkAncestors === void 0) { checkAncestors = true; }
  17325. if (checkAncestors === false) {
  17326. return this._isEnabled;
  17327. }
  17328. if (this._isEnabled === false) {
  17329. return false;
  17330. }
  17331. if (this.parent !== undefined && this.parent !== null) {
  17332. return this.parent.isEnabled(checkAncestors);
  17333. }
  17334. return true;
  17335. };
  17336. /**
  17337. * Set the enabled state of this node
  17338. * @param value defines the new enabled state
  17339. */
  17340. Node.prototype.setEnabled = function (value) {
  17341. this._isEnabled = value;
  17342. };
  17343. /**
  17344. * Is this node a descendant of the given node?
  17345. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17346. * @param ancestor defines the parent node to inspect
  17347. * @returns a boolean indicating if this node is a descendant of the given node
  17348. */
  17349. Node.prototype.isDescendantOf = function (ancestor) {
  17350. if (this.parent) {
  17351. if (this.parent === ancestor) {
  17352. return true;
  17353. }
  17354. return this.parent.isDescendantOf(ancestor);
  17355. }
  17356. return false;
  17357. };
  17358. /** @ignore */
  17359. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17360. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17361. if (!this._children) {
  17362. return;
  17363. }
  17364. for (var index = 0; index < this._children.length; index++) {
  17365. var item = this._children[index];
  17366. if (!predicate || predicate(item)) {
  17367. results.push(item);
  17368. }
  17369. if (!directDescendantsOnly) {
  17370. item._getDescendants(results, false, predicate);
  17371. }
  17372. }
  17373. };
  17374. /**
  17375. * Will return all nodes that have this node as ascendant
  17376. * @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
  17377. * @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
  17378. * @return all children nodes of all types
  17379. */
  17380. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17381. var results = new Array();
  17382. this._getDescendants(results, directDescendantsOnly, predicate);
  17383. return results;
  17384. };
  17385. /**
  17386. * Get all child-meshes of this node
  17387. * @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
  17388. * @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
  17389. * @returns an array of {BABYLON.AbstractMesh}
  17390. */
  17391. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17392. var results = [];
  17393. this._getDescendants(results, directDescendantsOnly, function (node) {
  17394. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17395. });
  17396. return results;
  17397. };
  17398. /**
  17399. * Get all child-transformNodes of this node
  17400. * @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
  17401. * @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
  17402. * @returns an array of {BABYLON.TransformNode}
  17403. */
  17404. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17405. var results = [];
  17406. this._getDescendants(results, directDescendantsOnly, function (node) {
  17407. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17408. });
  17409. return results;
  17410. };
  17411. /**
  17412. * Get all direct children of this node
  17413. * @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
  17414. * @returns an array of {BABYLON.Node}
  17415. */
  17416. Node.prototype.getChildren = function (predicate) {
  17417. return this.getDescendants(true, predicate);
  17418. };
  17419. /** @ignore */
  17420. Node.prototype._setReady = function (state) {
  17421. if (state === this._isReady) {
  17422. return;
  17423. }
  17424. if (!state) {
  17425. this._isReady = false;
  17426. return;
  17427. }
  17428. if (this.onReady) {
  17429. this.onReady(this);
  17430. }
  17431. this._isReady = true;
  17432. };
  17433. /**
  17434. * Get an animation by name
  17435. * @param name defines the name of the animation to look for
  17436. * @returns null if not found else the requested animation
  17437. */
  17438. Node.prototype.getAnimationByName = function (name) {
  17439. for (var i = 0; i < this.animations.length; i++) {
  17440. var animation = this.animations[i];
  17441. if (animation.name === name) {
  17442. return animation;
  17443. }
  17444. }
  17445. return null;
  17446. };
  17447. /**
  17448. * Creates an animation range for this node
  17449. * @param name defines the name of the range
  17450. * @param from defines the starting key
  17451. * @param to defines the end key
  17452. */
  17453. Node.prototype.createAnimationRange = function (name, from, to) {
  17454. // check name not already in use
  17455. if (!this._ranges[name]) {
  17456. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17457. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17458. if (this.animations[i]) {
  17459. this.animations[i].createRange(name, from, to);
  17460. }
  17461. }
  17462. }
  17463. };
  17464. /**
  17465. * Delete a specific animation range
  17466. * @param name defines the name of the range to delete
  17467. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17468. */
  17469. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17470. if (deleteFrames === void 0) { deleteFrames = true; }
  17471. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17472. if (this.animations[i]) {
  17473. this.animations[i].deleteRange(name, deleteFrames);
  17474. }
  17475. }
  17476. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17477. };
  17478. /**
  17479. * Get an animation range by name
  17480. * @param name defines the name of the animation range to look for
  17481. * @returns null if not found else the requested animation range
  17482. */
  17483. Node.prototype.getAnimationRange = function (name) {
  17484. return this._ranges[name];
  17485. };
  17486. /**
  17487. * Will start the animation sequence
  17488. * @param name defines the range frames for animation sequence
  17489. * @param loop defines if the animation should loop (false by default)
  17490. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17491. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17492. * @returns the object created for this animation. If range does not exist, it will return null
  17493. */
  17494. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17495. var range = this.getAnimationRange(name);
  17496. if (!range) {
  17497. return null;
  17498. }
  17499. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17500. };
  17501. /**
  17502. * Serialize animation ranges into a JSON compatible object
  17503. * @returns serialization object
  17504. */
  17505. Node.prototype.serializeAnimationRanges = function () {
  17506. var serializationRanges = [];
  17507. for (var name in this._ranges) {
  17508. var localRange = this._ranges[name];
  17509. if (!localRange) {
  17510. continue;
  17511. }
  17512. var range = {};
  17513. range.name = name;
  17514. range.from = localRange.from;
  17515. range.to = localRange.to;
  17516. serializationRanges.push(range);
  17517. }
  17518. return serializationRanges;
  17519. };
  17520. /**
  17521. * Computes the world matrix of the node
  17522. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17523. * @returns the world matrix
  17524. */
  17525. Node.prototype.computeWorldMatrix = function (force) {
  17526. return BABYLON.Matrix.Identity();
  17527. };
  17528. /**
  17529. * Releases resources associated with this node.
  17530. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17531. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17532. */
  17533. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17534. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17535. if (!doNotRecurse) {
  17536. var nodes = this.getDescendants(true);
  17537. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17538. var node = nodes_1[_i];
  17539. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17540. }
  17541. }
  17542. else {
  17543. var transformNodes = this.getChildTransformNodes(true);
  17544. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17545. var transformNode = transformNodes_1[_a];
  17546. transformNode.parent = null;
  17547. transformNode.computeWorldMatrix(true);
  17548. }
  17549. }
  17550. this.parent = null;
  17551. // Callback
  17552. this.onDisposeObservable.notifyObservers(this);
  17553. this.onDisposeObservable.clear();
  17554. // Behaviors
  17555. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17556. var behavior = _c[_b];
  17557. behavior.detach();
  17558. }
  17559. this._behaviors = [];
  17560. this._isDisposed = true;
  17561. };
  17562. /**
  17563. * Parse animation range data from a serialization object and store them into a given node
  17564. * @param node defines where to store the animation ranges
  17565. * @param parsedNode defines the serialization object to read data from
  17566. * @param scene defines the hosting scene
  17567. */
  17568. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17569. if (parsedNode.ranges) {
  17570. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17571. var data = parsedNode.ranges[index];
  17572. node.createAnimationRange(data.name, data.from, data.to);
  17573. }
  17574. }
  17575. };
  17576. __decorate([
  17577. BABYLON.serialize()
  17578. ], Node.prototype, "name", void 0);
  17579. __decorate([
  17580. BABYLON.serialize()
  17581. ], Node.prototype, "id", void 0);
  17582. __decorate([
  17583. BABYLON.serialize()
  17584. ], Node.prototype, "uniqueId", void 0);
  17585. __decorate([
  17586. BABYLON.serialize()
  17587. ], Node.prototype, "state", void 0);
  17588. __decorate([
  17589. BABYLON.serialize()
  17590. ], Node.prototype, "metadata", void 0);
  17591. return Node;
  17592. }());
  17593. BABYLON.Node = Node;
  17594. })(BABYLON || (BABYLON = {}));
  17595. //# sourceMappingURL=babylon.node.js.map
  17596. "use strict";
  17597. var BABYLON;
  17598. (function (BABYLON) {
  17599. var BoundingSphere = /** @class */ (function () {
  17600. function BoundingSphere(minimum, maximum) {
  17601. this.minimum = minimum;
  17602. this.maximum = maximum;
  17603. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17604. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  17605. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  17606. this.radius = distance * 0.5;
  17607. this.centerWorld = BABYLON.Vector3.Zero();
  17608. this._update(BABYLON.Matrix.Identity());
  17609. }
  17610. // Methods
  17611. BoundingSphere.prototype._update = function (world) {
  17612. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17613. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17614. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17615. };
  17616. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17617. for (var i = 0; i < 6; i++) {
  17618. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17619. return false;
  17620. }
  17621. return true;
  17622. };
  17623. BoundingSphere.prototype.intersectsPoint = function (point) {
  17624. var x = this.centerWorld.x - point.x;
  17625. var y = this.centerWorld.y - point.y;
  17626. var z = this.centerWorld.z - point.z;
  17627. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17628. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17629. return false;
  17630. return true;
  17631. };
  17632. // Statics
  17633. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17634. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17635. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17636. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17637. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17638. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17639. return false;
  17640. return true;
  17641. };
  17642. return BoundingSphere;
  17643. }());
  17644. BABYLON.BoundingSphere = BoundingSphere;
  17645. })(BABYLON || (BABYLON = {}));
  17646. //# sourceMappingURL=babylon.boundingSphere.js.map
  17647. "use strict";
  17648. var BABYLON;
  17649. (function (BABYLON) {
  17650. var BoundingBox = /** @class */ (function () {
  17651. function BoundingBox(minimum, maximum) {
  17652. this.minimum = minimum;
  17653. this.maximum = maximum;
  17654. this.vectors = new Array();
  17655. this.vectorsWorld = new Array();
  17656. // Bounding vectors
  17657. this.vectors.push(this.minimum.clone());
  17658. this.vectors.push(this.maximum.clone());
  17659. this.vectors.push(this.minimum.clone());
  17660. this.vectors[2].x = this.maximum.x;
  17661. this.vectors.push(this.minimum.clone());
  17662. this.vectors[3].y = this.maximum.y;
  17663. this.vectors.push(this.minimum.clone());
  17664. this.vectors[4].z = this.maximum.z;
  17665. this.vectors.push(this.maximum.clone());
  17666. this.vectors[5].z = this.minimum.z;
  17667. this.vectors.push(this.maximum.clone());
  17668. this.vectors[6].x = this.minimum.x;
  17669. this.vectors.push(this.maximum.clone());
  17670. this.vectors[7].y = this.minimum.y;
  17671. // OBB
  17672. this.center = this.maximum.add(this.minimum).scale(0.5);
  17673. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17674. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17675. // World
  17676. for (var index = 0; index < this.vectors.length; index++) {
  17677. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17678. }
  17679. this.minimumWorld = BABYLON.Vector3.Zero();
  17680. this.maximumWorld = BABYLON.Vector3.Zero();
  17681. this.centerWorld = BABYLON.Vector3.Zero();
  17682. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17683. this._update(BABYLON.Matrix.Identity());
  17684. }
  17685. // Methods
  17686. BoundingBox.prototype.getWorldMatrix = function () {
  17687. return this._worldMatrix;
  17688. };
  17689. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17690. this._worldMatrix.copyFrom(matrix);
  17691. return this;
  17692. };
  17693. BoundingBox.prototype._update = function (world) {
  17694. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17695. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17696. for (var index = 0; index < this.vectors.length; index++) {
  17697. var v = this.vectorsWorld[index];
  17698. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17699. if (v.x < this.minimumWorld.x)
  17700. this.minimumWorld.x = v.x;
  17701. if (v.y < this.minimumWorld.y)
  17702. this.minimumWorld.y = v.y;
  17703. if (v.z < this.minimumWorld.z)
  17704. this.minimumWorld.z = v.z;
  17705. if (v.x > this.maximumWorld.x)
  17706. this.maximumWorld.x = v.x;
  17707. if (v.y > this.maximumWorld.y)
  17708. this.maximumWorld.y = v.y;
  17709. if (v.z > this.maximumWorld.z)
  17710. this.maximumWorld.z = v.z;
  17711. }
  17712. // Extend
  17713. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17714. this.extendSizeWorld.scaleInPlace(0.5);
  17715. // OBB
  17716. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17717. this.centerWorld.scaleInPlace(0.5);
  17718. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17719. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17720. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17721. this._worldMatrix = world;
  17722. };
  17723. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17724. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17725. };
  17726. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17727. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17728. };
  17729. BoundingBox.prototype.intersectsPoint = function (point) {
  17730. var delta = -BABYLON.Epsilon;
  17731. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17732. return false;
  17733. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17734. return false;
  17735. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17736. return false;
  17737. return true;
  17738. };
  17739. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17740. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17741. };
  17742. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17743. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17744. return false;
  17745. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17746. return false;
  17747. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17748. return false;
  17749. return true;
  17750. };
  17751. // Statics
  17752. BoundingBox.Intersects = function (box0, box1) {
  17753. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17754. return false;
  17755. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17756. return false;
  17757. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17758. return false;
  17759. return true;
  17760. };
  17761. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17762. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17763. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17764. return (num <= (sphereRadius * sphereRadius));
  17765. };
  17766. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17767. for (var p = 0; p < 6; p++) {
  17768. for (var i = 0; i < 8; i++) {
  17769. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17770. return false;
  17771. }
  17772. }
  17773. }
  17774. return true;
  17775. };
  17776. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17777. for (var p = 0; p < 6; p++) {
  17778. var inCount = 8;
  17779. for (var i = 0; i < 8; i++) {
  17780. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17781. --inCount;
  17782. }
  17783. else {
  17784. break;
  17785. }
  17786. }
  17787. if (inCount === 0)
  17788. return false;
  17789. }
  17790. return true;
  17791. };
  17792. return BoundingBox;
  17793. }());
  17794. BABYLON.BoundingBox = BoundingBox;
  17795. })(BABYLON || (BABYLON = {}));
  17796. //# sourceMappingURL=babylon.boundingBox.js.map
  17797. "use strict";
  17798. var BABYLON;
  17799. (function (BABYLON) {
  17800. var computeBoxExtents = function (axis, box) {
  17801. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17802. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17803. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17804. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17805. var r = r0 + r1 + r2;
  17806. return {
  17807. min: p - r,
  17808. max: p + r
  17809. };
  17810. };
  17811. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17812. var axisOverlap = function (axis, box0, box1) {
  17813. var result0 = computeBoxExtents(axis, box0);
  17814. var result1 = computeBoxExtents(axis, box1);
  17815. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17816. };
  17817. var BoundingInfo = /** @class */ (function () {
  17818. function BoundingInfo(minimum, maximum) {
  17819. this.minimum = minimum;
  17820. this.maximum = maximum;
  17821. this._isLocked = false;
  17822. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17823. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17824. }
  17825. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17826. get: function () {
  17827. return this._isLocked;
  17828. },
  17829. set: function (value) {
  17830. this._isLocked = value;
  17831. },
  17832. enumerable: true,
  17833. configurable: true
  17834. });
  17835. // Methods
  17836. BoundingInfo.prototype.update = function (world) {
  17837. if (this._isLocked) {
  17838. return;
  17839. }
  17840. this.boundingBox._update(world);
  17841. this.boundingSphere._update(world);
  17842. };
  17843. /**
  17844. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17845. * @param center New center of the bounding info
  17846. * @param extend New extend of the bounding info
  17847. */
  17848. BoundingInfo.prototype.centerOn = function (center, extend) {
  17849. this.minimum = center.subtract(extend);
  17850. this.maximum = center.add(extend);
  17851. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17852. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17853. return this;
  17854. };
  17855. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17856. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17857. return false;
  17858. return this.boundingBox.isInFrustum(frustumPlanes);
  17859. };
  17860. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17861. /**
  17862. * Gets the world distance between the min and max points of the bounding box
  17863. */
  17864. get: function () {
  17865. var boundingBox = this.boundingBox;
  17866. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  17867. return size.length();
  17868. },
  17869. enumerable: true,
  17870. configurable: true
  17871. });
  17872. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17873. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  17874. };
  17875. BoundingInfo.prototype._checkCollision = function (collider) {
  17876. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  17877. };
  17878. BoundingInfo.prototype.intersectsPoint = function (point) {
  17879. if (!this.boundingSphere.centerWorld) {
  17880. return false;
  17881. }
  17882. if (!this.boundingSphere.intersectsPoint(point)) {
  17883. return false;
  17884. }
  17885. if (!this.boundingBox.intersectsPoint(point)) {
  17886. return false;
  17887. }
  17888. return true;
  17889. };
  17890. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  17891. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  17892. return false;
  17893. }
  17894. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  17895. return false;
  17896. }
  17897. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  17898. return false;
  17899. }
  17900. if (!precise) {
  17901. return true;
  17902. }
  17903. var box0 = this.boundingBox;
  17904. var box1 = boundingInfo.boundingBox;
  17905. if (!axisOverlap(box0.directions[0], box0, box1))
  17906. return false;
  17907. if (!axisOverlap(box0.directions[1], box0, box1))
  17908. return false;
  17909. if (!axisOverlap(box0.directions[2], box0, box1))
  17910. return false;
  17911. if (!axisOverlap(box1.directions[0], box0, box1))
  17912. return false;
  17913. if (!axisOverlap(box1.directions[1], box0, box1))
  17914. return false;
  17915. if (!axisOverlap(box1.directions[2], box0, box1))
  17916. return false;
  17917. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  17918. return false;
  17919. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  17920. return false;
  17921. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  17922. return false;
  17923. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  17924. return false;
  17925. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  17926. return false;
  17927. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  17928. return false;
  17929. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  17930. return false;
  17931. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  17932. return false;
  17933. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  17934. return false;
  17935. return true;
  17936. };
  17937. return BoundingInfo;
  17938. }());
  17939. BABYLON.BoundingInfo = BoundingInfo;
  17940. })(BABYLON || (BABYLON = {}));
  17941. //# sourceMappingURL=babylon.boundingInfo.js.map
  17942. "use strict";
  17943. var BABYLON;
  17944. (function (BABYLON) {
  17945. var TransformNode = /** @class */ (function (_super) {
  17946. __extends(TransformNode, _super);
  17947. function TransformNode(name, scene, isPure) {
  17948. if (scene === void 0) { scene = null; }
  17949. if (isPure === void 0) { isPure = true; }
  17950. var _this = _super.call(this, name, scene) || this;
  17951. _this._forward = new BABYLON.Vector3(0, 0, 1);
  17952. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  17953. _this._up = new BABYLON.Vector3(0, 1, 0);
  17954. _this._right = new BABYLON.Vector3(1, 0, 0);
  17955. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  17956. // Properties
  17957. _this._rotation = BABYLON.Vector3.Zero();
  17958. _this._scaling = BABYLON.Vector3.One();
  17959. _this._isDirty = false;
  17960. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  17961. _this.scalingDeterminant = 1;
  17962. _this.infiniteDistance = false;
  17963. _this.position = BABYLON.Vector3.Zero();
  17964. _this._localWorld = BABYLON.Matrix.Zero();
  17965. _this._worldMatrix = BABYLON.Matrix.Zero();
  17966. _this._worldMatrixDeterminant = 0;
  17967. _this._absolutePosition = BABYLON.Vector3.Zero();
  17968. _this._pivotMatrix = BABYLON.Matrix.Identity();
  17969. _this._postMultiplyPivotMatrix = false;
  17970. _this._isWorldMatrixFrozen = false;
  17971. /**
  17972. * An event triggered after the world matrix is updated
  17973. */
  17974. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  17975. _this._nonUniformScaling = false;
  17976. if (isPure) {
  17977. _this.getScene().addTransformNode(_this);
  17978. }
  17979. return _this;
  17980. }
  17981. /**
  17982. * Gets a string idenfifying the name of the class
  17983. * @returns "TransformNode" string
  17984. */
  17985. TransformNode.prototype.getClassName = function () {
  17986. return "TransformNode";
  17987. };
  17988. Object.defineProperty(TransformNode.prototype, "rotation", {
  17989. /**
  17990. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  17991. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  17992. * Default : (0.0, 0.0, 0.0)
  17993. */
  17994. get: function () {
  17995. return this._rotation;
  17996. },
  17997. set: function (newRotation) {
  17998. this._rotation = newRotation;
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. Object.defineProperty(TransformNode.prototype, "scaling", {
  18004. /**
  18005. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18006. * Default : (1.0, 1.0, 1.0)
  18007. */
  18008. get: function () {
  18009. return this._scaling;
  18010. },
  18011. /**
  18012. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18013. * Default : (1.0, 1.0, 1.0)
  18014. */
  18015. set: function (newScaling) {
  18016. this._scaling = newScaling;
  18017. },
  18018. enumerable: true,
  18019. configurable: true
  18020. });
  18021. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18022. /**
  18023. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18024. * It's null by default.
  18025. * 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)
  18026. */
  18027. get: function () {
  18028. return this._rotationQuaternion;
  18029. },
  18030. set: function (quaternion) {
  18031. this._rotationQuaternion = quaternion;
  18032. //reset the rotation vector.
  18033. if (quaternion && this.rotation.length()) {
  18034. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18035. }
  18036. },
  18037. enumerable: true,
  18038. configurable: true
  18039. });
  18040. Object.defineProperty(TransformNode.prototype, "forward", {
  18041. /**
  18042. * The forward direction of that transform in world space.
  18043. */
  18044. get: function () {
  18045. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18046. },
  18047. enumerable: true,
  18048. configurable: true
  18049. });
  18050. Object.defineProperty(TransformNode.prototype, "up", {
  18051. /**
  18052. * The up direction of that transform in world space.
  18053. */
  18054. get: function () {
  18055. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18056. },
  18057. enumerable: true,
  18058. configurable: true
  18059. });
  18060. Object.defineProperty(TransformNode.prototype, "right", {
  18061. /**
  18062. * The right direction of that transform in world space.
  18063. */
  18064. get: function () {
  18065. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18066. },
  18067. enumerable: true,
  18068. configurable: true
  18069. });
  18070. /**
  18071. * Returns the latest update of the World matrix
  18072. * Returns a Matrix.
  18073. */
  18074. TransformNode.prototype.getWorldMatrix = function () {
  18075. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18076. this.computeWorldMatrix();
  18077. }
  18078. return this._worldMatrix;
  18079. };
  18080. /**
  18081. * Returns the latest update of the World matrix determinant.
  18082. */
  18083. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18084. return this._worldMatrixDeterminant;
  18085. };
  18086. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18087. /**
  18088. * Returns directly the latest state of the mesh World matrix.
  18089. * A Matrix is returned.
  18090. */
  18091. get: function () {
  18092. return this._worldMatrix;
  18093. },
  18094. enumerable: true,
  18095. configurable: true
  18096. });
  18097. /**
  18098. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18099. * Returns the TransformNode.
  18100. */
  18101. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18102. this._poseMatrix.copyFrom(matrix);
  18103. return this;
  18104. };
  18105. /**
  18106. * Returns the mesh Pose matrix.
  18107. * Returned object : Matrix
  18108. */
  18109. TransformNode.prototype.getPoseMatrix = function () {
  18110. return this._poseMatrix;
  18111. };
  18112. TransformNode.prototype._isSynchronized = function () {
  18113. if (this._isDirty) {
  18114. return false;
  18115. }
  18116. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18117. return false;
  18118. if (this._cache.pivotMatrixUpdated) {
  18119. return false;
  18120. }
  18121. if (this.infiniteDistance) {
  18122. return false;
  18123. }
  18124. if (!this._cache.position.equals(this.position))
  18125. return false;
  18126. if (this.rotationQuaternion) {
  18127. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18128. return false;
  18129. }
  18130. if (!this._cache.rotation.equals(this.rotation))
  18131. return false;
  18132. if (!this._cache.scaling.equals(this.scaling))
  18133. return false;
  18134. return true;
  18135. };
  18136. TransformNode.prototype._initCache = function () {
  18137. _super.prototype._initCache.call(this);
  18138. this._cache.localMatrixUpdated = false;
  18139. this._cache.position = BABYLON.Vector3.Zero();
  18140. this._cache.scaling = BABYLON.Vector3.Zero();
  18141. this._cache.rotation = BABYLON.Vector3.Zero();
  18142. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18143. this._cache.billboardMode = -1;
  18144. };
  18145. TransformNode.prototype.markAsDirty = function (property) {
  18146. if (property === "rotation") {
  18147. this.rotationQuaternion = null;
  18148. }
  18149. this._currentRenderId = Number.MAX_VALUE;
  18150. this._isDirty = true;
  18151. return this;
  18152. };
  18153. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18154. /**
  18155. * Returns the current mesh absolute position.
  18156. * Retuns a Vector3.
  18157. */
  18158. get: function () {
  18159. return this._absolutePosition;
  18160. },
  18161. enumerable: true,
  18162. configurable: true
  18163. });
  18164. /**
  18165. * Sets a new matrix to apply before all other transformation
  18166. * @param matrix defines the transform matrix
  18167. * @returns the current TransformNode
  18168. */
  18169. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18170. return this.setPivotMatrix(matrix, false);
  18171. };
  18172. /**
  18173. * Sets a new pivot matrix to the current node
  18174. * @param matrix defines the new pivot matrix to use
  18175. * @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
  18176. * @returns the current TransformNode
  18177. */
  18178. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18179. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18180. this._pivotMatrix = matrix.clone();
  18181. this._cache.pivotMatrixUpdated = true;
  18182. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18183. if (this._postMultiplyPivotMatrix) {
  18184. if (!this._pivotMatrixInverse) {
  18185. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18186. }
  18187. else {
  18188. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18189. }
  18190. }
  18191. return this;
  18192. };
  18193. /**
  18194. * Returns the mesh pivot matrix.
  18195. * Default : Identity.
  18196. * A Matrix is returned.
  18197. */
  18198. TransformNode.prototype.getPivotMatrix = function () {
  18199. return this._pivotMatrix;
  18200. };
  18201. /**
  18202. * Prevents the World matrix to be computed any longer.
  18203. * Returns the TransformNode.
  18204. */
  18205. TransformNode.prototype.freezeWorldMatrix = function () {
  18206. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18207. this.computeWorldMatrix(true);
  18208. this._isWorldMatrixFrozen = true;
  18209. return this;
  18210. };
  18211. /**
  18212. * Allows back the World matrix computation.
  18213. * Returns the TransformNode.
  18214. */
  18215. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18216. this._isWorldMatrixFrozen = false;
  18217. this.computeWorldMatrix(true);
  18218. return this;
  18219. };
  18220. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18221. /**
  18222. * True if the World matrix has been frozen.
  18223. * Returns a boolean.
  18224. */
  18225. get: function () {
  18226. return this._isWorldMatrixFrozen;
  18227. },
  18228. enumerable: true,
  18229. configurable: true
  18230. });
  18231. /**
  18232. * Retuns the mesh absolute position in the World.
  18233. * Returns a Vector3.
  18234. */
  18235. TransformNode.prototype.getAbsolutePosition = function () {
  18236. this.computeWorldMatrix();
  18237. return this._absolutePosition;
  18238. };
  18239. /**
  18240. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18241. * Returns the TransformNode.
  18242. */
  18243. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18244. if (!absolutePosition) {
  18245. return this;
  18246. }
  18247. var absolutePositionX;
  18248. var absolutePositionY;
  18249. var absolutePositionZ;
  18250. if (absolutePosition.x === undefined) {
  18251. if (arguments.length < 3) {
  18252. return this;
  18253. }
  18254. absolutePositionX = arguments[0];
  18255. absolutePositionY = arguments[1];
  18256. absolutePositionZ = arguments[2];
  18257. }
  18258. else {
  18259. absolutePositionX = absolutePosition.x;
  18260. absolutePositionY = absolutePosition.y;
  18261. absolutePositionZ = absolutePosition.z;
  18262. }
  18263. if (this.parent) {
  18264. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18265. invertParentWorldMatrix.invert();
  18266. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18267. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18268. }
  18269. else {
  18270. this.position.x = absolutePositionX;
  18271. this.position.y = absolutePositionY;
  18272. this.position.z = absolutePositionZ;
  18273. }
  18274. return this;
  18275. };
  18276. /**
  18277. * Sets the mesh position in its local space.
  18278. * Returns the TransformNode.
  18279. */
  18280. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18281. this.computeWorldMatrix();
  18282. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18283. return this;
  18284. };
  18285. /**
  18286. * Returns the mesh position in the local space from the current World matrix values.
  18287. * Returns a new Vector3.
  18288. */
  18289. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18290. this.computeWorldMatrix();
  18291. var invLocalWorldMatrix = this._localWorld.clone();
  18292. invLocalWorldMatrix.invert();
  18293. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18294. };
  18295. /**
  18296. * Translates the mesh along the passed Vector3 in its local space.
  18297. * Returns the TransformNode.
  18298. */
  18299. TransformNode.prototype.locallyTranslate = function (vector3) {
  18300. this.computeWorldMatrix(true);
  18301. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18302. return this;
  18303. };
  18304. /**
  18305. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18306. * @param targetPoint the position (must be in same space as current mesh) to look at
  18307. * @param yawCor optional yaw (y-axis) correction in radians
  18308. * @param pitchCor optional pitch (x-axis) correction in radians
  18309. * @param rollCor optional roll (z-axis) correction in radians
  18310. * @param space the choosen space of the target
  18311. * @returns the TransformNode.
  18312. */
  18313. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18314. if (yawCor === void 0) { yawCor = 0; }
  18315. if (pitchCor === void 0) { pitchCor = 0; }
  18316. if (rollCor === void 0) { rollCor = 0; }
  18317. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18318. var dv = TransformNode._lookAtVectorCache;
  18319. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18320. targetPoint.subtractToRef(pos, dv);
  18321. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18322. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18323. var pitch = Math.atan2(dv.y, len);
  18324. if (this.rotationQuaternion) {
  18325. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18326. }
  18327. else {
  18328. this.rotation.x = pitch + pitchCor;
  18329. this.rotation.y = yaw + yawCor;
  18330. this.rotation.z = rollCor;
  18331. }
  18332. return this;
  18333. };
  18334. /**
  18335. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18336. * This Vector3 is expressed in the World space.
  18337. */
  18338. TransformNode.prototype.getDirection = function (localAxis) {
  18339. var result = BABYLON.Vector3.Zero();
  18340. this.getDirectionToRef(localAxis, result);
  18341. return result;
  18342. };
  18343. /**
  18344. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18345. * localAxis is expressed in the mesh local space.
  18346. * result is computed in the Wordl space from the mesh World matrix.
  18347. * Returns the TransformNode.
  18348. */
  18349. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18350. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18351. return this;
  18352. };
  18353. /**
  18354. * Sets a new pivot point to the current node
  18355. * @param point defines the new pivot point to use
  18356. * @param space defines if the point is in world or local space (local by default)
  18357. * @returns the current TransformNode
  18358. */
  18359. TransformNode.prototype.setPivotPoint = function (point, space) {
  18360. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18361. if (this.getScene().getRenderId() == 0) {
  18362. this.computeWorldMatrix(true);
  18363. }
  18364. var wm = this.getWorldMatrix();
  18365. if (space == BABYLON.Space.WORLD) {
  18366. var tmat = BABYLON.Tmp.Matrix[0];
  18367. wm.invertToRef(tmat);
  18368. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18369. }
  18370. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18371. };
  18372. /**
  18373. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18374. */
  18375. TransformNode.prototype.getPivotPoint = function () {
  18376. var point = BABYLON.Vector3.Zero();
  18377. this.getPivotPointToRef(point);
  18378. return point;
  18379. };
  18380. /**
  18381. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18382. * Returns the TransformNode.
  18383. */
  18384. TransformNode.prototype.getPivotPointToRef = function (result) {
  18385. result.x = -this._pivotMatrix.m[12];
  18386. result.y = -this._pivotMatrix.m[13];
  18387. result.z = -this._pivotMatrix.m[14];
  18388. return this;
  18389. };
  18390. /**
  18391. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18392. */
  18393. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18394. var point = BABYLON.Vector3.Zero();
  18395. this.getAbsolutePivotPointToRef(point);
  18396. return point;
  18397. };
  18398. /**
  18399. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18400. * Returns the TransformNode.
  18401. */
  18402. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18403. result.x = this._pivotMatrix.m[12];
  18404. result.y = this._pivotMatrix.m[13];
  18405. result.z = this._pivotMatrix.m[14];
  18406. this.getPivotPointToRef(result);
  18407. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18408. return this;
  18409. };
  18410. /**
  18411. * Defines the passed node as the parent of the current node.
  18412. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18413. * Returns the TransformNode.
  18414. */
  18415. TransformNode.prototype.setParent = function (node) {
  18416. if (node === null) {
  18417. var rotation = BABYLON.Tmp.Quaternion[0];
  18418. var position = BABYLON.Tmp.Vector3[0];
  18419. var scale = BABYLON.Tmp.Vector3[1];
  18420. if (this.parent && this.parent.computeWorldMatrix) {
  18421. this.parent.computeWorldMatrix(true);
  18422. }
  18423. this.computeWorldMatrix(true);
  18424. this.getWorldMatrix().decompose(scale, rotation, position);
  18425. if (this.rotationQuaternion) {
  18426. this.rotationQuaternion.copyFrom(rotation);
  18427. }
  18428. else {
  18429. rotation.toEulerAnglesToRef(this.rotation);
  18430. }
  18431. this.scaling.x = scale.x;
  18432. this.scaling.y = scale.y;
  18433. this.scaling.z = scale.z;
  18434. this.position.x = position.x;
  18435. this.position.y = position.y;
  18436. this.position.z = position.z;
  18437. }
  18438. else {
  18439. var rotation = BABYLON.Tmp.Quaternion[0];
  18440. var position = BABYLON.Tmp.Vector3[0];
  18441. var scale = BABYLON.Tmp.Vector3[1];
  18442. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18443. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18444. this.computeWorldMatrix(true);
  18445. node.computeWorldMatrix(true);
  18446. node.getWorldMatrix().invertToRef(invParentMatrix);
  18447. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18448. diffMatrix.decompose(scale, rotation, position);
  18449. if (this.rotationQuaternion) {
  18450. this.rotationQuaternion.copyFrom(rotation);
  18451. }
  18452. else {
  18453. rotation.toEulerAnglesToRef(this.rotation);
  18454. }
  18455. this.position.x = position.x;
  18456. this.position.y = position.y;
  18457. this.position.z = position.z;
  18458. this.scaling.x = scale.x;
  18459. this.scaling.y = scale.y;
  18460. this.scaling.z = scale.z;
  18461. }
  18462. this.parent = node;
  18463. return this;
  18464. };
  18465. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18466. get: function () {
  18467. return this._nonUniformScaling;
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18473. if (this._nonUniformScaling === value) {
  18474. return false;
  18475. }
  18476. this._nonUniformScaling = true;
  18477. return true;
  18478. };
  18479. /**
  18480. * Attach the current TransformNode to another TransformNode associated with a bone
  18481. * @param bone Bone affecting the TransformNode
  18482. * @param affectedTransformNode TransformNode associated with the bone
  18483. */
  18484. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18485. this._transformToBoneReferal = affectedTransformNode;
  18486. this.parent = bone;
  18487. if (bone.getWorldMatrix().determinant() < 0) {
  18488. this.scalingDeterminant *= -1;
  18489. }
  18490. return this;
  18491. };
  18492. TransformNode.prototype.detachFromBone = function () {
  18493. if (!this.parent) {
  18494. return this;
  18495. }
  18496. if (this.parent.getWorldMatrix().determinant() < 0) {
  18497. this.scalingDeterminant *= -1;
  18498. }
  18499. this._transformToBoneReferal = null;
  18500. this.parent = null;
  18501. return this;
  18502. };
  18503. /**
  18504. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18505. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18506. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18507. * The passed axis is also normalized.
  18508. * Returns the TransformNode.
  18509. */
  18510. TransformNode.prototype.rotate = function (axis, amount, space) {
  18511. axis.normalize();
  18512. if (!this.rotationQuaternion) {
  18513. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18514. this.rotation = BABYLON.Vector3.Zero();
  18515. }
  18516. var rotationQuaternion;
  18517. if (!space || space === BABYLON.Space.LOCAL) {
  18518. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18519. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18520. }
  18521. else {
  18522. if (this.parent) {
  18523. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18524. invertParentWorldMatrix.invert();
  18525. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18526. }
  18527. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18528. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18529. }
  18530. return this;
  18531. };
  18532. /**
  18533. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18534. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18535. * The passed axis is also normalized.
  18536. * Returns the TransformNode.
  18537. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18538. */
  18539. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18540. axis.normalize();
  18541. if (!this.rotationQuaternion) {
  18542. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18543. this.rotation.copyFromFloats(0, 0, 0);
  18544. }
  18545. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18546. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18547. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18548. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18549. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18550. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18551. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18552. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18553. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18554. return this;
  18555. };
  18556. /**
  18557. * Translates the mesh along the axis vector for the passed distance in the given space.
  18558. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18559. * Returns the TransformNode.
  18560. */
  18561. TransformNode.prototype.translate = function (axis, distance, space) {
  18562. var displacementVector = axis.scale(distance);
  18563. if (!space || space === BABYLON.Space.LOCAL) {
  18564. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18565. this.setPositionWithLocalVector(tempV3);
  18566. }
  18567. else {
  18568. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18569. }
  18570. return this;
  18571. };
  18572. /**
  18573. * Adds a rotation step to the mesh current rotation.
  18574. * x, y, z are Euler angles expressed in radians.
  18575. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18576. * This means this rotation is made in the mesh local space only.
  18577. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18578. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18579. * ```javascript
  18580. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18581. * ```
  18582. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18583. * 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.
  18584. * Returns the TransformNode.
  18585. */
  18586. TransformNode.prototype.addRotation = function (x, y, z) {
  18587. var rotationQuaternion;
  18588. if (this.rotationQuaternion) {
  18589. rotationQuaternion = this.rotationQuaternion;
  18590. }
  18591. else {
  18592. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18593. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18594. }
  18595. var accumulation = BABYLON.Tmp.Quaternion[0];
  18596. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18597. rotationQuaternion.multiplyInPlace(accumulation);
  18598. if (!this.rotationQuaternion) {
  18599. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18600. }
  18601. return this;
  18602. };
  18603. /**
  18604. * Computes the mesh World matrix and returns it.
  18605. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18606. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18607. * If the parameter `force`is set to `true`, the actual computation is done.
  18608. * Returns the mesh World Matrix.
  18609. */
  18610. TransformNode.prototype.computeWorldMatrix = function (force) {
  18611. if (this._isWorldMatrixFrozen) {
  18612. return this._worldMatrix;
  18613. }
  18614. if (!force && this.isSynchronized(true)) {
  18615. this._currentRenderId = this.getScene().getRenderId();
  18616. return this._worldMatrix;
  18617. }
  18618. this._cache.position.copyFrom(this.position);
  18619. this._cache.scaling.copyFrom(this.scaling);
  18620. this._cache.pivotMatrixUpdated = false;
  18621. this._cache.billboardMode = this.billboardMode;
  18622. this._currentRenderId = this.getScene().getRenderId();
  18623. this._childRenderId = this.getScene().getRenderId();
  18624. this._isDirty = false;
  18625. // Scaling
  18626. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18627. // Rotation
  18628. //rotate, if quaternion is set and rotation was used
  18629. if (this.rotationQuaternion) {
  18630. var len = this.rotation.length();
  18631. if (len) {
  18632. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18633. this.rotation.copyFromFloats(0, 0, 0);
  18634. }
  18635. }
  18636. if (this.rotationQuaternion) {
  18637. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18638. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18639. }
  18640. else {
  18641. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18642. this._cache.rotation.copyFrom(this.rotation);
  18643. }
  18644. // Translation
  18645. var camera = this.getScene().activeCamera;
  18646. if (this.infiniteDistance && !this.parent && camera) {
  18647. var cameraWorldMatrix = camera.getWorldMatrix();
  18648. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18649. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18650. }
  18651. else {
  18652. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18653. }
  18654. // Composing transformations
  18655. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18656. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18657. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18658. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18659. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18660. // Need to decompose each rotation here
  18661. var currentPosition = BABYLON.Tmp.Vector3[3];
  18662. if (this.parent && this.parent.getWorldMatrix) {
  18663. if (this._transformToBoneReferal) {
  18664. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18665. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18666. }
  18667. else {
  18668. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18669. }
  18670. }
  18671. else {
  18672. currentPosition.copyFrom(this.position);
  18673. }
  18674. currentPosition.subtractInPlace(camera.globalPosition);
  18675. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18676. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18677. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18678. }
  18679. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18680. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18681. }
  18682. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18683. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18684. }
  18685. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18686. }
  18687. else {
  18688. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18689. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18690. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18691. }
  18692. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18693. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18694. }
  18695. // Local world
  18696. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18697. // Parent
  18698. if (this.parent && this.parent.getWorldMatrix) {
  18699. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18700. if (this._transformToBoneReferal) {
  18701. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18702. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18703. }
  18704. else {
  18705. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18706. }
  18707. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18708. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18709. this._worldMatrix.copyFrom(this._localWorld);
  18710. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18711. }
  18712. else {
  18713. if (this._transformToBoneReferal) {
  18714. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18715. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18716. }
  18717. else {
  18718. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18719. }
  18720. }
  18721. this._markSyncedWithParent();
  18722. }
  18723. else {
  18724. this._worldMatrix.copyFrom(this._localWorld);
  18725. }
  18726. // Post multiply inverse of pivotMatrix
  18727. if (this._postMultiplyPivotMatrix) {
  18728. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18729. }
  18730. // Normal matrix
  18731. if (this.scaling.isNonUniform) {
  18732. this._updateNonUniformScalingState(true);
  18733. }
  18734. else if (this.parent && this.parent._nonUniformScaling) {
  18735. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18736. }
  18737. else {
  18738. this._updateNonUniformScalingState(false);
  18739. }
  18740. this._afterComputeWorldMatrix();
  18741. // Absolute position
  18742. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18743. // Callbacks
  18744. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18745. if (!this._poseMatrix) {
  18746. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18747. }
  18748. // Cache the determinant
  18749. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18750. return this._worldMatrix;
  18751. };
  18752. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18753. };
  18754. /**
  18755. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18756. * @param func: callback function to add
  18757. *
  18758. * Returns the TransformNode.
  18759. */
  18760. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18761. this.onAfterWorldMatrixUpdateObservable.add(func);
  18762. return this;
  18763. };
  18764. /**
  18765. * Removes a registered callback function.
  18766. * Returns the TransformNode.
  18767. */
  18768. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18769. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18770. return this;
  18771. };
  18772. /**
  18773. * Clone the current transform node
  18774. * Returns the new transform node
  18775. * @param name Name of the new clone
  18776. * @param newParent New parent for the clone
  18777. * @param doNotCloneChildren Do not clone children hierarchy
  18778. */
  18779. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18780. var _this = this;
  18781. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18782. result.name = name;
  18783. result.id = name;
  18784. if (newParent) {
  18785. result.parent = newParent;
  18786. }
  18787. if (!doNotCloneChildren) {
  18788. // Children
  18789. var directDescendants = this.getDescendants(true);
  18790. for (var index = 0; index < directDescendants.length; index++) {
  18791. var child = directDescendants[index];
  18792. if (child.clone) {
  18793. child.clone(name + "." + child.name, result);
  18794. }
  18795. }
  18796. }
  18797. return result;
  18798. };
  18799. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18800. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18801. serializationObject.type = this.getClassName();
  18802. // Parent
  18803. if (this.parent) {
  18804. serializationObject.parentId = this.parent.id;
  18805. }
  18806. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18807. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18808. }
  18809. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18810. serializationObject.isEnabled = this.isEnabled();
  18811. // Parent
  18812. if (this.parent) {
  18813. serializationObject.parentId = this.parent.id;
  18814. }
  18815. return serializationObject;
  18816. };
  18817. // Statics
  18818. /**
  18819. * Returns a new TransformNode object parsed from the source provided.
  18820. * The parameter `parsedMesh` is the source.
  18821. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18822. */
  18823. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18824. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18825. if (BABYLON.Tags) {
  18826. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18827. }
  18828. if (parsedTransformNode.localMatrix) {
  18829. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18830. }
  18831. else if (parsedTransformNode.pivotMatrix) {
  18832. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18833. }
  18834. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18835. // Parent
  18836. if (parsedTransformNode.parentId) {
  18837. transformNode._waitingParentId = parsedTransformNode.parentId;
  18838. }
  18839. return transformNode;
  18840. };
  18841. /**
  18842. * Releases resources associated with this transform node.
  18843. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18844. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18845. */
  18846. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18847. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18848. // Animations
  18849. this.getScene().stopAnimation(this);
  18850. // Remove from scene
  18851. this.getScene().removeTransformNode(this);
  18852. this.onAfterWorldMatrixUpdateObservable.clear();
  18853. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18854. };
  18855. // Statics
  18856. TransformNode.BILLBOARDMODE_NONE = 0;
  18857. TransformNode.BILLBOARDMODE_X = 1;
  18858. TransformNode.BILLBOARDMODE_Y = 2;
  18859. TransformNode.BILLBOARDMODE_Z = 4;
  18860. TransformNode.BILLBOARDMODE_ALL = 7;
  18861. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18862. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  18863. __decorate([
  18864. BABYLON.serializeAsVector3()
  18865. ], TransformNode.prototype, "_rotation", void 0);
  18866. __decorate([
  18867. BABYLON.serializeAsQuaternion()
  18868. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  18869. __decorate([
  18870. BABYLON.serializeAsVector3()
  18871. ], TransformNode.prototype, "_scaling", void 0);
  18872. __decorate([
  18873. BABYLON.serialize()
  18874. ], TransformNode.prototype, "billboardMode", void 0);
  18875. __decorate([
  18876. BABYLON.serialize()
  18877. ], TransformNode.prototype, "scalingDeterminant", void 0);
  18878. __decorate([
  18879. BABYLON.serialize()
  18880. ], TransformNode.prototype, "infiniteDistance", void 0);
  18881. __decorate([
  18882. BABYLON.serializeAsVector3()
  18883. ], TransformNode.prototype, "position", void 0);
  18884. return TransformNode;
  18885. }(BABYLON.Node));
  18886. BABYLON.TransformNode = TransformNode;
  18887. })(BABYLON || (BABYLON = {}));
  18888. //# sourceMappingURL=babylon.transformNode.js.map
  18889. "use strict";
  18890. var BABYLON;
  18891. (function (BABYLON) {
  18892. var AbstractMesh = /** @class */ (function (_super) {
  18893. __extends(AbstractMesh, _super);
  18894. // Constructor
  18895. function AbstractMesh(name, scene) {
  18896. if (scene === void 0) { scene = null; }
  18897. var _this = _super.call(this, name, scene, false) || this;
  18898. _this._facetNb = 0; // facet number
  18899. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  18900. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  18901. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  18902. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  18903. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  18904. _this._subDiv = {
  18905. max: 1,
  18906. X: 1,
  18907. Y: 1,
  18908. Z: 1
  18909. };
  18910. _this._facetDepthSort = false; // is the facet depth sort to be computed
  18911. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  18912. // Events
  18913. /**
  18914. * An event triggered when this mesh collides with another one
  18915. */
  18916. _this.onCollideObservable = new BABYLON.Observable();
  18917. /**
  18918. * An event triggered when the collision's position changes
  18919. */
  18920. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  18921. /**
  18922. * An event triggered when material is changed
  18923. */
  18924. _this.onMaterialChangedObservable = new BABYLON.Observable();
  18925. // Properties
  18926. _this.definedFacingForward = true; // orientation for POV movement & rotation
  18927. /**
  18928. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  18929. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  18930. * or
  18931. * 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.
  18932. * for more info check WebGl documentations
  18933. */
  18934. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  18935. /**
  18936. * 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:
  18937. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  18938. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  18939. * 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.
  18940. */
  18941. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  18942. /**
  18943. * 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.
  18944. * The default value is -1 which means don't break the query and wait till the result.
  18945. */
  18946. _this.occlusionRetryCount = -1;
  18947. _this._occlusionInternalRetryCounter = 0;
  18948. _this._isOccluded = false;
  18949. _this._isOcclusionQueryInProgress = false;
  18950. _this._visibility = 1.0;
  18951. _this.alphaIndex = Number.MAX_VALUE;
  18952. _this.isVisible = true;
  18953. _this.isPickable = true;
  18954. _this.showBoundingBox = false;
  18955. _this.showSubMeshesBoundingBox = false;
  18956. _this.isBlocker = false;
  18957. _this.enablePointerMoveEvents = false;
  18958. _this.renderingGroupId = 0;
  18959. _this._receiveShadows = false;
  18960. _this.renderOutline = false;
  18961. _this.outlineColor = BABYLON.Color3.Red();
  18962. _this.outlineWidth = 0.02;
  18963. _this.renderOverlay = false;
  18964. _this.overlayColor = BABYLON.Color3.Red();
  18965. _this.overlayAlpha = 0.5;
  18966. _this._hasVertexAlpha = false;
  18967. _this._useVertexColors = true;
  18968. _this._computeBonesUsingShaders = true;
  18969. _this._numBoneInfluencers = 4;
  18970. _this._applyFog = true;
  18971. _this.useOctreeForRenderingSelection = true;
  18972. _this.useOctreeForPicking = true;
  18973. _this.useOctreeForCollisions = true;
  18974. _this._layerMask = 0x0FFFFFFF;
  18975. /**
  18976. * True if the mesh must be rendered in any case.
  18977. */
  18978. _this.alwaysSelectAsActiveMesh = false;
  18979. /**
  18980. * This scene's action manager
  18981. */
  18982. _this.actionManager = null;
  18983. // Physics
  18984. _this.physicsImpostor = null;
  18985. // Collisions
  18986. _this._checkCollisions = false;
  18987. _this._collisionMask = -1;
  18988. _this._collisionGroup = -1;
  18989. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  18990. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  18991. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18992. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18993. // Edges
  18994. _this.edgesWidth = 1;
  18995. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  18996. // Cache
  18997. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  18998. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  18999. _this._renderId = 0;
  19000. _this._intersectionsInProgress = new Array();
  19001. _this._unIndexed = false;
  19002. _this._lightSources = new Array();
  19003. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19004. if (collidedMesh === void 0) { collidedMesh = null; }
  19005. //TODO move this to the collision coordinator!
  19006. if (_this.getScene().workerCollisions)
  19007. newPosition.multiplyInPlace(_this._collider._radius);
  19008. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19009. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19010. _this.position.addInPlace(_this._diffPositionForCollisions);
  19011. }
  19012. if (collidedMesh) {
  19013. _this.onCollideObservable.notifyObservers(collidedMesh);
  19014. }
  19015. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19016. };
  19017. _this.getScene().addMesh(_this);
  19018. _this._resyncLightSources();
  19019. return _this;
  19020. }
  19021. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19022. get: function () {
  19023. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19024. },
  19025. enumerable: true,
  19026. configurable: true
  19027. });
  19028. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19029. get: function () {
  19030. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19031. },
  19032. enumerable: true,
  19033. configurable: true
  19034. });
  19035. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19036. get: function () {
  19037. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19038. },
  19039. enumerable: true,
  19040. configurable: true
  19041. });
  19042. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19043. get: function () {
  19044. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19045. },
  19046. enumerable: true,
  19047. configurable: true
  19048. });
  19049. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19050. get: function () {
  19051. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19052. },
  19053. enumerable: true,
  19054. configurable: true
  19055. });
  19056. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19057. /**
  19058. * Read-only : the number of facets in the mesh
  19059. */
  19060. get: function () {
  19061. return this._facetNb;
  19062. },
  19063. enumerable: true,
  19064. configurable: true
  19065. });
  19066. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19067. /**
  19068. * The number (integer) of subdivisions per axis in the partioning space
  19069. */
  19070. get: function () {
  19071. return this._partitioningSubdivisions;
  19072. },
  19073. set: function (nb) {
  19074. this._partitioningSubdivisions = nb;
  19075. },
  19076. enumerable: true,
  19077. configurable: true
  19078. });
  19079. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19080. /**
  19081. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19082. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  19083. */
  19084. get: function () {
  19085. return this._partitioningBBoxRatio;
  19086. },
  19087. set: function (ratio) {
  19088. this._partitioningBBoxRatio = ratio;
  19089. },
  19090. enumerable: true,
  19091. configurable: true
  19092. });
  19093. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19094. /**
  19095. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  19096. * Works only for updatable meshes.
  19097. * Doesn't work with multi-materials.
  19098. */
  19099. get: function () {
  19100. return this._facetDepthSort;
  19101. },
  19102. set: function (sort) {
  19103. this._facetDepthSort = sort;
  19104. },
  19105. enumerable: true,
  19106. configurable: true
  19107. });
  19108. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19109. /**
  19110. * The location (Vector3) where the facet depth sort must be computed from.
  19111. * By default, the active camera position.
  19112. * Used only when facet depth sort is enabled.
  19113. */
  19114. get: function () {
  19115. return this._facetDepthSortFrom;
  19116. },
  19117. set: function (location) {
  19118. this._facetDepthSortFrom = location;
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19124. /**
  19125. * Read-only boolean : is the feature facetData enabled ?
  19126. */
  19127. get: function () {
  19128. return this._facetDataEnabled;
  19129. },
  19130. enumerable: true,
  19131. configurable: true
  19132. });
  19133. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19134. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19135. return false;
  19136. }
  19137. this._markSubMeshesAsMiscDirty();
  19138. return true;
  19139. };
  19140. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19141. set: function (callback) {
  19142. if (this._onCollideObserver) {
  19143. this.onCollideObservable.remove(this._onCollideObserver);
  19144. }
  19145. this._onCollideObserver = this.onCollideObservable.add(callback);
  19146. },
  19147. enumerable: true,
  19148. configurable: true
  19149. });
  19150. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19151. set: function (callback) {
  19152. if (this._onCollisionPositionChangeObserver) {
  19153. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19154. }
  19155. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19156. },
  19157. enumerable: true,
  19158. configurable: true
  19159. });
  19160. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19161. /**
  19162. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  19163. */
  19164. get: function () {
  19165. return this._isOccluded;
  19166. },
  19167. set: function (value) {
  19168. this._isOccluded = value;
  19169. },
  19170. enumerable: true,
  19171. configurable: true
  19172. });
  19173. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19174. /**
  19175. * Flag to check the progress status of the query
  19176. */
  19177. get: function () {
  19178. return this._isOcclusionQueryInProgress;
  19179. },
  19180. enumerable: true,
  19181. configurable: true
  19182. });
  19183. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19184. /**
  19185. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19186. */
  19187. get: function () {
  19188. return this._visibility;
  19189. },
  19190. /**
  19191. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19192. */
  19193. set: function (value) {
  19194. if (this._visibility === value) {
  19195. return;
  19196. }
  19197. this._visibility = value;
  19198. this._markSubMeshesAsMiscDirty();
  19199. },
  19200. enumerable: true,
  19201. configurable: true
  19202. });
  19203. Object.defineProperty(AbstractMesh.prototype, "material", {
  19204. get: function () {
  19205. return this._material;
  19206. },
  19207. set: function (value) {
  19208. if (this._material === value) {
  19209. return;
  19210. }
  19211. this._material = value;
  19212. if (this.onMaterialChangedObservable.hasObservers) {
  19213. this.onMaterialChangedObservable.notifyObservers(this);
  19214. }
  19215. if (!this.subMeshes) {
  19216. return;
  19217. }
  19218. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19219. var subMesh = _a[_i];
  19220. subMesh.setEffect(null);
  19221. }
  19222. },
  19223. enumerable: true,
  19224. configurable: true
  19225. });
  19226. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19227. get: function () {
  19228. return this._receiveShadows;
  19229. },
  19230. set: function (value) {
  19231. if (this._receiveShadows === value) {
  19232. return;
  19233. }
  19234. this._receiveShadows = value;
  19235. this._markSubMeshesAsLightDirty();
  19236. },
  19237. enumerable: true,
  19238. configurable: true
  19239. });
  19240. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19241. get: function () {
  19242. return this._hasVertexAlpha;
  19243. },
  19244. set: function (value) {
  19245. if (this._hasVertexAlpha === value) {
  19246. return;
  19247. }
  19248. this._hasVertexAlpha = value;
  19249. this._markSubMeshesAsAttributesDirty();
  19250. this._markSubMeshesAsMiscDirty();
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19256. get: function () {
  19257. return this._useVertexColors;
  19258. },
  19259. set: function (value) {
  19260. if (this._useVertexColors === value) {
  19261. return;
  19262. }
  19263. this._useVertexColors = value;
  19264. this._markSubMeshesAsAttributesDirty();
  19265. },
  19266. enumerable: true,
  19267. configurable: true
  19268. });
  19269. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19270. get: function () {
  19271. return this._computeBonesUsingShaders;
  19272. },
  19273. set: function (value) {
  19274. if (this._computeBonesUsingShaders === value) {
  19275. return;
  19276. }
  19277. this._computeBonesUsingShaders = value;
  19278. this._markSubMeshesAsAttributesDirty();
  19279. },
  19280. enumerable: true,
  19281. configurable: true
  19282. });
  19283. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19284. get: function () {
  19285. return this._numBoneInfluencers;
  19286. },
  19287. set: function (value) {
  19288. if (this._numBoneInfluencers === value) {
  19289. return;
  19290. }
  19291. this._numBoneInfluencers = value;
  19292. this._markSubMeshesAsAttributesDirty();
  19293. },
  19294. enumerable: true,
  19295. configurable: true
  19296. });
  19297. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19298. get: function () {
  19299. return this._applyFog;
  19300. },
  19301. set: function (value) {
  19302. if (this._applyFog === value) {
  19303. return;
  19304. }
  19305. this._applyFog = value;
  19306. this._markSubMeshesAsMiscDirty();
  19307. },
  19308. enumerable: true,
  19309. configurable: true
  19310. });
  19311. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19312. get: function () {
  19313. return this._layerMask;
  19314. },
  19315. set: function (value) {
  19316. if (value === this._layerMask) {
  19317. return;
  19318. }
  19319. this._layerMask = value;
  19320. this._resyncLightSources();
  19321. },
  19322. enumerable: true,
  19323. configurable: true
  19324. });
  19325. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19326. get: function () {
  19327. return this._collisionMask;
  19328. },
  19329. set: function (mask) {
  19330. this._collisionMask = !isNaN(mask) ? mask : -1;
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19336. get: function () {
  19337. return this._collisionGroup;
  19338. },
  19339. set: function (mask) {
  19340. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19341. },
  19342. enumerable: true,
  19343. configurable: true
  19344. });
  19345. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19346. get: function () {
  19347. return null;
  19348. },
  19349. enumerable: true,
  19350. configurable: true
  19351. });
  19352. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19353. get: function () {
  19354. return this._skeleton;
  19355. },
  19356. set: function (value) {
  19357. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19358. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19359. }
  19360. if (value && value.needInitialSkinMatrix) {
  19361. value._registerMeshWithPoseMatrix(this);
  19362. }
  19363. this._skeleton = value;
  19364. if (!this._skeleton) {
  19365. this._bonesTransformMatrices = null;
  19366. }
  19367. this._markSubMeshesAsAttributesDirty();
  19368. },
  19369. enumerable: true,
  19370. configurable: true
  19371. });
  19372. /**
  19373. * Returns the string "AbstractMesh"
  19374. */
  19375. AbstractMesh.prototype.getClassName = function () {
  19376. return "AbstractMesh";
  19377. };
  19378. /**
  19379. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19380. */
  19381. AbstractMesh.prototype.toString = function (fullDetails) {
  19382. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19383. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19384. if (this._skeleton) {
  19385. ret += ", skeleton: " + this._skeleton.name;
  19386. }
  19387. if (fullDetails) {
  19388. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19389. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19390. }
  19391. return ret;
  19392. };
  19393. AbstractMesh.prototype._rebuild = function () {
  19394. if (this._occlusionQuery) {
  19395. this._occlusionQuery = null;
  19396. }
  19397. if (this._edgesRenderer) {
  19398. this._edgesRenderer._rebuild();
  19399. }
  19400. if (!this.subMeshes) {
  19401. return;
  19402. }
  19403. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19404. var subMesh = _a[_i];
  19405. subMesh._rebuild();
  19406. }
  19407. };
  19408. AbstractMesh.prototype._resyncLightSources = function () {
  19409. this._lightSources.length = 0;
  19410. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19411. var light = _a[_i];
  19412. if (!light.isEnabled()) {
  19413. continue;
  19414. }
  19415. if (light.canAffectMesh(this)) {
  19416. this._lightSources.push(light);
  19417. }
  19418. }
  19419. this._markSubMeshesAsLightDirty();
  19420. };
  19421. AbstractMesh.prototype._resyncLighSource = function (light) {
  19422. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19423. var index = this._lightSources.indexOf(light);
  19424. if (index === -1) {
  19425. if (!isIn) {
  19426. return;
  19427. }
  19428. this._lightSources.push(light);
  19429. }
  19430. else {
  19431. if (isIn) {
  19432. return;
  19433. }
  19434. this._lightSources.splice(index, 1);
  19435. }
  19436. this._markSubMeshesAsLightDirty();
  19437. };
  19438. AbstractMesh.prototype._removeLightSource = function (light) {
  19439. var index = this._lightSources.indexOf(light);
  19440. if (index === -1) {
  19441. return;
  19442. }
  19443. this._lightSources.splice(index, 1);
  19444. this._markSubMeshesAsLightDirty();
  19445. };
  19446. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19447. if (!this.subMeshes) {
  19448. return;
  19449. }
  19450. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19451. var subMesh = _a[_i];
  19452. if (subMesh._materialDefines) {
  19453. func(subMesh._materialDefines);
  19454. }
  19455. }
  19456. };
  19457. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19458. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19459. };
  19460. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19461. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19462. };
  19463. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19464. if (!this.subMeshes) {
  19465. return;
  19466. }
  19467. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19468. var subMesh = _a[_i];
  19469. var material = subMesh.getMaterial();
  19470. if (material) {
  19471. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19472. }
  19473. }
  19474. };
  19475. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19476. /**
  19477. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19478. * Default : (1.0, 1.0, 1.0)
  19479. */
  19480. get: function () {
  19481. return this._scaling;
  19482. },
  19483. /**
  19484. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19485. * Default : (1.0, 1.0, 1.0)
  19486. */
  19487. set: function (newScaling) {
  19488. this._scaling = newScaling;
  19489. if (this.physicsImpostor) {
  19490. this.physicsImpostor.forceUpdate();
  19491. }
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. // Methods
  19497. /**
  19498. * Disables the mesh edger rendering mode.
  19499. * Returns the AbstractMesh.
  19500. */
  19501. AbstractMesh.prototype.disableEdgesRendering = function () {
  19502. if (this._edgesRenderer) {
  19503. this._edgesRenderer.dispose();
  19504. this._edgesRenderer = null;
  19505. }
  19506. return this;
  19507. };
  19508. /**
  19509. * Enables the edge rendering mode on the mesh.
  19510. * This mode makes the mesh edges visible.
  19511. * Returns the AbstractMesh.
  19512. */
  19513. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19514. if (epsilon === void 0) { epsilon = 0.95; }
  19515. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19516. this.disableEdgesRendering();
  19517. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19518. return this;
  19519. };
  19520. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19521. /**
  19522. * Returns true if the mesh is blocked. Used by the class Mesh.
  19523. * Returns the boolean `false` by default.
  19524. */
  19525. get: function () {
  19526. return false;
  19527. },
  19528. enumerable: true,
  19529. configurable: true
  19530. });
  19531. /**
  19532. * Returns the mesh itself by default, used by the class Mesh.
  19533. * Returned type : AbstractMesh
  19534. */
  19535. AbstractMesh.prototype.getLOD = function (camera) {
  19536. return this;
  19537. };
  19538. /**
  19539. * Returns 0 by default, used by the class Mesh.
  19540. * Returns an integer.
  19541. */
  19542. AbstractMesh.prototype.getTotalVertices = function () {
  19543. return 0;
  19544. };
  19545. /**
  19546. * Returns null by default, used by the class Mesh.
  19547. * Returned type : integer array
  19548. */
  19549. AbstractMesh.prototype.getIndices = function () {
  19550. return null;
  19551. };
  19552. /**
  19553. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19554. * Returned type : float array or Float32Array
  19555. */
  19556. AbstractMesh.prototype.getVerticesData = function (kind) {
  19557. return null;
  19558. };
  19559. /**
  19560. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19561. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19562. * The `data` are either a numeric array either a Float32Array.
  19563. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19564. * 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).
  19565. * Note that a new underlying VertexBuffer object is created each call.
  19566. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19567. *
  19568. * Possible `kind` values :
  19569. * - BABYLON.VertexBuffer.PositionKind
  19570. * - BABYLON.VertexBuffer.UVKind
  19571. * - BABYLON.VertexBuffer.UV2Kind
  19572. * - BABYLON.VertexBuffer.UV3Kind
  19573. * - BABYLON.VertexBuffer.UV4Kind
  19574. * - BABYLON.VertexBuffer.UV5Kind
  19575. * - BABYLON.VertexBuffer.UV6Kind
  19576. * - BABYLON.VertexBuffer.ColorKind
  19577. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19578. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19579. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19580. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19581. *
  19582. * Returns the Mesh.
  19583. */
  19584. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19585. return this;
  19586. };
  19587. /**
  19588. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19589. * If the mesh has no geometry, it is simply returned as it is.
  19590. * The `data` are either a numeric array either a Float32Array.
  19591. * No new underlying VertexBuffer object is created.
  19592. * 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.
  19593. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19594. *
  19595. * Possible `kind` values :
  19596. * - BABYLON.VertexBuffer.PositionKind
  19597. * - BABYLON.VertexBuffer.UVKind
  19598. * - BABYLON.VertexBuffer.UV2Kind
  19599. * - BABYLON.VertexBuffer.UV3Kind
  19600. * - BABYLON.VertexBuffer.UV4Kind
  19601. * - BABYLON.VertexBuffer.UV5Kind
  19602. * - BABYLON.VertexBuffer.UV6Kind
  19603. * - BABYLON.VertexBuffer.ColorKind
  19604. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19605. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19606. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19607. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19608. *
  19609. * Returns the Mesh.
  19610. */
  19611. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19612. return this;
  19613. };
  19614. /**
  19615. * Sets the mesh indices.
  19616. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19617. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19618. * This method creates a new index buffer each call.
  19619. * Returns the Mesh.
  19620. */
  19621. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19622. return this;
  19623. };
  19624. /** Returns false by default, used by the class Mesh.
  19625. * Returns a boolean
  19626. */
  19627. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19628. return false;
  19629. };
  19630. /**
  19631. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19632. * Returns a BoundingInfo
  19633. */
  19634. AbstractMesh.prototype.getBoundingInfo = function () {
  19635. if (this._masterMesh) {
  19636. return this._masterMesh.getBoundingInfo();
  19637. }
  19638. if (!this._boundingInfo) {
  19639. // this._boundingInfo is being created here
  19640. this._updateBoundingInfo();
  19641. }
  19642. // cannot be null.
  19643. return this._boundingInfo;
  19644. };
  19645. /**
  19646. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19647. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19648. */
  19649. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19650. if (includeDescendants === void 0) { includeDescendants = true; }
  19651. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19652. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19653. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19654. if (maxDimension === 0) {
  19655. return this;
  19656. }
  19657. var scale = 1 / maxDimension;
  19658. this.scaling.scaleInPlace(scale);
  19659. return this;
  19660. };
  19661. /**
  19662. * Sets a mesh new object BoundingInfo.
  19663. * Returns the AbstractMesh.
  19664. */
  19665. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19666. this._boundingInfo = boundingInfo;
  19667. return this;
  19668. };
  19669. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19670. get: function () {
  19671. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19672. },
  19673. enumerable: true,
  19674. configurable: true
  19675. });
  19676. AbstractMesh.prototype._preActivate = function () {
  19677. };
  19678. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19679. };
  19680. AbstractMesh.prototype._activate = function (renderId) {
  19681. this._renderId = renderId;
  19682. };
  19683. /**
  19684. * Returns the latest update of the World matrix
  19685. * Returns a Matrix.
  19686. */
  19687. AbstractMesh.prototype.getWorldMatrix = function () {
  19688. if (this._masterMesh) {
  19689. return this._masterMesh.getWorldMatrix();
  19690. }
  19691. return _super.prototype.getWorldMatrix.call(this);
  19692. };
  19693. /**
  19694. * Returns the latest update of the World matrix determinant.
  19695. */
  19696. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19697. if (this._masterMesh) {
  19698. return this._masterMesh._getWorldMatrixDeterminant();
  19699. }
  19700. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19701. };
  19702. // ================================== Point of View Movement =================================
  19703. /**
  19704. * Perform relative position change from the point of view of behind the front of the mesh.
  19705. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19706. * Supports definition of mesh facing forward or backward.
  19707. * @param {number} amountRight
  19708. * @param {number} amountUp
  19709. * @param {number} amountForward
  19710. *
  19711. * Returns the AbstractMesh.
  19712. */
  19713. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19714. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19715. return this;
  19716. };
  19717. /**
  19718. * Calculate relative position change from the point of view of behind the front of the mesh.
  19719. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19720. * Supports definition of mesh facing forward or backward.
  19721. * @param {number} amountRight
  19722. * @param {number} amountUp
  19723. * @param {number} amountForward
  19724. *
  19725. * Returns a new Vector3.
  19726. */
  19727. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19728. var rotMatrix = new BABYLON.Matrix();
  19729. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19730. rotQuaternion.toRotationMatrix(rotMatrix);
  19731. var translationDelta = BABYLON.Vector3.Zero();
  19732. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19733. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19734. return translationDelta;
  19735. };
  19736. // ================================== Point of View Rotation =================================
  19737. /**
  19738. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19739. * Supports definition of mesh facing forward or backward.
  19740. * @param {number} flipBack
  19741. * @param {number} twirlClockwise
  19742. * @param {number} tiltRight
  19743. *
  19744. * Returns the AbstractMesh.
  19745. */
  19746. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19747. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19748. return this;
  19749. };
  19750. /**
  19751. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19752. * Supports definition of mesh facing forward or backward.
  19753. * @param {number} flipBack
  19754. * @param {number} twirlClockwise
  19755. * @param {number} tiltRight
  19756. *
  19757. * Returns a new Vector3.
  19758. */
  19759. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19760. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19761. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19762. };
  19763. /**
  19764. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19765. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19766. */
  19767. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19768. if (includeDescendants === void 0) { includeDescendants = true; }
  19769. this.computeWorldMatrix(true);
  19770. var min;
  19771. var max;
  19772. var boundingInfo = this.getBoundingInfo();
  19773. if (!this.subMeshes) {
  19774. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19775. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19776. }
  19777. else {
  19778. min = boundingInfo.boundingBox.minimumWorld;
  19779. max = boundingInfo.boundingBox.maximumWorld;
  19780. }
  19781. if (includeDescendants) {
  19782. var descendants = this.getDescendants(false);
  19783. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  19784. var descendant = descendants_1[_i];
  19785. var childMesh = descendant;
  19786. childMesh.computeWorldMatrix(true);
  19787. //make sure we have the needed params to get mix and max
  19788. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  19789. continue;
  19790. }
  19791. var childBoundingInfo = childMesh.getBoundingInfo();
  19792. var boundingBox = childBoundingInfo.boundingBox;
  19793. var minBox = boundingBox.minimumWorld;
  19794. var maxBox = boundingBox.maximumWorld;
  19795. BABYLON.Tools.CheckExtends(minBox, min, max);
  19796. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19797. }
  19798. }
  19799. return {
  19800. min: min,
  19801. max: max
  19802. };
  19803. };
  19804. /**
  19805. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  19806. * Returns the AbstractMesh.
  19807. */
  19808. AbstractMesh.prototype._updateBoundingInfo = function () {
  19809. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  19810. this._boundingInfo.update(this.worldMatrixFromCache);
  19811. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19812. return this;
  19813. };
  19814. /**
  19815. * Update a mesh's children BoundingInfo objects only.
  19816. * Returns the AbstractMesh.
  19817. */
  19818. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  19819. if (!this.subMeshes) {
  19820. return this;
  19821. }
  19822. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19823. var subMesh = this.subMeshes[subIndex];
  19824. if (!subMesh.IsGlobal) {
  19825. subMesh.updateBoundingInfo(matrix);
  19826. }
  19827. }
  19828. return this;
  19829. };
  19830. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  19831. // Bounding info
  19832. this._updateBoundingInfo();
  19833. };
  19834. /**
  19835. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  19836. * A mesh is in the frustum if its bounding box intersects the frustum.
  19837. * Boolean returned.
  19838. */
  19839. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  19840. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  19841. };
  19842. /**
  19843. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  19844. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  19845. * Boolean returned.
  19846. */
  19847. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19848. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  19849. ;
  19850. };
  19851. /**
  19852. * True if the mesh intersects another mesh or a SolidParticle object.
  19853. * 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)
  19854. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  19855. * Returns a boolean.
  19856. */
  19857. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  19858. if (precise === void 0) { precise = false; }
  19859. if (!this._boundingInfo || !mesh._boundingInfo) {
  19860. return false;
  19861. }
  19862. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  19863. return true;
  19864. }
  19865. if (includeDescendants) {
  19866. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  19867. var child = _a[_i];
  19868. if (child.intersectsMesh(mesh, precise, true)) {
  19869. return true;
  19870. }
  19871. }
  19872. }
  19873. return false;
  19874. };
  19875. /**
  19876. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  19877. * Returns a boolean.
  19878. */
  19879. AbstractMesh.prototype.intersectsPoint = function (point) {
  19880. if (!this._boundingInfo) {
  19881. return false;
  19882. }
  19883. return this._boundingInfo.intersectsPoint(point);
  19884. };
  19885. AbstractMesh.prototype.getPhysicsImpostor = function () {
  19886. return this.physicsImpostor;
  19887. };
  19888. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  19889. if (camera === void 0) { camera = null; }
  19890. if (!camera) {
  19891. camera = this.getScene().activeCamera;
  19892. }
  19893. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  19894. };
  19895. /**
  19896. * Returns the distance from the mesh to the active camera.
  19897. * Returns a float.
  19898. */
  19899. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  19900. if (camera === void 0) { camera = null; }
  19901. if (!camera) {
  19902. camera = this.getScene().activeCamera;
  19903. }
  19904. return this.absolutePosition.subtract(camera.position).length();
  19905. };
  19906. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  19907. if (!this.physicsImpostor) {
  19908. return this;
  19909. }
  19910. this.physicsImpostor.applyImpulse(force, contactPoint);
  19911. return this;
  19912. };
  19913. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  19914. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  19915. return this;
  19916. }
  19917. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  19918. mainPivot: pivot1,
  19919. connectedPivot: pivot2,
  19920. nativeParams: options
  19921. });
  19922. return this;
  19923. };
  19924. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  19925. // Collisions
  19926. /**
  19927. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  19928. * Default `false`.
  19929. */
  19930. get: function () {
  19931. return this._checkCollisions;
  19932. },
  19933. set: function (collisionEnabled) {
  19934. this._checkCollisions = collisionEnabled;
  19935. if (this.getScene().workerCollisions) {
  19936. this.getScene().collisionCoordinator.onMeshUpdated(this);
  19937. }
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(AbstractMesh.prototype, "collider", {
  19943. /**
  19944. * Gets Collider object used to compute collisions (not physics)
  19945. */
  19946. get: function () {
  19947. return this._collider;
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  19953. var globalPosition = this.getAbsolutePosition();
  19954. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  19955. if (!this._collider) {
  19956. this._collider = new BABYLON.Collider();
  19957. }
  19958. this._collider._radius = this.ellipsoid;
  19959. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  19960. return this;
  19961. };
  19962. // Submeshes octree
  19963. /**
  19964. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  19965. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  19966. * Returns an Octree of submeshes.
  19967. */
  19968. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  19969. if (maxCapacity === void 0) { maxCapacity = 64; }
  19970. if (maxDepth === void 0) { maxDepth = 2; }
  19971. if (!this._submeshesOctree) {
  19972. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  19973. }
  19974. this.computeWorldMatrix(true);
  19975. var boundingInfo = this.getBoundingInfo();
  19976. // Update octree
  19977. var bbox = boundingInfo.boundingBox;
  19978. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  19979. return this._submeshesOctree;
  19980. };
  19981. // Collisions
  19982. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  19983. this._generatePointsArray();
  19984. if (!this._positions) {
  19985. return this;
  19986. }
  19987. // Transformation
  19988. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  19989. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  19990. subMesh._lastColliderWorldVertices = [];
  19991. subMesh._trianglePlanes = [];
  19992. var start = subMesh.verticesStart;
  19993. var end = (subMesh.verticesStart + subMesh.verticesCount);
  19994. for (var i = start; i < end; i++) {
  19995. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  19996. }
  19997. }
  19998. // Collide
  19999. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20000. if (collider.collisionFound) {
  20001. collider.collidedMesh = this;
  20002. }
  20003. return this;
  20004. };
  20005. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20006. var subMeshes;
  20007. var len;
  20008. // Octrees
  20009. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20010. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20011. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20012. len = intersections.length;
  20013. subMeshes = intersections.data;
  20014. }
  20015. else {
  20016. subMeshes = this.subMeshes;
  20017. len = subMeshes.length;
  20018. }
  20019. for (var index = 0; index < len; index++) {
  20020. var subMesh = subMeshes[index];
  20021. // Bounding test
  20022. if (len > 1 && !subMesh._checkCollision(collider))
  20023. continue;
  20024. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20025. }
  20026. return this;
  20027. };
  20028. AbstractMesh.prototype._checkCollision = function (collider) {
  20029. // Bounding box test
  20030. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20031. return this;
  20032. // Transformation matrix
  20033. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20034. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20035. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20036. return this;
  20037. };
  20038. // Picking
  20039. AbstractMesh.prototype._generatePointsArray = function () {
  20040. return false;
  20041. };
  20042. /**
  20043. * Checks if the passed Ray intersects with the mesh.
  20044. * Returns an object PickingInfo.
  20045. */
  20046. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20047. var pickingInfo = new BABYLON.PickingInfo();
  20048. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20049. return pickingInfo;
  20050. }
  20051. if (!this._generatePointsArray()) {
  20052. return pickingInfo;
  20053. }
  20054. var intersectInfo = null;
  20055. // Octrees
  20056. var subMeshes;
  20057. var len;
  20058. if (this._submeshesOctree && this.useOctreeForPicking) {
  20059. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20060. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20061. len = intersections.length;
  20062. subMeshes = intersections.data;
  20063. }
  20064. else {
  20065. subMeshes = this.subMeshes;
  20066. len = subMeshes.length;
  20067. }
  20068. for (var index = 0; index < len; index++) {
  20069. var subMesh = subMeshes[index];
  20070. // Bounding test
  20071. if (len > 1 && !subMesh.canIntersects(ray))
  20072. continue;
  20073. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20074. if (currentIntersectInfo) {
  20075. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20076. intersectInfo = currentIntersectInfo;
  20077. intersectInfo.subMeshId = index;
  20078. if (fastCheck) {
  20079. break;
  20080. }
  20081. }
  20082. }
  20083. }
  20084. if (intersectInfo) {
  20085. // Get picked point
  20086. var world = this.getWorldMatrix();
  20087. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20088. var direction = ray.direction.clone();
  20089. direction = direction.scale(intersectInfo.distance);
  20090. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20091. var pickedPoint = worldOrigin.add(worldDirection);
  20092. // Return result
  20093. pickingInfo.hit = true;
  20094. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20095. pickingInfo.pickedPoint = pickedPoint;
  20096. pickingInfo.pickedMesh = this;
  20097. pickingInfo.bu = intersectInfo.bu || 0;
  20098. pickingInfo.bv = intersectInfo.bv || 0;
  20099. pickingInfo.faceId = intersectInfo.faceId;
  20100. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20101. return pickingInfo;
  20102. }
  20103. return pickingInfo;
  20104. };
  20105. /**
  20106. * Clones the mesh, used by the class Mesh.
  20107. * Just returns `null` for an AbstractMesh.
  20108. */
  20109. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20110. return null;
  20111. };
  20112. /**
  20113. * Disposes all the mesh submeshes.
  20114. * Returns the AbstractMesh.
  20115. */
  20116. AbstractMesh.prototype.releaseSubMeshes = function () {
  20117. if (this.subMeshes) {
  20118. while (this.subMeshes.length) {
  20119. this.subMeshes[0].dispose();
  20120. }
  20121. }
  20122. else {
  20123. this.subMeshes = new Array();
  20124. }
  20125. return this;
  20126. };
  20127. /**
  20128. * Releases resources associated with this abstract mesh.
  20129. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20130. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20131. */
  20132. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20133. var _this = this;
  20134. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20135. var index;
  20136. // Smart Array Retainers.
  20137. this.getScene().freeActiveMeshes();
  20138. this.getScene().freeRenderingGroups();
  20139. // Action manager
  20140. if (this.actionManager !== undefined && this.actionManager !== null) {
  20141. this.actionManager.dispose();
  20142. this.actionManager = null;
  20143. }
  20144. // Skeleton
  20145. this._skeleton = null;
  20146. // Physics
  20147. if (this.physicsImpostor) {
  20148. this.physicsImpostor.dispose();
  20149. }
  20150. // Intersections in progress
  20151. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20152. var other = this._intersectionsInProgress[index];
  20153. var pos = other._intersectionsInProgress.indexOf(this);
  20154. other._intersectionsInProgress.splice(pos, 1);
  20155. }
  20156. this._intersectionsInProgress = [];
  20157. // Lights
  20158. var lights = this.getScene().lights;
  20159. lights.forEach(function (light) {
  20160. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20161. if (meshIndex !== -1) {
  20162. light.includedOnlyMeshes.splice(meshIndex, 1);
  20163. }
  20164. meshIndex = light.excludedMeshes.indexOf(_this);
  20165. if (meshIndex !== -1) {
  20166. light.excludedMeshes.splice(meshIndex, 1);
  20167. }
  20168. // Shadow generators
  20169. var generator = light.getShadowGenerator();
  20170. if (generator) {
  20171. var shadowMap = generator.getShadowMap();
  20172. if (shadowMap && shadowMap.renderList) {
  20173. meshIndex = shadowMap.renderList.indexOf(_this);
  20174. if (meshIndex !== -1) {
  20175. shadowMap.renderList.splice(meshIndex, 1);
  20176. }
  20177. }
  20178. }
  20179. });
  20180. // Edges
  20181. if (this._edgesRenderer) {
  20182. this._edgesRenderer.dispose();
  20183. this._edgesRenderer = null;
  20184. }
  20185. // SubMeshes
  20186. if (this.getClassName() !== "InstancedMesh") {
  20187. this.releaseSubMeshes();
  20188. }
  20189. // Octree
  20190. var sceneOctree = this.getScene().selectionOctree;
  20191. if (sceneOctree !== undefined && sceneOctree !== null) {
  20192. var index = sceneOctree.dynamicContent.indexOf(this);
  20193. if (index !== -1) {
  20194. sceneOctree.dynamicContent.splice(index, 1);
  20195. }
  20196. }
  20197. // Query
  20198. var engine = this.getScene().getEngine();
  20199. if (this._occlusionQuery) {
  20200. this._isOcclusionQueryInProgress = false;
  20201. engine.deleteQuery(this._occlusionQuery);
  20202. this._occlusionQuery = null;
  20203. }
  20204. // Engine
  20205. engine.wipeCaches();
  20206. // Remove from scene
  20207. this.getScene().removeMesh(this);
  20208. if (disposeMaterialAndTextures) {
  20209. if (this.material) {
  20210. this.material.dispose(false, true);
  20211. }
  20212. }
  20213. if (!doNotRecurse) {
  20214. // Particles
  20215. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20216. if (this.getScene().particleSystems[index].emitter === this) {
  20217. this.getScene().particleSystems[index].dispose();
  20218. index--;
  20219. }
  20220. }
  20221. }
  20222. // facet data
  20223. if (this._facetDataEnabled) {
  20224. this.disableFacetData();
  20225. }
  20226. this.onAfterWorldMatrixUpdateObservable.clear();
  20227. this.onCollideObservable.clear();
  20228. this.onCollisionPositionChangeObservable.clear();
  20229. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20230. };
  20231. /**
  20232. * Adds the passed mesh as a child to the current mesh.
  20233. * Returns the AbstractMesh.
  20234. */
  20235. AbstractMesh.prototype.addChild = function (mesh) {
  20236. mesh.setParent(this);
  20237. return this;
  20238. };
  20239. /**
  20240. * Removes the passed mesh from the current mesh children list.
  20241. * Returns the AbstractMesh.
  20242. */
  20243. AbstractMesh.prototype.removeChild = function (mesh) {
  20244. mesh.setParent(null);
  20245. return this;
  20246. };
  20247. // Facet data
  20248. /**
  20249. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20250. * Returns the AbstractMesh.
  20251. */
  20252. AbstractMesh.prototype._initFacetData = function () {
  20253. if (!this._facetNormals) {
  20254. this._facetNormals = new Array();
  20255. }
  20256. if (!this._facetPositions) {
  20257. this._facetPositions = new Array();
  20258. }
  20259. if (!this._facetPartitioning) {
  20260. this._facetPartitioning = new Array();
  20261. }
  20262. this._facetNb = (this.getIndices().length / 3) | 0;
  20263. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20264. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20265. for (var f = 0; f < this._facetNb; f++) {
  20266. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20267. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20268. }
  20269. this._facetDataEnabled = true;
  20270. return this;
  20271. };
  20272. /**
  20273. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20274. * This method can be called within the render loop.
  20275. * 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.
  20276. * Returns the AbstractMesh.
  20277. */
  20278. AbstractMesh.prototype.updateFacetData = function () {
  20279. if (!this._facetDataEnabled) {
  20280. this._initFacetData();
  20281. }
  20282. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20283. var indices = this.getIndices();
  20284. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20285. var bInfo = this.getBoundingInfo();
  20286. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20287. // init arrays, matrix and sort function on first call
  20288. this._facetDepthSortEnabled = true;
  20289. if (indices instanceof Uint16Array) {
  20290. this._depthSortedIndices = new Uint16Array(indices);
  20291. }
  20292. else if (indices instanceof Uint32Array) {
  20293. this._depthSortedIndices = new Uint32Array(indices);
  20294. }
  20295. else {
  20296. var needs32bits = false;
  20297. for (var i = 0; i < indices.length; i++) {
  20298. if (indices[i] > 65535) {
  20299. needs32bits = true;
  20300. break;
  20301. }
  20302. }
  20303. if (needs32bits) {
  20304. this._depthSortedIndices = new Uint32Array(indices);
  20305. }
  20306. else {
  20307. this._depthSortedIndices = new Uint16Array(indices);
  20308. }
  20309. }
  20310. this._facetDepthSortFunction = function (f1, f2) {
  20311. return (f2.sqDistance - f1.sqDistance);
  20312. };
  20313. if (!this._facetDepthSortFrom) {
  20314. var camera = this.getScene().activeCamera;
  20315. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20316. }
  20317. this._depthSortedFacets = [];
  20318. for (var f = 0; f < this._facetNb; f++) {
  20319. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20320. this._depthSortedFacets.push(depthSortedFacet);
  20321. }
  20322. this._invertedMatrix = BABYLON.Matrix.Identity();
  20323. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20324. }
  20325. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20326. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20327. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20328. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20329. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20330. this._subDiv.max = this._partitioningSubdivisions;
  20331. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20332. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20333. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20334. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20335. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20336. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20337. // set the parameters for ComputeNormals()
  20338. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20339. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20340. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20341. this._facetParameters.bInfo = bInfo;
  20342. this._facetParameters.bbSize = this._bbSize;
  20343. this._facetParameters.subDiv = this._subDiv;
  20344. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20345. this._facetParameters.depthSort = this._facetDepthSort;
  20346. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20347. this.computeWorldMatrix(true);
  20348. this._worldMatrix.invertToRef(this._invertedMatrix);
  20349. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20350. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20351. }
  20352. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20353. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20354. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20355. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20356. var l = (this._depthSortedIndices.length / 3) | 0;
  20357. for (var f = 0; f < l; f++) {
  20358. var sind = this._depthSortedFacets[f].ind;
  20359. this._depthSortedIndices[f * 3] = indices[sind];
  20360. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20361. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20362. }
  20363. this.updateIndices(this._depthSortedIndices);
  20364. }
  20365. return this;
  20366. };
  20367. /**
  20368. * Returns the facetLocalNormals array.
  20369. * The normals are expressed in the mesh local space.
  20370. */
  20371. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20372. if (!this._facetNormals) {
  20373. this.updateFacetData();
  20374. }
  20375. return this._facetNormals;
  20376. };
  20377. /**
  20378. * Returns the facetLocalPositions array.
  20379. * The facet positions are expressed in the mesh local space.
  20380. */
  20381. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20382. if (!this._facetPositions) {
  20383. this.updateFacetData();
  20384. }
  20385. return this._facetPositions;
  20386. };
  20387. /**
  20388. * Returns the facetLocalPartioning array.
  20389. */
  20390. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20391. if (!this._facetPartitioning) {
  20392. this.updateFacetData();
  20393. }
  20394. return this._facetPartitioning;
  20395. };
  20396. /**
  20397. * Returns the i-th facet position in the world system.
  20398. * This method allocates a new Vector3 per call.
  20399. */
  20400. AbstractMesh.prototype.getFacetPosition = function (i) {
  20401. var pos = BABYLON.Vector3.Zero();
  20402. this.getFacetPositionToRef(i, pos);
  20403. return pos;
  20404. };
  20405. /**
  20406. * Sets the reference Vector3 with the i-th facet position in the world system.
  20407. * Returns the AbstractMesh.
  20408. */
  20409. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20410. var localPos = (this.getFacetLocalPositions())[i];
  20411. var world = this.getWorldMatrix();
  20412. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20413. return this;
  20414. };
  20415. /**
  20416. * Returns the i-th facet normal in the world system.
  20417. * This method allocates a new Vector3 per call.
  20418. */
  20419. AbstractMesh.prototype.getFacetNormal = function (i) {
  20420. var norm = BABYLON.Vector3.Zero();
  20421. this.getFacetNormalToRef(i, norm);
  20422. return norm;
  20423. };
  20424. /**
  20425. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20426. * Returns the AbstractMesh.
  20427. */
  20428. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20429. var localNorm = (this.getFacetLocalNormals())[i];
  20430. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20431. return this;
  20432. };
  20433. /**
  20434. * 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).
  20435. */
  20436. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20437. var bInfo = this.getBoundingInfo();
  20438. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20439. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20440. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20441. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20442. return null;
  20443. }
  20444. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20445. };
  20446. /**
  20447. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20448. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20449. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  20450. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20451. * 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.
  20452. */
  20453. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20454. if (checkFace === void 0) { checkFace = false; }
  20455. if (facing === void 0) { facing = true; }
  20456. var world = this.getWorldMatrix();
  20457. var invMat = BABYLON.Tmp.Matrix[5];
  20458. world.invertToRef(invMat);
  20459. var invVect = BABYLON.Tmp.Vector3[8];
  20460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20461. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20462. if (projected) {
  20463. // tranform the local computed projected vector to world coordinates
  20464. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20465. }
  20466. return closest;
  20467. };
  20468. /**
  20469. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20470. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20471. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  20472. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20473. * 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.
  20474. */
  20475. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20476. if (checkFace === void 0) { checkFace = false; }
  20477. if (facing === void 0) { facing = true; }
  20478. var closest = null;
  20479. var tmpx = 0.0;
  20480. var tmpy = 0.0;
  20481. var tmpz = 0.0;
  20482. var d = 0.0; // tmp dot facet normal * facet position
  20483. var t0 = 0.0;
  20484. var projx = 0.0;
  20485. var projy = 0.0;
  20486. var projz = 0.0;
  20487. // Get all the facets in the same partitioning block than (x, y, z)
  20488. var facetPositions = this.getFacetLocalPositions();
  20489. var facetNormals = this.getFacetLocalNormals();
  20490. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20491. if (!facetsInBlock) {
  20492. return null;
  20493. }
  20494. // Get the closest facet to (x, y, z)
  20495. var shortest = Number.MAX_VALUE; // init distance vars
  20496. var tmpDistance = shortest;
  20497. var fib; // current facet in the block
  20498. var norm; // current facet normal
  20499. var p0; // current facet barycenter position
  20500. // loop on all the facets in the current partitioning block
  20501. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20502. fib = facetsInBlock[idx];
  20503. norm = facetNormals[fib];
  20504. p0 = facetPositions[fib];
  20505. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20506. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20507. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20508. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20509. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20510. projx = x + norm.x * t0;
  20511. projy = y + norm.y * t0;
  20512. projz = z + norm.z * t0;
  20513. tmpx = projx - x;
  20514. tmpy = projy - y;
  20515. tmpz = projz - z;
  20516. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20517. if (tmpDistance < shortest) {
  20518. shortest = tmpDistance;
  20519. closest = fib;
  20520. if (projected) {
  20521. projected.x = projx;
  20522. projected.y = projy;
  20523. projected.z = projz;
  20524. }
  20525. }
  20526. }
  20527. }
  20528. return closest;
  20529. };
  20530. /**
  20531. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20532. */
  20533. AbstractMesh.prototype.getFacetDataParameters = function () {
  20534. return this._facetParameters;
  20535. };
  20536. /**
  20537. * Disables the feature FacetData and frees the related memory.
  20538. * Returns the AbstractMesh.
  20539. */
  20540. AbstractMesh.prototype.disableFacetData = function () {
  20541. if (this._facetDataEnabled) {
  20542. this._facetDataEnabled = false;
  20543. this._facetPositions = new Array();
  20544. this._facetNormals = new Array();
  20545. this._facetPartitioning = new Array();
  20546. this._facetParameters = null;
  20547. this._depthSortedIndices = new Uint32Array(0);
  20548. }
  20549. return this;
  20550. };
  20551. /**
  20552. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20553. * Returns the mesh.
  20554. */
  20555. AbstractMesh.prototype.updateIndices = function (indices) {
  20556. return this;
  20557. };
  20558. /**
  20559. * The mesh Geometry. Actually used by the Mesh object.
  20560. * Returns a blank geometry object.
  20561. */
  20562. /**
  20563. * Creates new normals data for the mesh.
  20564. * @param updatable.
  20565. */
  20566. AbstractMesh.prototype.createNormals = function (updatable) {
  20567. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20568. var indices = this.getIndices();
  20569. var normals;
  20570. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20571. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20572. }
  20573. else {
  20574. normals = [];
  20575. }
  20576. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20577. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20578. };
  20579. /**
  20580. * Align the mesh with a normal.
  20581. * Returns the mesh.
  20582. */
  20583. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20584. if (!upDirection) {
  20585. upDirection = BABYLON.Axis.Y;
  20586. }
  20587. var axisX = BABYLON.Tmp.Vector3[0];
  20588. var axisZ = BABYLON.Tmp.Vector3[1];
  20589. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20590. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20591. if (this.rotationQuaternion) {
  20592. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20593. }
  20594. else {
  20595. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20596. }
  20597. return this;
  20598. };
  20599. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20600. var engine = this.getEngine();
  20601. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20602. this._isOccluded = false;
  20603. return;
  20604. }
  20605. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20606. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20607. if (isOcclusionQueryAvailable) {
  20608. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20609. this._isOcclusionQueryInProgress = false;
  20610. this._occlusionInternalRetryCounter = 0;
  20611. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20612. }
  20613. else {
  20614. this._occlusionInternalRetryCounter++;
  20615. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20616. this._isOcclusionQueryInProgress = false;
  20617. this._occlusionInternalRetryCounter = 0;
  20618. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20619. // if strict continue the last state of the object.
  20620. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20621. }
  20622. else {
  20623. return;
  20624. }
  20625. }
  20626. }
  20627. var scene = this.getScene();
  20628. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20629. if (!this._occlusionQuery) {
  20630. this._occlusionQuery = engine.createQuery();
  20631. }
  20632. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20633. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20634. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20635. this._isOcclusionQueryInProgress = true;
  20636. };
  20637. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20638. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20639. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20640. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20641. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20642. return AbstractMesh;
  20643. }(BABYLON.TransformNode));
  20644. BABYLON.AbstractMesh = AbstractMesh;
  20645. })(BABYLON || (BABYLON = {}));
  20646. //# sourceMappingURL=babylon.abstractMesh.js.map
  20647. "use strict";
  20648. var BABYLON;
  20649. (function (BABYLON) {
  20650. /**
  20651. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20652. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20653. * 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.
  20654. */
  20655. var Light = /** @class */ (function (_super) {
  20656. __extends(Light, _super);
  20657. /**
  20658. * Creates a Light object in the scene.
  20659. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20660. * @param name The firendly name of the light
  20661. * @param scene The scene the light belongs too
  20662. */
  20663. function Light(name, scene) {
  20664. var _this = _super.call(this, name, scene) || this;
  20665. /**
  20666. * Diffuse gives the basic color to an object.
  20667. */
  20668. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20669. /**
  20670. * Specular produces a highlight color on an object.
  20671. * Note: This is note affecting PBR materials.
  20672. */
  20673. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20674. /**
  20675. * Strength of the light.
  20676. * Note: By default it is define in the framework own unit.
  20677. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20678. */
  20679. _this.intensity = 1.0;
  20680. /**
  20681. * Defines how far from the source the light is impacting in scene units.
  20682. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20683. */
  20684. _this.range = Number.MAX_VALUE;
  20685. /**
  20686. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20687. * of light.
  20688. */
  20689. _this._photometricScale = 1.0;
  20690. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20691. _this._radius = 0.00001;
  20692. /**
  20693. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20694. * exceeding the number allowed of the materials.
  20695. */
  20696. _this.renderPriority = 0;
  20697. /**
  20698. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20699. * the current shadow generator.
  20700. */
  20701. _this.shadowEnabled = true;
  20702. _this._excludeWithLayerMask = 0;
  20703. _this._includeOnlyWithLayerMask = 0;
  20704. _this._lightmapMode = 0;
  20705. /**
  20706. * @ignore Internal use only.
  20707. */
  20708. _this._excludedMeshesIds = new Array();
  20709. /**
  20710. * @ignore Internal use only.
  20711. */
  20712. _this._includedOnlyMeshesIds = new Array();
  20713. _this.getScene().addLight(_this);
  20714. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20715. _this._buildUniformLayout();
  20716. _this.includedOnlyMeshes = new Array();
  20717. _this.excludedMeshes = new Array();
  20718. _this._resyncMeshes();
  20719. return _this;
  20720. }
  20721. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20722. /**
  20723. * If every light affecting the material is in this lightmapMode,
  20724. * material.lightmapTexture adds or multiplies
  20725. * (depends on material.useLightmapAsShadowmap)
  20726. * after every other light calculations.
  20727. */
  20728. get: function () {
  20729. return Light._LIGHTMAP_DEFAULT;
  20730. },
  20731. enumerable: true,
  20732. configurable: true
  20733. });
  20734. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20735. /**
  20736. * material.lightmapTexture as only diffuse lighting from this light
  20737. * adds only specular lighting from this light
  20738. * adds dynamic shadows
  20739. */
  20740. get: function () {
  20741. return Light._LIGHTMAP_SPECULAR;
  20742. },
  20743. enumerable: true,
  20744. configurable: true
  20745. });
  20746. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20747. /**
  20748. * material.lightmapTexture as only lighting
  20749. * no light calculation from this light
  20750. * only adds dynamic shadows from this light
  20751. */
  20752. get: function () {
  20753. return Light._LIGHTMAP_SHADOWSONLY;
  20754. },
  20755. enumerable: true,
  20756. configurable: true
  20757. });
  20758. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20759. /**
  20760. * Each light type uses the default quantity according to its type:
  20761. * point/spot lights use luminous intensity
  20762. * directional lights use illuminance
  20763. */
  20764. get: function () {
  20765. return Light._INTENSITYMODE_AUTOMATIC;
  20766. },
  20767. enumerable: true,
  20768. configurable: true
  20769. });
  20770. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20771. /**
  20772. * lumen (lm)
  20773. */
  20774. get: function () {
  20775. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20776. },
  20777. enumerable: true,
  20778. configurable: true
  20779. });
  20780. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  20781. /**
  20782. * candela (lm/sr)
  20783. */
  20784. get: function () {
  20785. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  20786. },
  20787. enumerable: true,
  20788. configurable: true
  20789. });
  20790. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  20791. /**
  20792. * lux (lm/m^2)
  20793. */
  20794. get: function () {
  20795. return Light._INTENSITYMODE_ILLUMINANCE;
  20796. },
  20797. enumerable: true,
  20798. configurable: true
  20799. });
  20800. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  20801. /**
  20802. * nit (cd/m^2)
  20803. */
  20804. get: function () {
  20805. return Light._INTENSITYMODE_LUMINANCE;
  20806. },
  20807. enumerable: true,
  20808. configurable: true
  20809. });
  20810. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  20811. /**
  20812. * Light type const id of the point light.
  20813. */
  20814. get: function () {
  20815. return Light._LIGHTTYPEID_POINTLIGHT;
  20816. },
  20817. enumerable: true,
  20818. configurable: true
  20819. });
  20820. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  20821. /**
  20822. * Light type const id of the directional light.
  20823. */
  20824. get: function () {
  20825. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  20826. },
  20827. enumerable: true,
  20828. configurable: true
  20829. });
  20830. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  20831. /**
  20832. * Light type const id of the spot light.
  20833. */
  20834. get: function () {
  20835. return Light._LIGHTTYPEID_SPOTLIGHT;
  20836. },
  20837. enumerable: true,
  20838. configurable: true
  20839. });
  20840. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  20841. /**
  20842. * Light type const id of the hemispheric light.
  20843. */
  20844. get: function () {
  20845. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  20846. },
  20847. enumerable: true,
  20848. configurable: true
  20849. });
  20850. Object.defineProperty(Light.prototype, "intensityMode", {
  20851. /**
  20852. * Gets the photometric scale used to interpret the intensity.
  20853. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20854. */
  20855. get: function () {
  20856. return this._intensityMode;
  20857. },
  20858. /**
  20859. * Sets the photometric scale used to interpret the intensity.
  20860. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20861. */
  20862. set: function (value) {
  20863. this._intensityMode = value;
  20864. this._computePhotometricScale();
  20865. },
  20866. enumerable: true,
  20867. configurable: true
  20868. });
  20869. ;
  20870. ;
  20871. Object.defineProperty(Light.prototype, "radius", {
  20872. /**
  20873. * Gets the light radius used by PBR Materials to simulate soft area lights.
  20874. */
  20875. get: function () {
  20876. return this._radius;
  20877. },
  20878. /**
  20879. * sets the light radius used by PBR Materials to simulate soft area lights.
  20880. */
  20881. set: function (value) {
  20882. this._radius = value;
  20883. this._computePhotometricScale();
  20884. },
  20885. enumerable: true,
  20886. configurable: true
  20887. });
  20888. ;
  20889. ;
  20890. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  20891. /**
  20892. * Gets the only meshes impacted by this light.
  20893. */
  20894. get: function () {
  20895. return this._includedOnlyMeshes;
  20896. },
  20897. /**
  20898. * Sets the only meshes impacted by this light.
  20899. */
  20900. set: function (value) {
  20901. this._includedOnlyMeshes = value;
  20902. this._hookArrayForIncludedOnly(value);
  20903. },
  20904. enumerable: true,
  20905. configurable: true
  20906. });
  20907. Object.defineProperty(Light.prototype, "excludedMeshes", {
  20908. /**
  20909. * Gets the meshes not impacted by this light.
  20910. */
  20911. get: function () {
  20912. return this._excludedMeshes;
  20913. },
  20914. /**
  20915. * Sets the meshes not impacted by this light.
  20916. */
  20917. set: function (value) {
  20918. this._excludedMeshes = value;
  20919. this._hookArrayForExcluded(value);
  20920. },
  20921. enumerable: true,
  20922. configurable: true
  20923. });
  20924. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  20925. /**
  20926. * Gets the layer id use to find what meshes are not impacted by the light.
  20927. * Inactive if 0
  20928. */
  20929. get: function () {
  20930. return this._excludeWithLayerMask;
  20931. },
  20932. /**
  20933. * Sets the layer id use to find what meshes are not impacted by the light.
  20934. * Inactive if 0
  20935. */
  20936. set: function (value) {
  20937. this._excludeWithLayerMask = value;
  20938. this._resyncMeshes();
  20939. },
  20940. enumerable: true,
  20941. configurable: true
  20942. });
  20943. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  20944. /**
  20945. * Gets the layer id use to find what meshes are impacted by the light.
  20946. * Inactive if 0
  20947. */
  20948. get: function () {
  20949. return this._includeOnlyWithLayerMask;
  20950. },
  20951. /**
  20952. * Sets the layer id use to find what meshes are impacted by the light.
  20953. * Inactive if 0
  20954. */
  20955. set: function (value) {
  20956. this._includeOnlyWithLayerMask = value;
  20957. this._resyncMeshes();
  20958. },
  20959. enumerable: true,
  20960. configurable: true
  20961. });
  20962. Object.defineProperty(Light.prototype, "lightmapMode", {
  20963. /**
  20964. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20965. */
  20966. get: function () {
  20967. return this._lightmapMode;
  20968. },
  20969. /**
  20970. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20971. */
  20972. set: function (value) {
  20973. if (this._lightmapMode === value) {
  20974. return;
  20975. }
  20976. this._lightmapMode = value;
  20977. this._markMeshesAsLightDirty();
  20978. },
  20979. enumerable: true,
  20980. configurable: true
  20981. });
  20982. /**
  20983. * Returns the string "Light".
  20984. * @returns the class name
  20985. */
  20986. Light.prototype.getClassName = function () {
  20987. return "Light";
  20988. };
  20989. /**
  20990. * Converts the light information to a readable string for debug purpose.
  20991. * @param fullDetails Supports for multiple levels of logging within scene loading
  20992. * @returns the human readable light info
  20993. */
  20994. Light.prototype.toString = function (fullDetails) {
  20995. var ret = "Name: " + this.name;
  20996. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  20997. if (this.animations) {
  20998. for (var i = 0; i < this.animations.length; i++) {
  20999. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21000. }
  21001. }
  21002. if (fullDetails) {
  21003. }
  21004. return ret;
  21005. };
  21006. /**
  21007. * Set the enabled state of this node.
  21008. * @param value - the new enabled state
  21009. */
  21010. Light.prototype.setEnabled = function (value) {
  21011. _super.prototype.setEnabled.call(this, value);
  21012. this._resyncMeshes();
  21013. };
  21014. /**
  21015. * Returns the Light associated shadow generator if any.
  21016. * @return the associated shadow generator.
  21017. */
  21018. Light.prototype.getShadowGenerator = function () {
  21019. return this._shadowGenerator;
  21020. };
  21021. /**
  21022. * Returns a Vector3, the absolute light position in the World.
  21023. * @returns the world space position of the light
  21024. */
  21025. Light.prototype.getAbsolutePosition = function () {
  21026. return BABYLON.Vector3.Zero();
  21027. };
  21028. /**
  21029. * Specifies if the light will affect the passed mesh.
  21030. * @param mesh The mesh to test against the light
  21031. * @return true the mesh is affected otherwise, false.
  21032. */
  21033. Light.prototype.canAffectMesh = function (mesh) {
  21034. if (!mesh) {
  21035. return true;
  21036. }
  21037. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21038. return false;
  21039. }
  21040. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21041. return false;
  21042. }
  21043. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21044. return false;
  21045. }
  21046. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21047. return false;
  21048. }
  21049. return true;
  21050. };
  21051. /**
  21052. * Computes and Returns the light World matrix.
  21053. * @returns the world matrix
  21054. */
  21055. Light.prototype.getWorldMatrix = function () {
  21056. this._currentRenderId = this.getScene().getRenderId();
  21057. this._childRenderId = this._currentRenderId;
  21058. var worldMatrix = this._getWorldMatrix();
  21059. if (this.parent && this.parent.getWorldMatrix) {
  21060. if (!this._parentedWorldMatrix) {
  21061. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21062. }
  21063. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21064. this._markSyncedWithParent();
  21065. return this._parentedWorldMatrix;
  21066. }
  21067. return worldMatrix;
  21068. };
  21069. /**
  21070. * Sort function to order lights for rendering.
  21071. * @param a First Light object to compare to second.
  21072. * @param b Second Light object to compare first.
  21073. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21074. */
  21075. Light.CompareLightsPriority = function (a, b) {
  21076. //shadow-casting lights have priority over non-shadow-casting lights
  21077. //the renderPrioirty is a secondary sort criterion
  21078. if (a.shadowEnabled !== b.shadowEnabled) {
  21079. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21080. }
  21081. return b.renderPriority - a.renderPriority;
  21082. };
  21083. /**
  21084. * Releases resources associated with this node.
  21085. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21086. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21087. */
  21088. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21089. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21090. if (this._shadowGenerator) {
  21091. this._shadowGenerator.dispose();
  21092. this._shadowGenerator = null;
  21093. }
  21094. // Animations
  21095. this.getScene().stopAnimation(this);
  21096. // Remove from meshes
  21097. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21098. var mesh = _a[_i];
  21099. mesh._removeLightSource(this);
  21100. }
  21101. this._uniformBuffer.dispose();
  21102. // Remove from scene
  21103. this.getScene().removeLight(this);
  21104. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21105. };
  21106. /**
  21107. * Returns the light type ID (integer).
  21108. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21109. */
  21110. Light.prototype.getTypeID = function () {
  21111. return 0;
  21112. };
  21113. /**
  21114. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21115. * @returns the scaled intensity in intensity mode unit
  21116. */
  21117. Light.prototype.getScaledIntensity = function () {
  21118. return this._photometricScale * this.intensity;
  21119. };
  21120. /**
  21121. * Returns a new Light object, named "name", from the current one.
  21122. * @param name The name of the cloned light
  21123. * @returns the new created light
  21124. */
  21125. Light.prototype.clone = function (name) {
  21126. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21127. if (!constructor) {
  21128. return null;
  21129. }
  21130. return BABYLON.SerializationHelper.Clone(constructor, this);
  21131. };
  21132. /**
  21133. * Serializes the current light into a Serialization object.
  21134. * @returns the serialized object.
  21135. */
  21136. Light.prototype.serialize = function () {
  21137. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21138. // Type
  21139. serializationObject.type = this.getTypeID();
  21140. // Parent
  21141. if (this.parent) {
  21142. serializationObject.parentId = this.parent.id;
  21143. }
  21144. // Inclusion / exclusions
  21145. if (this.excludedMeshes.length > 0) {
  21146. serializationObject.excludedMeshesIds = [];
  21147. this.excludedMeshes.forEach(function (mesh) {
  21148. serializationObject.excludedMeshesIds.push(mesh.id);
  21149. });
  21150. }
  21151. if (this.includedOnlyMeshes.length > 0) {
  21152. serializationObject.includedOnlyMeshesIds = [];
  21153. this.includedOnlyMeshes.forEach(function (mesh) {
  21154. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21155. });
  21156. }
  21157. // Animations
  21158. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21159. serializationObject.ranges = this.serializeAnimationRanges();
  21160. return serializationObject;
  21161. };
  21162. /**
  21163. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21164. * This new light is named "name" and added to the passed scene.
  21165. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21166. * @param name The friendly name of the light
  21167. * @param scene The scene the new light will belong to
  21168. * @returns the constructor function
  21169. */
  21170. Light.GetConstructorFromName = function (type, name, scene) {
  21171. switch (type) {
  21172. case 0:
  21173. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21174. case 1:
  21175. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21176. case 2:
  21177. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21178. case 3:
  21179. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21180. }
  21181. return null;
  21182. };
  21183. /**
  21184. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21185. * @param parsedLight The JSON representation of the light
  21186. * @param scene The scene to create the parsed light in
  21187. * @returns the created light after parsing
  21188. */
  21189. Light.Parse = function (parsedLight, scene) {
  21190. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21191. if (!constructor) {
  21192. return null;
  21193. }
  21194. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21195. // Inclusion / exclusions
  21196. if (parsedLight.excludedMeshesIds) {
  21197. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21198. }
  21199. if (parsedLight.includedOnlyMeshesIds) {
  21200. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21201. }
  21202. // Parent
  21203. if (parsedLight.parentId) {
  21204. light._waitingParentId = parsedLight.parentId;
  21205. }
  21206. // Animations
  21207. if (parsedLight.animations) {
  21208. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21209. var parsedAnimation = parsedLight.animations[animationIndex];
  21210. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21211. }
  21212. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21213. }
  21214. if (parsedLight.autoAnimate) {
  21215. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21216. }
  21217. return light;
  21218. };
  21219. Light.prototype._hookArrayForExcluded = function (array) {
  21220. var _this = this;
  21221. var oldPush = array.push;
  21222. array.push = function () {
  21223. var items = [];
  21224. for (var _i = 0; _i < arguments.length; _i++) {
  21225. items[_i] = arguments[_i];
  21226. }
  21227. var result = oldPush.apply(array, items);
  21228. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21229. var item = items_1[_a];
  21230. item._resyncLighSource(_this);
  21231. }
  21232. return result;
  21233. };
  21234. var oldSplice = array.splice;
  21235. array.splice = function (index, deleteCount) {
  21236. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21237. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21238. var item = deleted_1[_i];
  21239. item._resyncLighSource(_this);
  21240. }
  21241. return deleted;
  21242. };
  21243. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21244. var item = array_1[_i];
  21245. item._resyncLighSource(this);
  21246. }
  21247. };
  21248. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21249. var _this = this;
  21250. var oldPush = array.push;
  21251. array.push = function () {
  21252. var items = [];
  21253. for (var _i = 0; _i < arguments.length; _i++) {
  21254. items[_i] = arguments[_i];
  21255. }
  21256. var result = oldPush.apply(array, items);
  21257. _this._resyncMeshes();
  21258. return result;
  21259. };
  21260. var oldSplice = array.splice;
  21261. array.splice = function (index, deleteCount) {
  21262. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21263. _this._resyncMeshes();
  21264. return deleted;
  21265. };
  21266. this._resyncMeshes();
  21267. };
  21268. Light.prototype._resyncMeshes = function () {
  21269. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21270. var mesh = _a[_i];
  21271. mesh._resyncLighSource(this);
  21272. }
  21273. };
  21274. /**
  21275. * Forces the meshes to update their light related information in their rendering used effects
  21276. * @ignore Internal Use Only
  21277. */
  21278. Light.prototype._markMeshesAsLightDirty = function () {
  21279. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21280. var mesh = _a[_i];
  21281. if (mesh._lightSources.indexOf(this) !== -1) {
  21282. mesh._markSubMeshesAsLightDirty();
  21283. }
  21284. }
  21285. };
  21286. /**
  21287. * Recomputes the cached photometric scale if needed.
  21288. */
  21289. Light.prototype._computePhotometricScale = function () {
  21290. this._photometricScale = this._getPhotometricScale();
  21291. this.getScene().resetCachedMaterial();
  21292. };
  21293. /**
  21294. * Returns the Photometric Scale according to the light type and intensity mode.
  21295. */
  21296. Light.prototype._getPhotometricScale = function () {
  21297. var photometricScale = 0.0;
  21298. var lightTypeID = this.getTypeID();
  21299. //get photometric mode
  21300. var photometricMode = this.intensityMode;
  21301. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21302. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21303. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21304. }
  21305. else {
  21306. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21307. }
  21308. }
  21309. //compute photometric scale
  21310. switch (lightTypeID) {
  21311. case Light.LIGHTTYPEID_POINTLIGHT:
  21312. case Light.LIGHTTYPEID_SPOTLIGHT:
  21313. switch (photometricMode) {
  21314. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21315. photometricScale = 1.0 / (4.0 * Math.PI);
  21316. break;
  21317. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21318. photometricScale = 1.0;
  21319. break;
  21320. case Light.INTENSITYMODE_LUMINANCE:
  21321. photometricScale = this.radius * this.radius;
  21322. break;
  21323. }
  21324. break;
  21325. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21326. switch (photometricMode) {
  21327. case Light.INTENSITYMODE_ILLUMINANCE:
  21328. photometricScale = 1.0;
  21329. break;
  21330. case Light.INTENSITYMODE_LUMINANCE:
  21331. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21332. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21333. var apexAngleRadians = this.radius;
  21334. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21335. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21336. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21337. photometricScale = solidAngle;
  21338. break;
  21339. }
  21340. break;
  21341. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21342. // No fall off in hemisperic light.
  21343. photometricScale = 1.0;
  21344. break;
  21345. }
  21346. return photometricScale;
  21347. };
  21348. /**
  21349. * Reorder the light in the scene according to their defined priority.
  21350. * @ignore Internal Use Only
  21351. */
  21352. Light.prototype._reorderLightsInScene = function () {
  21353. var scene = this.getScene();
  21354. if (this._renderPriority != 0) {
  21355. scene.requireLightSorting = true;
  21356. }
  21357. this.getScene().sortLightsByPriority();
  21358. };
  21359. //lightmapMode Consts
  21360. Light._LIGHTMAP_DEFAULT = 0;
  21361. Light._LIGHTMAP_SPECULAR = 1;
  21362. Light._LIGHTMAP_SHADOWSONLY = 2;
  21363. // Intensity Mode Consts
  21364. Light._INTENSITYMODE_AUTOMATIC = 0;
  21365. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21366. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21367. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21368. Light._INTENSITYMODE_LUMINANCE = 4;
  21369. // Light types ids const.
  21370. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21371. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21372. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21373. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21374. __decorate([
  21375. BABYLON.serializeAsColor3()
  21376. ], Light.prototype, "diffuse", void 0);
  21377. __decorate([
  21378. BABYLON.serializeAsColor3()
  21379. ], Light.prototype, "specular", void 0);
  21380. __decorate([
  21381. BABYLON.serialize()
  21382. ], Light.prototype, "intensity", void 0);
  21383. __decorate([
  21384. BABYLON.serialize()
  21385. ], Light.prototype, "range", void 0);
  21386. __decorate([
  21387. BABYLON.serialize()
  21388. ], Light.prototype, "intensityMode", null);
  21389. __decorate([
  21390. BABYLON.serialize()
  21391. ], Light.prototype, "radius", null);
  21392. __decorate([
  21393. BABYLON.serialize()
  21394. ], Light.prototype, "_renderPriority", void 0);
  21395. __decorate([
  21396. BABYLON.expandToProperty("_reorderLightsInScene")
  21397. ], Light.prototype, "renderPriority", void 0);
  21398. __decorate([
  21399. BABYLON.serialize()
  21400. ], Light.prototype, "shadowEnabled", void 0);
  21401. __decorate([
  21402. BABYLON.serialize("excludeWithLayerMask")
  21403. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21404. __decorate([
  21405. BABYLON.serialize("includeOnlyWithLayerMask")
  21406. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21407. __decorate([
  21408. BABYLON.serialize("lightmapMode")
  21409. ], Light.prototype, "_lightmapMode", void 0);
  21410. return Light;
  21411. }(BABYLON.Node));
  21412. BABYLON.Light = Light;
  21413. })(BABYLON || (BABYLON = {}));
  21414. //# sourceMappingURL=babylon.light.js.map
  21415. "use strict";
  21416. var BABYLON;
  21417. (function (BABYLON) {
  21418. var Camera = /** @class */ (function (_super) {
  21419. __extends(Camera, _super);
  21420. function Camera(name, position, scene) {
  21421. var _this = _super.call(this, name, scene) || this;
  21422. /**
  21423. * The vector the camera should consider as up.
  21424. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21425. */
  21426. _this.upVector = BABYLON.Vector3.Up();
  21427. _this.orthoLeft = null;
  21428. _this.orthoRight = null;
  21429. _this.orthoBottom = null;
  21430. _this.orthoTop = null;
  21431. /**
  21432. * FOV is set in Radians. (default is 0.8)
  21433. */
  21434. _this.fov = 0.8;
  21435. _this.minZ = 1;
  21436. _this.maxZ = 10000.0;
  21437. _this.inertia = 0.9;
  21438. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21439. _this.isIntermediate = false;
  21440. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21441. /**
  21442. * Restricts the camera to viewing objects with the same layerMask.
  21443. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21444. */
  21445. _this.layerMask = 0x0FFFFFFF;
  21446. /**
  21447. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21448. */
  21449. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21450. // Camera rig members
  21451. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21452. _this._rigCameras = new Array();
  21453. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21454. _this._skipRendering = false;
  21455. _this.customRenderTargets = new Array();
  21456. // Observables
  21457. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21458. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21459. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21460. _this.onRestoreStateObservable = new BABYLON.Observable();
  21461. // Cache
  21462. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21463. _this._projectionMatrix = new BABYLON.Matrix();
  21464. _this._doNotComputeProjectionMatrix = false;
  21465. _this._postProcesses = new Array();
  21466. _this._transformMatrix = BABYLON.Matrix.Zero();
  21467. _this._activeMeshes = new BABYLON.SmartArray(256);
  21468. _this._globalPosition = BABYLON.Vector3.Zero();
  21469. _this._refreshFrustumPlanes = true;
  21470. _this.getScene().addCamera(_this);
  21471. if (!_this.getScene().activeCamera) {
  21472. _this.getScene().activeCamera = _this;
  21473. }
  21474. _this.position = position;
  21475. return _this;
  21476. }
  21477. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21478. get: function () {
  21479. return Camera._PERSPECTIVE_CAMERA;
  21480. },
  21481. enumerable: true,
  21482. configurable: true
  21483. });
  21484. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21485. get: function () {
  21486. return Camera._ORTHOGRAPHIC_CAMERA;
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21492. /**
  21493. * This is the default FOV mode for perspective cameras.
  21494. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21495. *
  21496. */
  21497. get: function () {
  21498. return Camera._FOVMODE_VERTICAL_FIXED;
  21499. },
  21500. enumerable: true,
  21501. configurable: true
  21502. });
  21503. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21504. /**
  21505. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21506. *
  21507. */
  21508. get: function () {
  21509. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21510. },
  21511. enumerable: true,
  21512. configurable: true
  21513. });
  21514. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21515. get: function () {
  21516. return Camera._RIG_MODE_NONE;
  21517. },
  21518. enumerable: true,
  21519. configurable: true
  21520. });
  21521. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21522. get: function () {
  21523. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21524. },
  21525. enumerable: true,
  21526. configurable: true
  21527. });
  21528. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21529. get: function () {
  21530. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21536. get: function () {
  21537. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21543. get: function () {
  21544. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21545. },
  21546. enumerable: true,
  21547. configurable: true
  21548. });
  21549. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21550. get: function () {
  21551. return Camera._RIG_MODE_VR;
  21552. },
  21553. enumerable: true,
  21554. configurable: true
  21555. });
  21556. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21557. get: function () {
  21558. return Camera._RIG_MODE_WEBVR;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. /**
  21564. * Store current camera state (fov, position, etc..)
  21565. */
  21566. Camera.prototype.storeState = function () {
  21567. this._stateStored = true;
  21568. this._storedFov = this.fov;
  21569. return this;
  21570. };
  21571. /**
  21572. * Restores the camera state values if it has been stored. You must call storeState() first
  21573. */
  21574. Camera.prototype._restoreStateValues = function () {
  21575. if (!this._stateStored) {
  21576. return false;
  21577. }
  21578. this.fov = this._storedFov;
  21579. return true;
  21580. };
  21581. /**
  21582. * Restored camera state. You must call storeState() first
  21583. */
  21584. Camera.prototype.restoreState = function () {
  21585. if (this._restoreStateValues()) {
  21586. this.onRestoreStateObservable.notifyObservers(this);
  21587. return true;
  21588. }
  21589. return false;
  21590. };
  21591. Camera.prototype.getClassName = function () {
  21592. return "Camera";
  21593. };
  21594. /**
  21595. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21596. */
  21597. Camera.prototype.toString = function (fullDetails) {
  21598. var ret = "Name: " + this.name;
  21599. ret += ", type: " + this.getClassName();
  21600. if (this.animations) {
  21601. for (var i = 0; i < this.animations.length; i++) {
  21602. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21603. }
  21604. }
  21605. if (fullDetails) {
  21606. }
  21607. return ret;
  21608. };
  21609. Object.defineProperty(Camera.prototype, "globalPosition", {
  21610. get: function () {
  21611. return this._globalPosition;
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Camera.prototype.getActiveMeshes = function () {
  21617. return this._activeMeshes;
  21618. };
  21619. Camera.prototype.isActiveMesh = function (mesh) {
  21620. return (this._activeMeshes.indexOf(mesh) !== -1);
  21621. };
  21622. /**
  21623. * Is this camera ready to be used/rendered
  21624. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21625. * @return true if the camera is ready
  21626. */
  21627. Camera.prototype.isReady = function (completeCheck) {
  21628. if (completeCheck === void 0) { completeCheck = false; }
  21629. if (completeCheck) {
  21630. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21631. var pp = _a[_i];
  21632. if (pp && !pp.isReady()) {
  21633. return false;
  21634. }
  21635. }
  21636. }
  21637. return _super.prototype.isReady.call(this, completeCheck);
  21638. };
  21639. //Cache
  21640. Camera.prototype._initCache = function () {
  21641. _super.prototype._initCache.call(this);
  21642. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21643. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21644. this._cache.mode = undefined;
  21645. this._cache.minZ = undefined;
  21646. this._cache.maxZ = undefined;
  21647. this._cache.fov = undefined;
  21648. this._cache.fovMode = undefined;
  21649. this._cache.aspectRatio = undefined;
  21650. this._cache.orthoLeft = undefined;
  21651. this._cache.orthoRight = undefined;
  21652. this._cache.orthoBottom = undefined;
  21653. this._cache.orthoTop = undefined;
  21654. this._cache.renderWidth = undefined;
  21655. this._cache.renderHeight = undefined;
  21656. };
  21657. Camera.prototype._updateCache = function (ignoreParentClass) {
  21658. if (!ignoreParentClass) {
  21659. _super.prototype._updateCache.call(this);
  21660. }
  21661. this._cache.position.copyFrom(this.position);
  21662. this._cache.upVector.copyFrom(this.upVector);
  21663. };
  21664. // Synchronized
  21665. Camera.prototype._isSynchronized = function () {
  21666. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21667. };
  21668. Camera.prototype._isSynchronizedViewMatrix = function () {
  21669. if (!_super.prototype._isSynchronized.call(this))
  21670. return false;
  21671. return this._cache.position.equals(this.position)
  21672. && this._cache.upVector.equals(this.upVector)
  21673. && this.isSynchronizedWithParent();
  21674. };
  21675. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21676. var check = this._cache.mode === this.mode
  21677. && this._cache.minZ === this.minZ
  21678. && this._cache.maxZ === this.maxZ;
  21679. if (!check) {
  21680. return false;
  21681. }
  21682. var engine = this.getEngine();
  21683. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21684. check = this._cache.fov === this.fov
  21685. && this._cache.fovMode === this.fovMode
  21686. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21687. }
  21688. else {
  21689. check = this._cache.orthoLeft === this.orthoLeft
  21690. && this._cache.orthoRight === this.orthoRight
  21691. && this._cache.orthoBottom === this.orthoBottom
  21692. && this._cache.orthoTop === this.orthoTop
  21693. && this._cache.renderWidth === engine.getRenderWidth()
  21694. && this._cache.renderHeight === engine.getRenderHeight();
  21695. }
  21696. return check;
  21697. };
  21698. // Controls
  21699. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21700. };
  21701. Camera.prototype.detachControl = function (element) {
  21702. };
  21703. Camera.prototype.update = function () {
  21704. this._checkInputs();
  21705. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21706. this._updateRigCameras();
  21707. }
  21708. };
  21709. Camera.prototype._checkInputs = function () {
  21710. this.onAfterCheckInputsObservable.notifyObservers(this);
  21711. };
  21712. Object.defineProperty(Camera.prototype, "rigCameras", {
  21713. get: function () {
  21714. return this._rigCameras;
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21720. get: function () {
  21721. return this._rigPostProcess;
  21722. },
  21723. enumerable: true,
  21724. configurable: true
  21725. });
  21726. /**
  21727. * Internal, gets the first post proces.
  21728. * @returns the first post process to be run on this camera.
  21729. */
  21730. Camera.prototype._getFirstPostProcess = function () {
  21731. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  21732. if (this._postProcesses[ppIndex] !== null) {
  21733. return this._postProcesses[ppIndex];
  21734. }
  21735. }
  21736. return null;
  21737. };
  21738. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21739. // invalidate framebuffer
  21740. var firstPostProcess = this._getFirstPostProcess();
  21741. if (firstPostProcess) {
  21742. firstPostProcess.markTextureDirty();
  21743. }
  21744. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21745. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21746. var cam = this._rigCameras[i];
  21747. var rigPostProcess = cam._rigPostProcess;
  21748. // for VR rig, there does not have to be a post process
  21749. if (rigPostProcess) {
  21750. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21751. if (isPass) {
  21752. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21753. cam.isIntermediate = this._postProcesses.length === 0;
  21754. }
  21755. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21756. rigPostProcess.markTextureDirty();
  21757. }
  21758. else {
  21759. cam._postProcesses = this._postProcesses.slice(0);
  21760. }
  21761. }
  21762. };
  21763. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21764. if (insertAt === void 0) { insertAt = null; }
  21765. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21766. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21767. return 0;
  21768. }
  21769. if (insertAt == null || insertAt < 0) {
  21770. this._postProcesses.push(postProcess);
  21771. }
  21772. else if (this._postProcesses[insertAt] === null) {
  21773. this._postProcesses[insertAt] = postProcess;
  21774. }
  21775. else {
  21776. this._postProcesses.splice(insertAt, 0, postProcess);
  21777. }
  21778. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21779. return this._postProcesses.indexOf(postProcess);
  21780. };
  21781. Camera.prototype.detachPostProcess = function (postProcess) {
  21782. var idx = this._postProcesses.indexOf(postProcess);
  21783. if (idx !== -1) {
  21784. this._postProcesses[idx] = null;
  21785. }
  21786. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21787. };
  21788. Camera.prototype.getWorldMatrix = function () {
  21789. if (!this._worldMatrix) {
  21790. this._worldMatrix = BABYLON.Matrix.Identity();
  21791. }
  21792. var viewMatrix = this.getViewMatrix();
  21793. viewMatrix.invertToRef(this._worldMatrix);
  21794. return this._worldMatrix;
  21795. };
  21796. Camera.prototype._getViewMatrix = function () {
  21797. return BABYLON.Matrix.Identity();
  21798. };
  21799. Camera.prototype.getViewMatrix = function (force) {
  21800. if (!force && this._isSynchronizedViewMatrix()) {
  21801. return this._computedViewMatrix;
  21802. }
  21803. this.updateCache();
  21804. this._computedViewMatrix = this._getViewMatrix();
  21805. this._currentRenderId = this.getScene().getRenderId();
  21806. this._childRenderId = this._currentRenderId;
  21807. this._refreshFrustumPlanes = true;
  21808. if (!this.parent || !this.parent.getWorldMatrix) {
  21809. this._globalPosition.copyFrom(this.position);
  21810. }
  21811. else {
  21812. if (!this._worldMatrix) {
  21813. this._worldMatrix = BABYLON.Matrix.Identity();
  21814. }
  21815. this._computedViewMatrix.invertToRef(this._worldMatrix);
  21816. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  21817. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  21818. this._computedViewMatrix.invert();
  21819. this._markSyncedWithParent();
  21820. }
  21821. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  21822. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  21823. }
  21824. this.onViewMatrixChangedObservable.notifyObservers(this);
  21825. return this._computedViewMatrix;
  21826. };
  21827. Camera.prototype.freezeProjectionMatrix = function (projection) {
  21828. this._doNotComputeProjectionMatrix = true;
  21829. if (projection !== undefined) {
  21830. this._projectionMatrix = projection;
  21831. }
  21832. };
  21833. ;
  21834. Camera.prototype.unfreezeProjectionMatrix = function () {
  21835. this._doNotComputeProjectionMatrix = false;
  21836. };
  21837. ;
  21838. Camera.prototype.getProjectionMatrix = function (force) {
  21839. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  21840. return this._projectionMatrix;
  21841. }
  21842. // Cache
  21843. this._cache.mode = this.mode;
  21844. this._cache.minZ = this.minZ;
  21845. this._cache.maxZ = this.maxZ;
  21846. // Matrix
  21847. this._refreshFrustumPlanes = true;
  21848. var engine = this.getEngine();
  21849. var scene = this.getScene();
  21850. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21851. this._cache.fov = this.fov;
  21852. this._cache.fovMode = this.fovMode;
  21853. this._cache.aspectRatio = engine.getAspectRatio(this);
  21854. if (this.minZ <= 0) {
  21855. this.minZ = 0.1;
  21856. }
  21857. if (scene.useRightHandedSystem) {
  21858. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21859. }
  21860. else {
  21861. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21862. }
  21863. }
  21864. else {
  21865. var halfWidth = engine.getRenderWidth() / 2.0;
  21866. var halfHeight = engine.getRenderHeight() / 2.0;
  21867. if (scene.useRightHandedSystem) {
  21868. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21869. }
  21870. else {
  21871. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21872. }
  21873. this._cache.orthoLeft = this.orthoLeft;
  21874. this._cache.orthoRight = this.orthoRight;
  21875. this._cache.orthoBottom = this.orthoBottom;
  21876. this._cache.orthoTop = this.orthoTop;
  21877. this._cache.renderWidth = engine.getRenderWidth();
  21878. this._cache.renderHeight = engine.getRenderHeight();
  21879. }
  21880. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  21881. return this._projectionMatrix;
  21882. };
  21883. Camera.prototype.getTranformationMatrix = function () {
  21884. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21885. return this._transformMatrix;
  21886. };
  21887. Camera.prototype.updateFrustumPlanes = function () {
  21888. if (!this._refreshFrustumPlanes) {
  21889. return;
  21890. }
  21891. this.getTranformationMatrix();
  21892. if (!this._frustumPlanes) {
  21893. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21894. }
  21895. else {
  21896. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21897. }
  21898. this._refreshFrustumPlanes = false;
  21899. };
  21900. Camera.prototype.isInFrustum = function (target) {
  21901. this.updateFrustumPlanes();
  21902. return target.isInFrustum(this._frustumPlanes);
  21903. };
  21904. Camera.prototype.isCompletelyInFrustum = function (target) {
  21905. this.updateFrustumPlanes();
  21906. return target.isCompletelyInFrustum(this._frustumPlanes);
  21907. };
  21908. Camera.prototype.getForwardRay = function (length, transform, origin) {
  21909. if (length === void 0) { length = 100; }
  21910. if (!transform) {
  21911. transform = this.getWorldMatrix();
  21912. }
  21913. if (!origin) {
  21914. origin = this.position;
  21915. }
  21916. var forward = new BABYLON.Vector3(0, 0, 1);
  21917. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  21918. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  21919. return new BABYLON.Ray(origin, direction, length);
  21920. };
  21921. /**
  21922. * Releases resources associated with this node.
  21923. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21924. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21925. */
  21926. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21927. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21928. // Observables
  21929. this.onViewMatrixChangedObservable.clear();
  21930. this.onProjectionMatrixChangedObservable.clear();
  21931. this.onAfterCheckInputsObservable.clear();
  21932. this.onRestoreStateObservable.clear();
  21933. // Inputs
  21934. if (this.inputs) {
  21935. this.inputs.clear();
  21936. }
  21937. // Animations
  21938. this.getScene().stopAnimation(this);
  21939. // Remove from scene
  21940. this.getScene().removeCamera(this);
  21941. while (this._rigCameras.length > 0) {
  21942. var camera = this._rigCameras.pop();
  21943. if (camera) {
  21944. camera.dispose();
  21945. }
  21946. }
  21947. // Postprocesses
  21948. if (this._rigPostProcess) {
  21949. this._rigPostProcess.dispose(this);
  21950. this._rigPostProcess = null;
  21951. this._postProcesses = [];
  21952. }
  21953. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21954. this._rigPostProcess = null;
  21955. this._postProcesses = [];
  21956. }
  21957. else {
  21958. var i = this._postProcesses.length;
  21959. while (--i >= 0) {
  21960. var postProcess = this._postProcesses[i];
  21961. if (postProcess) {
  21962. postProcess.dispose(this);
  21963. }
  21964. }
  21965. }
  21966. // Render targets
  21967. var i = this.customRenderTargets.length;
  21968. while (--i >= 0) {
  21969. this.customRenderTargets[i].dispose();
  21970. }
  21971. this.customRenderTargets = [];
  21972. // Active Meshes
  21973. this._activeMeshes.dispose();
  21974. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21975. };
  21976. Object.defineProperty(Camera.prototype, "leftCamera", {
  21977. // ---- Camera rigs section ----
  21978. get: function () {
  21979. if (this._rigCameras.length < 1) {
  21980. return null;
  21981. }
  21982. return this._rigCameras[0];
  21983. },
  21984. enumerable: true,
  21985. configurable: true
  21986. });
  21987. Object.defineProperty(Camera.prototype, "rightCamera", {
  21988. get: function () {
  21989. if (this._rigCameras.length < 2) {
  21990. return null;
  21991. }
  21992. return this._rigCameras[1];
  21993. },
  21994. enumerable: true,
  21995. configurable: true
  21996. });
  21997. Camera.prototype.getLeftTarget = function () {
  21998. if (this._rigCameras.length < 1) {
  21999. return null;
  22000. }
  22001. return this._rigCameras[0].getTarget();
  22002. };
  22003. Camera.prototype.getRightTarget = function () {
  22004. if (this._rigCameras.length < 2) {
  22005. return null;
  22006. }
  22007. return this._rigCameras[1].getTarget();
  22008. };
  22009. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22010. if (this.cameraRigMode === mode) {
  22011. return;
  22012. }
  22013. while (this._rigCameras.length > 0) {
  22014. var camera = this._rigCameras.pop();
  22015. if (camera) {
  22016. camera.dispose();
  22017. }
  22018. }
  22019. this.cameraRigMode = mode;
  22020. this._cameraRigParams = {};
  22021. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22022. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22023. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22024. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22025. // create the rig cameras, unless none
  22026. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22027. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22028. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22029. if (leftCamera && rightCamera) {
  22030. this._rigCameras.push(leftCamera);
  22031. this._rigCameras.push(rightCamera);
  22032. }
  22033. }
  22034. switch (this.cameraRigMode) {
  22035. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22036. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22037. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22038. break;
  22039. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22040. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22041. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22042. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22043. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22044. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22045. break;
  22046. case Camera.RIG_MODE_VR:
  22047. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22048. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22049. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22050. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22051. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22052. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22053. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22054. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22055. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22056. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22057. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22058. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22059. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22060. if (metrics.compensateDistortion) {
  22061. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22062. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22063. }
  22064. break;
  22065. case Camera.RIG_MODE_WEBVR:
  22066. if (rigParams.vrDisplay) {
  22067. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22068. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22069. //Left eye
  22070. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22071. this._rigCameras[0].setCameraRigParameter("left", true);
  22072. //leaving this for future reference
  22073. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22074. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22075. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22076. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22077. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22078. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22079. this._rigCameras[0].parent = this;
  22080. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22081. //Right eye
  22082. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22083. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22084. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22085. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22086. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22087. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22088. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22089. this._rigCameras[1].parent = this;
  22090. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22091. if (Camera.UseAlternateWebVRRendering) {
  22092. this._rigCameras[1]._skipRendering = true;
  22093. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22094. }
  22095. }
  22096. break;
  22097. }
  22098. this._cascadePostProcessesToRigCams();
  22099. this.update();
  22100. };
  22101. Camera.prototype._getVRProjectionMatrix = function () {
  22102. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22103. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22104. return this._projectionMatrix;
  22105. };
  22106. Camera.prototype._updateCameraRotationMatrix = function () {
  22107. //Here for WebVR
  22108. };
  22109. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22110. //Here for WebVR
  22111. };
  22112. /**
  22113. * This function MUST be overwritten by the different WebVR cameras available.
  22114. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22115. */
  22116. Camera.prototype._getWebVRProjectionMatrix = function () {
  22117. return BABYLON.Matrix.Identity();
  22118. };
  22119. /**
  22120. * This function MUST be overwritten by the different WebVR cameras available.
  22121. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22122. */
  22123. Camera.prototype._getWebVRViewMatrix = function () {
  22124. return BABYLON.Matrix.Identity();
  22125. };
  22126. Camera.prototype.setCameraRigParameter = function (name, value) {
  22127. if (!this._cameraRigParams) {
  22128. this._cameraRigParams = {};
  22129. }
  22130. this._cameraRigParams[name] = value;
  22131. //provisionnally:
  22132. if (name === "interaxialDistance") {
  22133. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22134. }
  22135. };
  22136. /**
  22137. * needs to be overridden by children so sub has required properties to be copied
  22138. */
  22139. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22140. return null;
  22141. };
  22142. /**
  22143. * May need to be overridden by children
  22144. */
  22145. Camera.prototype._updateRigCameras = function () {
  22146. for (var i = 0; i < this._rigCameras.length; i++) {
  22147. this._rigCameras[i].minZ = this.minZ;
  22148. this._rigCameras[i].maxZ = this.maxZ;
  22149. this._rigCameras[i].fov = this.fov;
  22150. }
  22151. // only update viewport when ANAGLYPH
  22152. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22153. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22154. }
  22155. };
  22156. Camera.prototype._setupInputs = function () {
  22157. };
  22158. Camera.prototype.serialize = function () {
  22159. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22160. // Type
  22161. serializationObject.type = this.getClassName();
  22162. // Parent
  22163. if (this.parent) {
  22164. serializationObject.parentId = this.parent.id;
  22165. }
  22166. if (this.inputs) {
  22167. this.inputs.serialize(serializationObject);
  22168. }
  22169. // Animations
  22170. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22171. serializationObject.ranges = this.serializeAnimationRanges();
  22172. return serializationObject;
  22173. };
  22174. Camera.prototype.clone = function (name) {
  22175. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22176. };
  22177. Camera.prototype.getDirection = function (localAxis) {
  22178. var result = BABYLON.Vector3.Zero();
  22179. this.getDirectionToRef(localAxis, result);
  22180. return result;
  22181. };
  22182. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22183. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22184. };
  22185. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22186. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22187. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22188. switch (type) {
  22189. case "ArcRotateCamera":
  22190. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22191. case "DeviceOrientationCamera":
  22192. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22193. case "FollowCamera":
  22194. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22195. case "ArcFollowCamera":
  22196. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22197. case "GamepadCamera":
  22198. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22199. case "TouchCamera":
  22200. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22201. case "VirtualJoysticksCamera":
  22202. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22203. case "WebVRFreeCamera":
  22204. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22205. case "WebVRGamepadCamera":
  22206. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22207. case "VRDeviceOrientationFreeCamera":
  22208. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22209. case "VRDeviceOrientationGamepadCamera":
  22210. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22211. case "AnaglyphArcRotateCamera":
  22212. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22213. case "AnaglyphFreeCamera":
  22214. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22215. case "AnaglyphGamepadCamera":
  22216. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22217. case "AnaglyphUniversalCamera":
  22218. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22219. case "StereoscopicArcRotateCamera":
  22220. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22221. case "StereoscopicFreeCamera":
  22222. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22223. case "StereoscopicGamepadCamera":
  22224. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22225. case "StereoscopicUniversalCamera":
  22226. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22227. case "FreeCamera":// Forcing Universal here
  22228. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22229. default:// Universal Camera is the default value
  22230. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22231. }
  22232. };
  22233. Camera.prototype.computeWorldMatrix = function () {
  22234. return this.getWorldMatrix();
  22235. };
  22236. Camera.Parse = function (parsedCamera, scene) {
  22237. var type = parsedCamera.type;
  22238. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22239. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22240. // Parent
  22241. if (parsedCamera.parentId) {
  22242. camera._waitingParentId = parsedCamera.parentId;
  22243. }
  22244. //If camera has an input manager, let it parse inputs settings
  22245. if (camera.inputs) {
  22246. camera.inputs.parse(parsedCamera);
  22247. camera._setupInputs();
  22248. }
  22249. if (camera.setPosition) {
  22250. camera.position.copyFromFloats(0, 0, 0);
  22251. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22252. }
  22253. // Target
  22254. if (parsedCamera.target) {
  22255. if (camera.setTarget) {
  22256. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22257. }
  22258. }
  22259. // Apply 3d rig, when found
  22260. if (parsedCamera.cameraRigMode) {
  22261. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22262. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22263. }
  22264. // Animations
  22265. if (parsedCamera.animations) {
  22266. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22267. var parsedAnimation = parsedCamera.animations[animationIndex];
  22268. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22269. }
  22270. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22271. }
  22272. if (parsedCamera.autoAnimate) {
  22273. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22274. }
  22275. return camera;
  22276. };
  22277. // Statics
  22278. Camera._PERSPECTIVE_CAMERA = 0;
  22279. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22280. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22281. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22282. Camera._RIG_MODE_NONE = 0;
  22283. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22284. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22285. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22286. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22287. Camera._RIG_MODE_VR = 20;
  22288. Camera._RIG_MODE_WEBVR = 21;
  22289. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22290. Camera.UseAlternateWebVRRendering = false;
  22291. __decorate([
  22292. BABYLON.serializeAsVector3()
  22293. ], Camera.prototype, "position", void 0);
  22294. __decorate([
  22295. BABYLON.serializeAsVector3()
  22296. ], Camera.prototype, "upVector", void 0);
  22297. __decorate([
  22298. BABYLON.serialize()
  22299. ], Camera.prototype, "orthoLeft", void 0);
  22300. __decorate([
  22301. BABYLON.serialize()
  22302. ], Camera.prototype, "orthoRight", void 0);
  22303. __decorate([
  22304. BABYLON.serialize()
  22305. ], Camera.prototype, "orthoBottom", void 0);
  22306. __decorate([
  22307. BABYLON.serialize()
  22308. ], Camera.prototype, "orthoTop", void 0);
  22309. __decorate([
  22310. BABYLON.serialize()
  22311. ], Camera.prototype, "fov", void 0);
  22312. __decorate([
  22313. BABYLON.serialize()
  22314. ], Camera.prototype, "minZ", void 0);
  22315. __decorate([
  22316. BABYLON.serialize()
  22317. ], Camera.prototype, "maxZ", void 0);
  22318. __decorate([
  22319. BABYLON.serialize()
  22320. ], Camera.prototype, "inertia", void 0);
  22321. __decorate([
  22322. BABYLON.serialize()
  22323. ], Camera.prototype, "mode", void 0);
  22324. __decorate([
  22325. BABYLON.serialize()
  22326. ], Camera.prototype, "layerMask", void 0);
  22327. __decorate([
  22328. BABYLON.serialize()
  22329. ], Camera.prototype, "fovMode", void 0);
  22330. __decorate([
  22331. BABYLON.serialize()
  22332. ], Camera.prototype, "cameraRigMode", void 0);
  22333. __decorate([
  22334. BABYLON.serialize()
  22335. ], Camera.prototype, "interaxialDistance", void 0);
  22336. __decorate([
  22337. BABYLON.serialize()
  22338. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22339. return Camera;
  22340. }(BABYLON.Node));
  22341. BABYLON.Camera = Camera;
  22342. })(BABYLON || (BABYLON = {}));
  22343. //# sourceMappingURL=babylon.camera.js.map
  22344. "use strict";
  22345. var BABYLON;
  22346. (function (BABYLON) {
  22347. var RenderingManager = /** @class */ (function () {
  22348. function RenderingManager(scene) {
  22349. this._renderingGroups = new Array();
  22350. this._autoClearDepthStencil = {};
  22351. this._customOpaqueSortCompareFn = {};
  22352. this._customAlphaTestSortCompareFn = {};
  22353. this._customTransparentSortCompareFn = {};
  22354. this._renderinGroupInfo = null;
  22355. this._scene = scene;
  22356. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22357. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22358. }
  22359. }
  22360. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22361. if (depth === void 0) { depth = true; }
  22362. if (stencil === void 0) { stencil = true; }
  22363. if (this._depthStencilBufferAlreadyCleaned) {
  22364. return;
  22365. }
  22366. this._scene.getEngine().clear(null, false, depth, stencil);
  22367. this._depthStencilBufferAlreadyCleaned = true;
  22368. };
  22369. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22370. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22371. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22372. var info = null;
  22373. if (observable) {
  22374. if (!this._renderinGroupInfo) {
  22375. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22376. }
  22377. info = this._renderinGroupInfo;
  22378. info.scene = this._scene;
  22379. info.camera = this._scene.activeCamera;
  22380. }
  22381. // Dispatch sprites
  22382. if (renderSprites) {
  22383. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22384. var manager = this._scene.spriteManagers[index];
  22385. this.dispatchSprites(manager);
  22386. }
  22387. }
  22388. // Render
  22389. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22390. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22391. var renderingGroup = this._renderingGroups[index];
  22392. if (!renderingGroup && !observable)
  22393. continue;
  22394. var renderingGroupMask = 0;
  22395. // Fire PRECLEAR stage
  22396. if (observable && info) {
  22397. renderingGroupMask = Math.pow(2, index);
  22398. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22399. info.renderingGroupId = index;
  22400. observable.notifyObservers(info, renderingGroupMask);
  22401. }
  22402. // Clear depth/stencil if needed
  22403. if (RenderingManager.AUTOCLEAR) {
  22404. var autoClear = this._autoClearDepthStencil[index];
  22405. if (autoClear && autoClear.autoClear) {
  22406. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22407. }
  22408. }
  22409. if (observable && info) {
  22410. // Fire PREOPAQUE stage
  22411. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22412. observable.notifyObservers(info, renderingGroupMask);
  22413. // Fire PRETRANSPARENT stage
  22414. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22415. observable.notifyObservers(info, renderingGroupMask);
  22416. }
  22417. if (renderingGroup)
  22418. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22419. // Fire POSTTRANSPARENT stage
  22420. if (observable && info) {
  22421. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22422. observable.notifyObservers(info, renderingGroupMask);
  22423. }
  22424. }
  22425. };
  22426. RenderingManager.prototype.reset = function () {
  22427. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22428. var renderingGroup = this._renderingGroups[index];
  22429. if (renderingGroup) {
  22430. renderingGroup.prepare();
  22431. }
  22432. }
  22433. };
  22434. RenderingManager.prototype.dispose = function () {
  22435. this.freeRenderingGroups();
  22436. this._renderingGroups.length = 0;
  22437. };
  22438. /**
  22439. * Clear the info related to rendering groups preventing retention points during dispose.
  22440. */
  22441. RenderingManager.prototype.freeRenderingGroups = function () {
  22442. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22443. var renderingGroup = this._renderingGroups[index];
  22444. if (renderingGroup) {
  22445. renderingGroup.dispose();
  22446. }
  22447. }
  22448. };
  22449. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22450. if (this._renderingGroups[renderingGroupId] === undefined) {
  22451. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22452. }
  22453. };
  22454. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22455. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22456. this._prepareRenderingGroup(renderingGroupId);
  22457. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22458. };
  22459. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22460. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22461. this._prepareRenderingGroup(renderingGroupId);
  22462. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22463. };
  22464. /**
  22465. * @param subMesh The submesh to dispatch
  22466. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22467. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22468. */
  22469. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22470. if (mesh === undefined) {
  22471. mesh = subMesh.getMesh();
  22472. }
  22473. var renderingGroupId = mesh.renderingGroupId || 0;
  22474. this._prepareRenderingGroup(renderingGroupId);
  22475. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22476. };
  22477. /**
  22478. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22479. * This allowed control for front to back rendering or reversly depending of the special needs.
  22480. *
  22481. * @param renderingGroupId The rendering group id corresponding to its index
  22482. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22483. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22484. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22485. */
  22486. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22487. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22488. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22489. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22490. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22491. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22492. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22493. if (this._renderingGroups[renderingGroupId]) {
  22494. var group = this._renderingGroups[renderingGroupId];
  22495. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22496. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22497. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22498. }
  22499. };
  22500. /**
  22501. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22502. *
  22503. * @param renderingGroupId The rendering group id corresponding to its index
  22504. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22505. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22506. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22507. */
  22508. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22509. if (depth === void 0) { depth = true; }
  22510. if (stencil === void 0) { stencil = true; }
  22511. this._autoClearDepthStencil[renderingGroupId] = {
  22512. autoClear: autoClearDepthStencil,
  22513. depth: depth,
  22514. stencil: stencil
  22515. };
  22516. };
  22517. /**
  22518. * The max id used for rendering groups (not included)
  22519. */
  22520. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22521. /**
  22522. * The min id used for rendering groups (included)
  22523. */
  22524. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22525. /**
  22526. * Used to globally prevent autoclearing scenes.
  22527. */
  22528. RenderingManager.AUTOCLEAR = true;
  22529. return RenderingManager;
  22530. }());
  22531. BABYLON.RenderingManager = RenderingManager;
  22532. })(BABYLON || (BABYLON = {}));
  22533. //# sourceMappingURL=babylon.renderingManager.js.map
  22534. "use strict";
  22535. var BABYLON;
  22536. (function (BABYLON) {
  22537. var RenderingGroup = /** @class */ (function () {
  22538. /**
  22539. * Creates a new rendering group.
  22540. * @param index The rendering group index
  22541. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22542. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22543. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22544. */
  22545. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22546. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22547. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22548. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22549. this.index = index;
  22550. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22551. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22552. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22553. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22554. this._particleSystems = new BABYLON.SmartArray(256);
  22555. this._spriteManagers = new BABYLON.SmartArray(256);
  22556. this._edgesRenderers = new BABYLON.SmartArray(16);
  22557. this._scene = scene;
  22558. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22559. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22560. this.transparentSortCompareFn = transparentSortCompareFn;
  22561. }
  22562. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22563. /**
  22564. * Set the opaque sort comparison function.
  22565. * If null the sub meshes will be render in the order they were created
  22566. */
  22567. set: function (value) {
  22568. this._opaqueSortCompareFn = value;
  22569. if (value) {
  22570. this._renderOpaque = this.renderOpaqueSorted;
  22571. }
  22572. else {
  22573. this._renderOpaque = RenderingGroup.renderUnsorted;
  22574. }
  22575. },
  22576. enumerable: true,
  22577. configurable: true
  22578. });
  22579. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22580. /**
  22581. * Set the alpha test sort comparison function.
  22582. * If null the sub meshes will be render in the order they were created
  22583. */
  22584. set: function (value) {
  22585. this._alphaTestSortCompareFn = value;
  22586. if (value) {
  22587. this._renderAlphaTest = this.renderAlphaTestSorted;
  22588. }
  22589. else {
  22590. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22591. }
  22592. },
  22593. enumerable: true,
  22594. configurable: true
  22595. });
  22596. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22597. /**
  22598. * Set the transparent sort comparison function.
  22599. * If null the sub meshes will be render in the order they were created
  22600. */
  22601. set: function (value) {
  22602. if (value) {
  22603. this._transparentSortCompareFn = value;
  22604. }
  22605. else {
  22606. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22607. }
  22608. this._renderTransparent = this.renderTransparentSorted;
  22609. },
  22610. enumerable: true,
  22611. configurable: true
  22612. });
  22613. /**
  22614. * Render all the sub meshes contained in the group.
  22615. * @param customRenderFunction Used to override the default render behaviour of the group.
  22616. * @returns true if rendered some submeshes.
  22617. */
  22618. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22619. if (customRenderFunction) {
  22620. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22621. return;
  22622. }
  22623. var engine = this._scene.getEngine();
  22624. // Depth only
  22625. if (this._depthOnlySubMeshes.length !== 0) {
  22626. engine.setColorWrite(false);
  22627. this._renderAlphaTest(this._depthOnlySubMeshes);
  22628. engine.setColorWrite(true);
  22629. }
  22630. // Opaque
  22631. if (this._opaqueSubMeshes.length !== 0) {
  22632. this._renderOpaque(this._opaqueSubMeshes);
  22633. }
  22634. // Alpha test
  22635. if (this._alphaTestSubMeshes.length !== 0) {
  22636. this._renderAlphaTest(this._alphaTestSubMeshes);
  22637. }
  22638. var stencilState = engine.getStencilBuffer();
  22639. engine.setStencilBuffer(false);
  22640. // Sprites
  22641. if (renderSprites) {
  22642. this._renderSprites();
  22643. }
  22644. // Particles
  22645. if (renderParticles) {
  22646. this._renderParticles(activeMeshes);
  22647. }
  22648. if (this.onBeforeTransparentRendering) {
  22649. this.onBeforeTransparentRendering();
  22650. }
  22651. // Transparent
  22652. if (this._transparentSubMeshes.length !== 0) {
  22653. this._renderTransparent(this._transparentSubMeshes);
  22654. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22655. }
  22656. // Set back stencil to false in case it changes before the edge renderer.
  22657. engine.setStencilBuffer(false);
  22658. // Edges
  22659. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22660. this._edgesRenderers.data[edgesRendererIndex].render();
  22661. }
  22662. // Restore Stencil state.
  22663. engine.setStencilBuffer(stencilState);
  22664. };
  22665. /**
  22666. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22667. * @param subMeshes The submeshes to render
  22668. */
  22669. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22670. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22671. };
  22672. /**
  22673. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22674. * @param subMeshes The submeshes to render
  22675. */
  22676. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22677. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22678. };
  22679. /**
  22680. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22681. * @param subMeshes The submeshes to render
  22682. */
  22683. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22684. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22685. };
  22686. /**
  22687. * Renders the submeshes in a specified order.
  22688. * @param subMeshes The submeshes to sort before render
  22689. * @param sortCompareFn The comparison function use to sort
  22690. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22691. * @param transparent Specifies to activate blending if true
  22692. */
  22693. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22694. var subIndex = 0;
  22695. var subMesh;
  22696. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22697. for (; subIndex < subMeshes.length; subIndex++) {
  22698. subMesh = subMeshes.data[subIndex];
  22699. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22700. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22701. }
  22702. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22703. if (sortCompareFn) {
  22704. sortedArray.sort(sortCompareFn);
  22705. }
  22706. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22707. subMesh = sortedArray[subIndex];
  22708. if (transparent) {
  22709. var material = subMesh.getMaterial();
  22710. if (material && material.needDepthPrePass) {
  22711. var engine = material.getScene().getEngine();
  22712. engine.setColorWrite(false);
  22713. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22714. subMesh.render(false);
  22715. engine.setColorWrite(true);
  22716. }
  22717. }
  22718. subMesh.render(transparent);
  22719. }
  22720. };
  22721. /**
  22722. * Renders the submeshes in the order they were dispatched (no sort applied).
  22723. * @param subMeshes The submeshes to render
  22724. */
  22725. RenderingGroup.renderUnsorted = function (subMeshes) {
  22726. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22727. var submesh = subMeshes.data[subIndex];
  22728. submesh.render(false);
  22729. }
  22730. };
  22731. /**
  22732. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22733. * are rendered back to front if in the same alpha index.
  22734. *
  22735. * @param a The first submesh
  22736. * @param b The second submesh
  22737. * @returns The result of the comparison
  22738. */
  22739. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22740. // Alpha index first
  22741. if (a._alphaIndex > b._alphaIndex) {
  22742. return 1;
  22743. }
  22744. if (a._alphaIndex < b._alphaIndex) {
  22745. return -1;
  22746. }
  22747. // Then distance to camera
  22748. return RenderingGroup.backToFrontSortCompare(a, b);
  22749. };
  22750. /**
  22751. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22752. * are rendered back to front.
  22753. *
  22754. * @param a The first submesh
  22755. * @param b The second submesh
  22756. * @returns The result of the comparison
  22757. */
  22758. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22759. // Then distance to camera
  22760. if (a._distanceToCamera < b._distanceToCamera) {
  22761. return 1;
  22762. }
  22763. if (a._distanceToCamera > b._distanceToCamera) {
  22764. return -1;
  22765. }
  22766. return 0;
  22767. };
  22768. /**
  22769. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22770. * are rendered front to back (prevent overdraw).
  22771. *
  22772. * @param a The first submesh
  22773. * @param b The second submesh
  22774. * @returns The result of the comparison
  22775. */
  22776. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22777. // Then distance to camera
  22778. if (a._distanceToCamera < b._distanceToCamera) {
  22779. return -1;
  22780. }
  22781. if (a._distanceToCamera > b._distanceToCamera) {
  22782. return 1;
  22783. }
  22784. return 0;
  22785. };
  22786. /**
  22787. * Resets the different lists of submeshes to prepare a new frame.
  22788. */
  22789. RenderingGroup.prototype.prepare = function () {
  22790. this._opaqueSubMeshes.reset();
  22791. this._transparentSubMeshes.reset();
  22792. this._alphaTestSubMeshes.reset();
  22793. this._depthOnlySubMeshes.reset();
  22794. this._particleSystems.reset();
  22795. this._spriteManagers.reset();
  22796. this._edgesRenderers.reset();
  22797. };
  22798. RenderingGroup.prototype.dispose = function () {
  22799. this._opaqueSubMeshes.dispose();
  22800. this._transparentSubMeshes.dispose();
  22801. this._alphaTestSubMeshes.dispose();
  22802. this._depthOnlySubMeshes.dispose();
  22803. this._particleSystems.dispose();
  22804. this._spriteManagers.dispose();
  22805. this._edgesRenderers.dispose();
  22806. };
  22807. /**
  22808. * Inserts the submesh in its correct queue depending on its material.
  22809. * @param subMesh The submesh to dispatch
  22810. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22811. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22812. */
  22813. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  22814. // Get mesh and materials if not provided
  22815. if (mesh === undefined) {
  22816. mesh = subMesh.getMesh();
  22817. }
  22818. if (material === undefined) {
  22819. material = subMesh.getMaterial();
  22820. }
  22821. if (material === null || material === undefined) {
  22822. return;
  22823. }
  22824. if (material.needAlphaBlendingForMesh(mesh)) {
  22825. this._transparentSubMeshes.push(subMesh);
  22826. }
  22827. else if (material.needAlphaTesting()) {
  22828. if (material.needDepthPrePass) {
  22829. this._depthOnlySubMeshes.push(subMesh);
  22830. }
  22831. this._alphaTestSubMeshes.push(subMesh);
  22832. }
  22833. else {
  22834. if (material.needDepthPrePass) {
  22835. this._depthOnlySubMeshes.push(subMesh);
  22836. }
  22837. this._opaqueSubMeshes.push(subMesh); // Opaque
  22838. }
  22839. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  22840. this._edgesRenderers.push(mesh._edgesRenderer);
  22841. }
  22842. };
  22843. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  22844. this._spriteManagers.push(spriteManager);
  22845. };
  22846. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  22847. this._particleSystems.push(particleSystem);
  22848. };
  22849. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  22850. if (this._particleSystems.length === 0) {
  22851. return;
  22852. }
  22853. // Particles
  22854. var activeCamera = this._scene.activeCamera;
  22855. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  22856. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  22857. var particleSystem = this._particleSystems.data[particleIndex];
  22858. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  22859. continue;
  22860. }
  22861. var emitter = particleSystem.emitter;
  22862. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  22863. this._scene._activeParticles.addCount(particleSystem.render(), false);
  22864. }
  22865. }
  22866. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  22867. };
  22868. RenderingGroup.prototype._renderSprites = function () {
  22869. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  22870. return;
  22871. }
  22872. // Sprites
  22873. var activeCamera = this._scene.activeCamera;
  22874. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  22875. for (var id = 0; id < this._spriteManagers.length; id++) {
  22876. var spriteManager = this._spriteManagers.data[id];
  22877. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  22878. spriteManager.render();
  22879. }
  22880. }
  22881. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  22882. };
  22883. return RenderingGroup;
  22884. }());
  22885. BABYLON.RenderingGroup = RenderingGroup;
  22886. })(BABYLON || (BABYLON = {}));
  22887. //# sourceMappingURL=babylon.renderingGroup.js.map
  22888. "use strict";
  22889. var BABYLON;
  22890. (function (BABYLON) {
  22891. /** @ignore */
  22892. var ClickInfo = /** @class */ (function () {
  22893. function ClickInfo() {
  22894. this._singleClick = false;
  22895. this._doubleClick = false;
  22896. this._hasSwiped = false;
  22897. this._ignore = false;
  22898. }
  22899. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  22900. get: function () {
  22901. return this._singleClick;
  22902. },
  22903. set: function (b) {
  22904. this._singleClick = b;
  22905. },
  22906. enumerable: true,
  22907. configurable: true
  22908. });
  22909. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  22910. get: function () {
  22911. return this._doubleClick;
  22912. },
  22913. set: function (b) {
  22914. this._doubleClick = b;
  22915. },
  22916. enumerable: true,
  22917. configurable: true
  22918. });
  22919. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  22920. get: function () {
  22921. return this._hasSwiped;
  22922. },
  22923. set: function (b) {
  22924. this._hasSwiped = b;
  22925. },
  22926. enumerable: true,
  22927. configurable: true
  22928. });
  22929. Object.defineProperty(ClickInfo.prototype, "ignore", {
  22930. get: function () {
  22931. return this._ignore;
  22932. },
  22933. set: function (b) {
  22934. this._ignore = b;
  22935. },
  22936. enumerable: true,
  22937. configurable: true
  22938. });
  22939. return ClickInfo;
  22940. }());
  22941. /**
  22942. * This class is used by the onRenderingGroupObservable
  22943. */
  22944. var RenderingGroupInfo = /** @class */ (function () {
  22945. function RenderingGroupInfo() {
  22946. }
  22947. /**
  22948. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  22949. * This stage will be fired no matter what
  22950. */
  22951. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  22952. /**
  22953. * Called before opaque object are rendered.
  22954. * This stage will be fired only if there's 3D Opaque content to render
  22955. */
  22956. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  22957. /**
  22958. * Called after the opaque objects are rendered and before the transparent ones
  22959. * This stage will be fired only if there's 3D transparent content to render
  22960. */
  22961. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  22962. /**
  22963. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  22964. * This stage will be fired no matter what
  22965. */
  22966. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  22967. return RenderingGroupInfo;
  22968. }());
  22969. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  22970. /**
  22971. * Represents a scene to be rendered by the engine.
  22972. * @see http://doc.babylonjs.com/features/scene
  22973. */
  22974. var Scene = /** @class */ (function () {
  22975. /**
  22976. * Creates a new Scene
  22977. * @param engine defines the engine to use to render this scene
  22978. */
  22979. function Scene(engine) {
  22980. // Members
  22981. /**
  22982. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  22983. */
  22984. this.autoClear = true;
  22985. /**
  22986. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  22987. */
  22988. this.autoClearDepthAndStencil = true;
  22989. /**
  22990. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  22991. */
  22992. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  22993. /**
  22994. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  22995. */
  22996. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22997. this._forceWireframe = false;
  22998. this._forcePointsCloud = false;
  22999. /**
  23000. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23001. */
  23002. this.forceShowBoundingBoxes = false;
  23003. /**
  23004. * Gets or sets a boolean indicating if animations are enabled
  23005. */
  23006. this.animationsEnabled = true;
  23007. /**
  23008. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23009. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23010. */
  23011. this.useConstantAnimationDeltaTime = false;
  23012. /**
  23013. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23014. * Please note that it requires to run a ray cast through the scene on every frame
  23015. */
  23016. this.constantlyUpdateMeshUnderPointer = false;
  23017. /**
  23018. * Defines the HTML cursor to use when hovering over interactive elements
  23019. */
  23020. this.hoverCursor = "pointer";
  23021. /**
  23022. * Defines the HTML default cursor to use (empty by default)
  23023. */
  23024. this.defaultCursor = "";
  23025. /**
  23026. * This is used to call preventDefault() on pointer down
  23027. * in order to block unwanted artifacts like system double clicks
  23028. */
  23029. this.preventDefaultOnPointerDown = true;
  23030. // Metadata
  23031. /**
  23032. * Gets or sets user defined metadata
  23033. */
  23034. this.metadata = null;
  23035. /**
  23036. * Use this array to add regular expressions used to disable offline support for specific urls
  23037. */
  23038. this.disableOfflineSupportExceptionRules = new Array();
  23039. /**
  23040. * An event triggered when the scene is disposed.
  23041. */
  23042. this.onDisposeObservable = new BABYLON.Observable();
  23043. this._onDisposeObserver = null;
  23044. /**
  23045. * An event triggered before rendering the scene (right after animations and physics)
  23046. */
  23047. this.onBeforeRenderObservable = new BABYLON.Observable();
  23048. this._onBeforeRenderObserver = null;
  23049. /**
  23050. * An event triggered after rendering the scene
  23051. */
  23052. this.onAfterRenderObservable = new BABYLON.Observable();
  23053. this._onAfterRenderObserver = null;
  23054. /**
  23055. * An event triggered before animating the scene
  23056. */
  23057. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23058. /**
  23059. * An event triggered after animations processing
  23060. */
  23061. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23062. /**
  23063. * An event triggered before draw calls are ready to be sent
  23064. */
  23065. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23066. /**
  23067. * An event triggered after draw calls have been sent
  23068. */
  23069. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23070. /**
  23071. * An event triggered when physic simulation is about to be run
  23072. */
  23073. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23074. /**
  23075. * An event triggered when physic simulation has been done
  23076. */
  23077. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23078. /**
  23079. * An event triggered when the scene is ready
  23080. */
  23081. this.onReadyObservable = new BABYLON.Observable();
  23082. /**
  23083. * An event triggered before rendering a camera
  23084. */
  23085. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23086. this._onBeforeCameraRenderObserver = null;
  23087. /**
  23088. * An event triggered after rendering a camera
  23089. */
  23090. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23091. this._onAfterCameraRenderObserver = null;
  23092. /**
  23093. * An event triggered when active meshes evaluation is about to start
  23094. */
  23095. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23096. /**
  23097. * An event triggered when active meshes evaluation is done
  23098. */
  23099. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23100. /**
  23101. * An event triggered when particles rendering is about to start
  23102. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23103. */
  23104. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23105. /**
  23106. * An event triggered when particles rendering is done
  23107. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23108. */
  23109. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23110. /**
  23111. * An event triggered when sprites rendering is about to start
  23112. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23113. */
  23114. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23115. /**
  23116. * An event triggered when sprites rendering is done
  23117. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23118. */
  23119. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23120. /**
  23121. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23122. */
  23123. this.onDataLoadedObservable = new BABYLON.Observable();
  23124. /**
  23125. * An event triggered when a camera is created
  23126. */
  23127. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23128. /**
  23129. * An event triggered when a camera is removed
  23130. */
  23131. this.onCameraRemovedObservable = new BABYLON.Observable();
  23132. /**
  23133. * An event triggered when a light is created
  23134. */
  23135. this.onNewLightAddedObservable = new BABYLON.Observable();
  23136. /**
  23137. * An event triggered when a light is removed
  23138. */
  23139. this.onLightRemovedObservable = new BABYLON.Observable();
  23140. /**
  23141. * An event triggered when a geometry is created
  23142. */
  23143. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23144. /**
  23145. * An event triggered when a geometry is removed
  23146. */
  23147. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23148. /**
  23149. * An event triggered when a transform node is created
  23150. */
  23151. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23152. /**
  23153. * An event triggered when a transform node is removed
  23154. */
  23155. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23156. /**
  23157. * An event triggered when a mesh is created
  23158. */
  23159. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23160. /**
  23161. * An event triggered when a mesh is removed
  23162. */
  23163. this.onMeshRemovedObservable = new BABYLON.Observable();
  23164. /**
  23165. * An event triggered when render targets are about to be rendered
  23166. * Can happen multiple times per frame.
  23167. */
  23168. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23169. /**
  23170. * An event triggered when render targets were rendered.
  23171. * Can happen multiple times per frame.
  23172. */
  23173. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23174. /**
  23175. * An event triggered before calculating deterministic simulation step
  23176. */
  23177. this.onBeforeStepObservable = new BABYLON.Observable();
  23178. /**
  23179. * An event triggered after calculating deterministic simulation step
  23180. */
  23181. this.onAfterStepObservable = new BABYLON.Observable();
  23182. /**
  23183. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23184. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23185. * 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)
  23186. */
  23187. this.onRenderingGroupObservable = new BABYLON.Observable();
  23188. // Animations
  23189. /**
  23190. * Gets a list of Animations associated with the scene
  23191. */
  23192. this.animations = [];
  23193. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23194. /**
  23195. * 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).
  23196. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23197. */
  23198. this.onPrePointerObservable = new BABYLON.Observable();
  23199. /**
  23200. * Observable event triggered each time an input event is received from the rendering canvas
  23201. */
  23202. this.onPointerObservable = new BABYLON.Observable();
  23203. this._meshPickProceed = false;
  23204. this._currentPickResult = null;
  23205. this._previousPickResult = null;
  23206. this._totalPointersPressed = 0;
  23207. this._doubleClickOccured = false;
  23208. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23209. this.cameraToUseForPointers = null;
  23210. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23211. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23212. this._startingPointerTime = 0;
  23213. this._previousStartingPointerTime = 0;
  23214. // Deterministic lockstep
  23215. this._timeAccumulator = 0;
  23216. this._currentStepId = 0;
  23217. this._currentInternalStep = 0;
  23218. // Keyboard
  23219. /**
  23220. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23221. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23222. */
  23223. this.onPreKeyboardObservable = new BABYLON.Observable();
  23224. /**
  23225. * Observable event triggered each time an keyboard event is received from the hosting window
  23226. */
  23227. this.onKeyboardObservable = new BABYLON.Observable();
  23228. // Coordinates system
  23229. this._useRightHandedSystem = false;
  23230. // Fog
  23231. this._fogEnabled = true;
  23232. this._fogMode = Scene.FOGMODE_NONE;
  23233. /**
  23234. * Gets or sets the fog color to use
  23235. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23236. */
  23237. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23238. /**
  23239. * Gets or sets the fog density to use
  23240. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23241. */
  23242. this.fogDensity = 0.1;
  23243. /**
  23244. * Gets or sets the fog start distance to use
  23245. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23246. */
  23247. this.fogStart = 0;
  23248. /**
  23249. * Gets or sets the fog end distance to use
  23250. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23251. */
  23252. this.fogEnd = 1000.0;
  23253. // Lights
  23254. this._shadowsEnabled = true;
  23255. this._lightsEnabled = true;
  23256. /**
  23257. * All of the lights added to this scene
  23258. * @see http://doc.babylonjs.com/babylon101/lights
  23259. */
  23260. this.lights = new Array();
  23261. // Cameras
  23262. /** All of the cameras added to this scene.
  23263. * @see http://doc.babylonjs.com/babylon101/cameras
  23264. */
  23265. this.cameras = new Array();
  23266. /** All of the active cameras added to this scene. */
  23267. this.activeCameras = new Array();
  23268. // Meshes
  23269. /**
  23270. * All of the tranform nodes added to this scene
  23271. * @see http://doc.babylonjs.com/how_to/transformnode
  23272. */
  23273. this.transformNodes = new Array();
  23274. /**
  23275. * All of the (abstract) meshes added to this scene
  23276. */
  23277. this.meshes = new Array();
  23278. /**
  23279. * All of the animation groups added to this scene
  23280. * @see http://doc.babylonjs.com/how_to/group
  23281. */
  23282. this.animationGroups = new Array();
  23283. // Geometries
  23284. this._geometries = new Array();
  23285. /**
  23286. * All of the materials added to this scene
  23287. * @see http://doc.babylonjs.com/babylon101/materials
  23288. */
  23289. this.materials = new Array();
  23290. /**
  23291. * All of the multi-materials added to this scene
  23292. * @see http://doc.babylonjs.com/how_to/multi_materials
  23293. */
  23294. this.multiMaterials = new Array();
  23295. // Textures
  23296. this._texturesEnabled = true;
  23297. /**
  23298. * All of the textures added to this scene
  23299. */
  23300. this.textures = new Array();
  23301. // Particles
  23302. /**
  23303. * Gets or sets a boolean indicating if particles are enabled on this scene
  23304. */
  23305. this.particlesEnabled = true;
  23306. /**
  23307. * All of the particle systems added to this scene
  23308. * @see http://doc.babylonjs.com/babylon101/particles
  23309. */
  23310. this.particleSystems = new Array();
  23311. // Sprites
  23312. /**
  23313. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23314. */
  23315. this.spritesEnabled = true;
  23316. /**
  23317. * All of the sprite managers added to this scene
  23318. * @see http://doc.babylonjs.com/babylon101/sprites
  23319. */
  23320. this.spriteManagers = new Array();
  23321. /**
  23322. * The list of layers (background and foreground) of the scene
  23323. */
  23324. this.layers = new Array();
  23325. /**
  23326. * The list of effect layers (highlights/glow) added to the scene
  23327. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23328. * @see http://doc.babylonjs.com/how_to/glow_layer
  23329. */
  23330. this.effectLayers = new Array();
  23331. // Skeletons
  23332. this._skeletonsEnabled = true;
  23333. /**
  23334. * The list of skeletons added to the scene
  23335. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23336. */
  23337. this.skeletons = new Array();
  23338. // Morph targets
  23339. /**
  23340. * The list of morph target managers added to the scene
  23341. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23342. */
  23343. this.morphTargetManagers = new Array();
  23344. // Lens flares
  23345. /**
  23346. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23347. */
  23348. this.lensFlaresEnabled = true;
  23349. /**
  23350. * The list of lens flare system added to the scene
  23351. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23352. */
  23353. this.lensFlareSystems = new Array();
  23354. // Collisions
  23355. /**
  23356. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23357. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23358. */
  23359. this.collisionsEnabled = true;
  23360. /**
  23361. * Defines the gravity applied to this scene (used only for collisions)
  23362. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23363. */
  23364. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23365. // Postprocesses
  23366. /**
  23367. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23368. */
  23369. this.postProcessesEnabled = true;
  23370. /**
  23371. * The list of postprocesses added to the scene
  23372. */
  23373. this.postProcesses = new Array();
  23374. // Customs render targets
  23375. /**
  23376. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23377. */
  23378. this.renderTargetsEnabled = true;
  23379. /**
  23380. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23381. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23382. */
  23383. this.dumpNextRenderTargets = false;
  23384. /**
  23385. * The list of user defined render targets added to the scene
  23386. */
  23387. this.customRenderTargets = new Array();
  23388. /**
  23389. * Gets the list of meshes imported to the scene through SceneLoader
  23390. */
  23391. this.importedMeshesFiles = new Array();
  23392. // Probes
  23393. /**
  23394. * Gets or sets a boolean indicating if probes are enabled on this scene
  23395. */
  23396. this.probesEnabled = true;
  23397. /**
  23398. * The list of reflection probes added to the scene
  23399. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23400. */
  23401. this.reflectionProbes = new Array();
  23402. /** @ignore */
  23403. this._actionManagers = new Array();
  23404. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23405. // Procedural textures
  23406. /**
  23407. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23408. */
  23409. this.proceduralTexturesEnabled = true;
  23410. /**
  23411. * The list of procedural textures added to the scene
  23412. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23413. */
  23414. this.proceduralTextures = new Array();
  23415. /**
  23416. * The list of sound tracks added to the scene
  23417. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23418. */
  23419. this.soundTracks = new Array();
  23420. this._audioEnabled = true;
  23421. this._headphone = false;
  23422. // Performance counters
  23423. this._totalVertices = new BABYLON.PerfCounter();
  23424. /** @ignore */
  23425. this._activeIndices = new BABYLON.PerfCounter();
  23426. /** @ignore */
  23427. this._activeParticles = new BABYLON.PerfCounter();
  23428. /** @ignore */
  23429. this._activeBones = new BABYLON.PerfCounter();
  23430. this._animationTime = 0;
  23431. /**
  23432. * Gets or sets a general scale for animation speed
  23433. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23434. */
  23435. this.animationTimeScale = 1;
  23436. this._renderId = 0;
  23437. this._executeWhenReadyTimeoutId = -1;
  23438. this._intermediateRendering = false;
  23439. this._viewUpdateFlag = -1;
  23440. this._projectionUpdateFlag = -1;
  23441. this._alternateViewUpdateFlag = -1;
  23442. this._alternateProjectionUpdateFlag = -1;
  23443. /** @ignore */
  23444. this._toBeDisposed = new BABYLON.SmartArray(256);
  23445. this._activeRequests = new Array();
  23446. this._pendingData = new Array();
  23447. this._isDisposed = false;
  23448. /**
  23449. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23450. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23451. */
  23452. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23453. this._activeMeshes = new BABYLON.SmartArray(256);
  23454. this._processedMaterials = new BABYLON.SmartArray(256);
  23455. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23456. /** @ignore */
  23457. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23458. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23459. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23460. /** @ignore */
  23461. this._activeAnimatables = new Array();
  23462. this._transformMatrix = BABYLON.Matrix.Zero();
  23463. this._useAlternateCameraConfiguration = false;
  23464. this._alternateRendering = false;
  23465. /**
  23466. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23467. * This is useful if there are more lights that the maximum simulteanous authorized
  23468. */
  23469. this.requireLightSorting = false;
  23470. this._depthRenderer = {};
  23471. this._activeMeshesFrozen = false;
  23472. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23473. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23474. this._engine.scenes.push(this);
  23475. this._uid = null;
  23476. this._renderingManager = new BABYLON.RenderingManager(this);
  23477. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23478. if (BABYLON.OutlineRenderer) {
  23479. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23480. }
  23481. if (BABYLON.Tools.IsWindowObjectExist()) {
  23482. this.attachControl();
  23483. }
  23484. //simplification queue
  23485. if (BABYLON.SimplificationQueue) {
  23486. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23487. }
  23488. //collision coordinator initialization. For now legacy per default.
  23489. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23490. // Uniform Buffer
  23491. this._createUbo();
  23492. // Default Image processing definition.
  23493. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23494. }
  23495. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23496. /** The fog is deactivated */
  23497. get: function () {
  23498. return Scene._FOGMODE_NONE;
  23499. },
  23500. enumerable: true,
  23501. configurable: true
  23502. });
  23503. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23504. /** The fog density is following an exponential function */
  23505. get: function () {
  23506. return Scene._FOGMODE_EXP;
  23507. },
  23508. enumerable: true,
  23509. configurable: true
  23510. });
  23511. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23512. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23513. get: function () {
  23514. return Scene._FOGMODE_EXP2;
  23515. },
  23516. enumerable: true,
  23517. configurable: true
  23518. });
  23519. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23520. /** The fog density is following a linear function. */
  23521. get: function () {
  23522. return Scene._FOGMODE_LINEAR;
  23523. },
  23524. enumerable: true,
  23525. configurable: true
  23526. });
  23527. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23528. /**
  23529. * Texture used in all pbr material as the reflection texture.
  23530. * As in the majority of the scene they are the same (exception for multi room and so on),
  23531. * this is easier to reference from here than from all the materials.
  23532. */
  23533. get: function () {
  23534. return this._environmentTexture;
  23535. },
  23536. /**
  23537. * Texture used in all pbr material as the reflection texture.
  23538. * As in the majority of the scene they are the same (exception for multi room and so on),
  23539. * this is easier to set here than in all the materials.
  23540. */
  23541. set: function (value) {
  23542. if (this._environmentTexture === value) {
  23543. return;
  23544. }
  23545. this._environmentTexture = value;
  23546. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23547. },
  23548. enumerable: true,
  23549. configurable: true
  23550. });
  23551. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23552. /**
  23553. * Default image processing configuration used either in the rendering
  23554. * Forward main pass or through the imageProcessingPostProcess if present.
  23555. * As in the majority of the scene they are the same (exception for multi camera),
  23556. * this is easier to reference from here than from all the materials and post process.
  23557. *
  23558. * No setter as we it is a shared configuration, you can set the values instead.
  23559. */
  23560. get: function () {
  23561. return this._imageProcessingConfiguration;
  23562. },
  23563. enumerable: true,
  23564. configurable: true
  23565. });
  23566. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23567. get: function () {
  23568. return this._forceWireframe;
  23569. },
  23570. /**
  23571. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23572. */
  23573. set: function (value) {
  23574. if (this._forceWireframe === value) {
  23575. return;
  23576. }
  23577. this._forceWireframe = value;
  23578. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23579. },
  23580. enumerable: true,
  23581. configurable: true
  23582. });
  23583. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23584. get: function () {
  23585. return this._forcePointsCloud;
  23586. },
  23587. /**
  23588. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23589. */
  23590. set: function (value) {
  23591. if (this._forcePointsCloud === value) {
  23592. return;
  23593. }
  23594. this._forcePointsCloud = value;
  23595. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23596. },
  23597. enumerable: true,
  23598. configurable: true
  23599. });
  23600. Object.defineProperty(Scene.prototype, "onDispose", {
  23601. /** Sets a function to be executed when this scene is disposed. */
  23602. set: function (callback) {
  23603. if (this._onDisposeObserver) {
  23604. this.onDisposeObservable.remove(this._onDisposeObserver);
  23605. }
  23606. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23607. },
  23608. enumerable: true,
  23609. configurable: true
  23610. });
  23611. Object.defineProperty(Scene.prototype, "beforeRender", {
  23612. /** Sets a function to be executed before rendering this scene */
  23613. set: function (callback) {
  23614. if (this._onBeforeRenderObserver) {
  23615. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23616. }
  23617. if (callback) {
  23618. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23619. }
  23620. },
  23621. enumerable: true,
  23622. configurable: true
  23623. });
  23624. Object.defineProperty(Scene.prototype, "afterRender", {
  23625. /** Sets a function to be executed after rendering this scene */
  23626. set: function (callback) {
  23627. if (this._onAfterRenderObserver) {
  23628. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23629. }
  23630. if (callback) {
  23631. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23632. }
  23633. },
  23634. enumerable: true,
  23635. configurable: true
  23636. });
  23637. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23638. /** Sets a function to be executed before rendering a camera*/
  23639. set: function (callback) {
  23640. if (this._onBeforeCameraRenderObserver) {
  23641. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23642. }
  23643. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23644. },
  23645. enumerable: true,
  23646. configurable: true
  23647. });
  23648. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23649. /** Sets a function to be executed after rendering a camera*/
  23650. set: function (callback) {
  23651. if (this._onAfterCameraRenderObserver) {
  23652. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23653. }
  23654. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23655. },
  23656. enumerable: true,
  23657. configurable: true
  23658. });
  23659. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23660. /**
  23661. * Gets the gamepad manager associated with the scene
  23662. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23663. */
  23664. get: function () {
  23665. if (!this._gamepadManager) {
  23666. this._gamepadManager = new BABYLON.GamepadManager(this);
  23667. }
  23668. return this._gamepadManager;
  23669. },
  23670. enumerable: true,
  23671. configurable: true
  23672. });
  23673. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23674. /**
  23675. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23676. */
  23677. get: function () {
  23678. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23679. },
  23680. enumerable: true,
  23681. configurable: true
  23682. });
  23683. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23684. get: function () {
  23685. return this._useRightHandedSystem;
  23686. },
  23687. /**
  23688. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23689. */
  23690. set: function (value) {
  23691. if (this._useRightHandedSystem === value) {
  23692. return;
  23693. }
  23694. this._useRightHandedSystem = value;
  23695. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23696. },
  23697. enumerable: true,
  23698. configurable: true
  23699. });
  23700. /**
  23701. * Sets the step Id used by deterministic lock step
  23702. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23703. * @param newStepId defines the step Id
  23704. */
  23705. Scene.prototype.setStepId = function (newStepId) {
  23706. this._currentStepId = newStepId;
  23707. };
  23708. ;
  23709. /**
  23710. * Gets the step Id used by deterministic lock step
  23711. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23712. * @returns the step Id
  23713. */
  23714. Scene.prototype.getStepId = function () {
  23715. return this._currentStepId;
  23716. };
  23717. ;
  23718. /**
  23719. * Gets the internal step used by deterministic lock step
  23720. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23721. * @returns the internal step
  23722. */
  23723. Scene.prototype.getInternalStep = function () {
  23724. return this._currentInternalStep;
  23725. };
  23726. ;
  23727. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23728. get: function () {
  23729. return this._fogEnabled;
  23730. },
  23731. /**
  23732. * Gets or sets a boolean indicating if fog is enabled on this scene
  23733. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23734. */
  23735. set: function (value) {
  23736. if (this._fogEnabled === value) {
  23737. return;
  23738. }
  23739. this._fogEnabled = value;
  23740. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23741. },
  23742. enumerable: true,
  23743. configurable: true
  23744. });
  23745. Object.defineProperty(Scene.prototype, "fogMode", {
  23746. get: function () {
  23747. return this._fogMode;
  23748. },
  23749. /**
  23750. * Gets or sets the fog mode to use
  23751. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23752. */
  23753. set: function (value) {
  23754. if (this._fogMode === value) {
  23755. return;
  23756. }
  23757. this._fogMode = value;
  23758. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23759. },
  23760. enumerable: true,
  23761. configurable: true
  23762. });
  23763. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23764. get: function () {
  23765. return this._shadowsEnabled;
  23766. },
  23767. /**
  23768. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23769. */
  23770. set: function (value) {
  23771. if (this._shadowsEnabled === value) {
  23772. return;
  23773. }
  23774. this._shadowsEnabled = value;
  23775. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23776. },
  23777. enumerable: true,
  23778. configurable: true
  23779. });
  23780. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  23781. get: function () {
  23782. return this._lightsEnabled;
  23783. },
  23784. /**
  23785. * Gets or sets a boolean indicating if lights are enabled on this scene
  23786. */
  23787. set: function (value) {
  23788. if (this._lightsEnabled === value) {
  23789. return;
  23790. }
  23791. this._lightsEnabled = value;
  23792. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23793. },
  23794. enumerable: true,
  23795. configurable: true
  23796. });
  23797. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  23798. /** The default material used on meshes when no material is affected */
  23799. get: function () {
  23800. if (!this._defaultMaterial) {
  23801. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  23802. }
  23803. return this._defaultMaterial;
  23804. },
  23805. /** The default material used on meshes when no material is affected */
  23806. set: function (value) {
  23807. this._defaultMaterial = value;
  23808. },
  23809. enumerable: true,
  23810. configurable: true
  23811. });
  23812. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  23813. get: function () {
  23814. return this._texturesEnabled;
  23815. },
  23816. /**
  23817. * Gets or sets a boolean indicating if textures are enabled on this scene
  23818. */
  23819. set: function (value) {
  23820. if (this._texturesEnabled === value) {
  23821. return;
  23822. }
  23823. this._texturesEnabled = value;
  23824. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23825. },
  23826. enumerable: true,
  23827. configurable: true
  23828. });
  23829. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  23830. get: function () {
  23831. return this._skeletonsEnabled;
  23832. },
  23833. /**
  23834. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  23835. */
  23836. set: function (value) {
  23837. if (this._skeletonsEnabled === value) {
  23838. return;
  23839. }
  23840. this._skeletonsEnabled = value;
  23841. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  23842. },
  23843. enumerable: true,
  23844. configurable: true
  23845. });
  23846. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  23847. /**
  23848. * Gets the postprocess render pipeline manager
  23849. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  23850. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  23851. */
  23852. get: function () {
  23853. if (!this._postProcessRenderPipelineManager) {
  23854. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  23855. }
  23856. return this._postProcessRenderPipelineManager;
  23857. },
  23858. enumerable: true,
  23859. configurable: true
  23860. });
  23861. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  23862. /**
  23863. * Gets the main soundtrack associated with the scene
  23864. */
  23865. get: function () {
  23866. if (!this._mainSoundTrack) {
  23867. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  23868. }
  23869. return this._mainSoundTrack;
  23870. },
  23871. enumerable: true,
  23872. configurable: true
  23873. });
  23874. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  23875. /** @ignore */
  23876. get: function () {
  23877. return this._alternateRendering;
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  23883. /**
  23884. * Gets the list of frustum planes (built from the active camera)
  23885. */
  23886. get: function () {
  23887. return this._frustumPlanes;
  23888. },
  23889. enumerable: true,
  23890. configurable: true
  23891. });
  23892. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  23893. /**
  23894. * Gets the current geometry buffer associated to the scene.
  23895. */
  23896. get: function () {
  23897. return this._geometryBufferRenderer;
  23898. },
  23899. /**
  23900. * Sets the current geometry buffer for the scene.
  23901. */
  23902. set: function (geometryBufferRenderer) {
  23903. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  23904. this._geometryBufferRenderer = geometryBufferRenderer;
  23905. }
  23906. },
  23907. enumerable: true,
  23908. configurable: true
  23909. });
  23910. Object.defineProperty(Scene.prototype, "debugLayer", {
  23911. /**
  23912. * Gets the debug layer associated with the scene
  23913. * @see http://doc.babylonjs.com/features/playground_debuglayer
  23914. */
  23915. get: function () {
  23916. if (!this._debugLayer) {
  23917. this._debugLayer = new BABYLON.DebugLayer(this);
  23918. }
  23919. return this._debugLayer;
  23920. },
  23921. enumerable: true,
  23922. configurable: true
  23923. });
  23924. Object.defineProperty(Scene.prototype, "workerCollisions", {
  23925. /**
  23926. * Gets a boolean indicating if collisions are processed on a web worker
  23927. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  23928. */
  23929. get: function () {
  23930. return this._workerCollisions;
  23931. },
  23932. set: function (enabled) {
  23933. if (!BABYLON.CollisionCoordinatorLegacy) {
  23934. return;
  23935. }
  23936. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  23937. this._workerCollisions = enabled;
  23938. if (this.collisionCoordinator) {
  23939. this.collisionCoordinator.destroy();
  23940. }
  23941. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  23942. this.collisionCoordinator.init(this);
  23943. },
  23944. enumerable: true,
  23945. configurable: true
  23946. });
  23947. Object.defineProperty(Scene.prototype, "selectionOctree", {
  23948. /**
  23949. * Gets the octree used to boost mesh selection (picking)
  23950. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  23951. */
  23952. get: function () {
  23953. return this._selectionOctree;
  23954. },
  23955. enumerable: true,
  23956. configurable: true
  23957. });
  23958. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  23959. /**
  23960. * Gets the mesh that is currently under the pointer
  23961. */
  23962. get: function () {
  23963. return this._pointerOverMesh;
  23964. },
  23965. enumerable: true,
  23966. configurable: true
  23967. });
  23968. Object.defineProperty(Scene.prototype, "pointerX", {
  23969. /**
  23970. * Gets the current on-screen X position of the pointer
  23971. */
  23972. get: function () {
  23973. return this._pointerX;
  23974. },
  23975. enumerable: true,
  23976. configurable: true
  23977. });
  23978. Object.defineProperty(Scene.prototype, "pointerY", {
  23979. /**
  23980. * Gets the current on-screen Y position of the pointer
  23981. */
  23982. get: function () {
  23983. return this._pointerY;
  23984. },
  23985. enumerable: true,
  23986. configurable: true
  23987. });
  23988. /**
  23989. * Gets the cached material (ie. the latest rendered one)
  23990. * @returns the cached material
  23991. */
  23992. Scene.prototype.getCachedMaterial = function () {
  23993. return this._cachedMaterial;
  23994. };
  23995. /**
  23996. * Gets the cached effect (ie. the latest rendered one)
  23997. * @returns the cached effect
  23998. */
  23999. Scene.prototype.getCachedEffect = function () {
  24000. return this._cachedEffect;
  24001. };
  24002. /**
  24003. * Gets the cached visibility state (ie. the latest rendered one)
  24004. * @returns the cached visibility state
  24005. */
  24006. Scene.prototype.getCachedVisibility = function () {
  24007. return this._cachedVisibility;
  24008. };
  24009. /**
  24010. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24011. * @param material defines the current material
  24012. * @param effect defines the current effect
  24013. * @param visibility defines the current visibility state
  24014. * @returns true if one parameter is not cached
  24015. */
  24016. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24017. if (visibility === void 0) { visibility = 1; }
  24018. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24019. };
  24020. /**
  24021. * Gets the bounding box renderer associated with the scene
  24022. * @returns a BoundingBoxRenderer
  24023. */
  24024. Scene.prototype.getBoundingBoxRenderer = function () {
  24025. if (!this._boundingBoxRenderer) {
  24026. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24027. }
  24028. return this._boundingBoxRenderer;
  24029. };
  24030. /**
  24031. * Gets the outline renderer associated with the scene
  24032. * @returns a OutlineRenderer
  24033. */
  24034. Scene.prototype.getOutlineRenderer = function () {
  24035. return this._outlineRenderer;
  24036. };
  24037. /**
  24038. * Gets the engine associated with the scene
  24039. * @returns an Engine
  24040. */
  24041. Scene.prototype.getEngine = function () {
  24042. return this._engine;
  24043. };
  24044. /**
  24045. * Gets the total number of vertices rendered per frame
  24046. * @returns the total number of vertices rendered per frame
  24047. */
  24048. Scene.prototype.getTotalVertices = function () {
  24049. return this._totalVertices.current;
  24050. };
  24051. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24052. /**
  24053. * Gets the performance counter for total vertices
  24054. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24055. */
  24056. get: function () {
  24057. return this._totalVertices;
  24058. },
  24059. enumerable: true,
  24060. configurable: true
  24061. });
  24062. /**
  24063. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24064. * @returns the total number of active indices rendered per frame
  24065. */
  24066. Scene.prototype.getActiveIndices = function () {
  24067. return this._activeIndices.current;
  24068. };
  24069. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24070. /**
  24071. * Gets the performance counter for active indices
  24072. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24073. */
  24074. get: function () {
  24075. return this._activeIndices;
  24076. },
  24077. enumerable: true,
  24078. configurable: true
  24079. });
  24080. /**
  24081. * Gets the total number of active particles rendered per frame
  24082. * @returns the total number of active particles rendered per frame
  24083. */
  24084. Scene.prototype.getActiveParticles = function () {
  24085. return this._activeParticles.current;
  24086. };
  24087. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24088. /**
  24089. * Gets the performance counter for active particles
  24090. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24091. */
  24092. get: function () {
  24093. return this._activeParticles;
  24094. },
  24095. enumerable: true,
  24096. configurable: true
  24097. });
  24098. /**
  24099. * Gets the total number of active bones rendered per frame
  24100. * @returns the total number of active bones rendered per frame
  24101. */
  24102. Scene.prototype.getActiveBones = function () {
  24103. return this._activeBones.current;
  24104. };
  24105. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24106. /**
  24107. * Gets the performance counter for active bones
  24108. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24109. */
  24110. get: function () {
  24111. return this._activeBones;
  24112. },
  24113. enumerable: true,
  24114. configurable: true
  24115. });
  24116. /** @ignore */
  24117. Scene.prototype.getInterFramePerfCounter = function () {
  24118. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24119. return 0;
  24120. };
  24121. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24122. /** @ignore */
  24123. get: function () {
  24124. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24125. return null;
  24126. },
  24127. enumerable: true,
  24128. configurable: true
  24129. });
  24130. /** @ignore */
  24131. Scene.prototype.getLastFrameDuration = function () {
  24132. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24133. return 0;
  24134. };
  24135. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24136. /** @ignore */
  24137. get: function () {
  24138. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24139. return null;
  24140. },
  24141. enumerable: true,
  24142. configurable: true
  24143. });
  24144. /** @ignore */
  24145. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24146. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24147. return 0;
  24148. };
  24149. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24150. /** @ignore */
  24151. get: function () {
  24152. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24153. return null;
  24154. },
  24155. enumerable: true,
  24156. configurable: true
  24157. });
  24158. /**
  24159. * Gets the array of active meshes
  24160. * @returns an array of AbstractMesh
  24161. */
  24162. Scene.prototype.getActiveMeshes = function () {
  24163. return this._activeMeshes;
  24164. };
  24165. /** @ignore */
  24166. Scene.prototype.getRenderTargetsDuration = function () {
  24167. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24168. return 0;
  24169. };
  24170. /** @ignore */
  24171. Scene.prototype.getRenderDuration = function () {
  24172. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24173. return 0;
  24174. };
  24175. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24176. /** @ignore */
  24177. get: function () {
  24178. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24179. return null;
  24180. },
  24181. enumerable: true,
  24182. configurable: true
  24183. });
  24184. /** @ignore */
  24185. Scene.prototype.getParticlesDuration = function () {
  24186. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24187. return 0;
  24188. };
  24189. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24190. /** @ignore */
  24191. get: function () {
  24192. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24193. return null;
  24194. },
  24195. enumerable: true,
  24196. configurable: true
  24197. });
  24198. /** @ignore */
  24199. Scene.prototype.getSpritesDuration = function () {
  24200. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24201. return 0;
  24202. };
  24203. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24204. /** @ignore */
  24205. get: function () {
  24206. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24207. return null;
  24208. },
  24209. enumerable: true,
  24210. configurable: true
  24211. });
  24212. /**
  24213. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24214. * @returns a number
  24215. */
  24216. Scene.prototype.getAnimationRatio = function () {
  24217. return this._animationRatio;
  24218. };
  24219. /**
  24220. * Gets an unique Id for the current frame
  24221. * @returns a number
  24222. */
  24223. Scene.prototype.getRenderId = function () {
  24224. return this._renderId;
  24225. };
  24226. /** Call this function if you want to manually increment the render Id*/
  24227. Scene.prototype.incrementRenderId = function () {
  24228. this._renderId++;
  24229. };
  24230. Scene.prototype._updatePointerPosition = function (evt) {
  24231. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24232. if (!canvasRect) {
  24233. return;
  24234. }
  24235. this._pointerX = evt.clientX - canvasRect.left;
  24236. this._pointerY = evt.clientY - canvasRect.top;
  24237. this._unTranslatedPointerX = this._pointerX;
  24238. this._unTranslatedPointerY = this._pointerY;
  24239. };
  24240. Scene.prototype._createUbo = function () {
  24241. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24242. this._sceneUbo.addUniform("viewProjection", 16);
  24243. this._sceneUbo.addUniform("view", 16);
  24244. };
  24245. Scene.prototype._createAlternateUbo = function () {
  24246. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24247. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24248. this._alternateSceneUbo.addUniform("view", 16);
  24249. };
  24250. // Pointers handling
  24251. /**
  24252. * Use this method to simulate a pointer move on a mesh
  24253. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24254. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24255. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24256. * @returns the current scene
  24257. */
  24258. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24259. var evt = new PointerEvent("pointermove", pointerEventInit);
  24260. return this._processPointerMove(pickResult, evt);
  24261. };
  24262. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24263. var canvas = this._engine.getRenderingCanvas();
  24264. if (!canvas) {
  24265. return this;
  24266. }
  24267. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24268. this.setPointerOverSprite(null);
  24269. this.setPointerOverMesh(pickResult.pickedMesh);
  24270. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24271. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24272. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24273. }
  24274. else {
  24275. canvas.style.cursor = this.hoverCursor;
  24276. }
  24277. }
  24278. else {
  24279. canvas.style.cursor = this.defaultCursor;
  24280. }
  24281. }
  24282. else {
  24283. this.setPointerOverMesh(null);
  24284. // Sprites
  24285. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24286. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24287. this.setPointerOverSprite(pickResult.pickedSprite);
  24288. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24289. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24290. }
  24291. else {
  24292. canvas.style.cursor = this.hoverCursor;
  24293. }
  24294. }
  24295. else {
  24296. this.setPointerOverSprite(null);
  24297. // Restore pointer
  24298. canvas.style.cursor = this.defaultCursor;
  24299. }
  24300. }
  24301. if (pickResult) {
  24302. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24303. if (this.onPointerMove) {
  24304. this.onPointerMove(evt, pickResult, type);
  24305. }
  24306. if (this.onPointerObservable.hasObservers()) {
  24307. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24308. this.onPointerObservable.notifyObservers(pi, type);
  24309. }
  24310. }
  24311. return this;
  24312. };
  24313. /**
  24314. * Use this method to simulate a pointer down on a mesh
  24315. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24316. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24317. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24318. * @returns the current scene
  24319. */
  24320. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24321. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24322. return this._processPointerDown(pickResult, evt);
  24323. };
  24324. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24325. var _this = this;
  24326. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24327. this._pickedDownMesh = pickResult.pickedMesh;
  24328. var actionManager = pickResult.pickedMesh.actionManager;
  24329. if (actionManager) {
  24330. if (actionManager.hasPickTriggers) {
  24331. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24332. switch (evt.button) {
  24333. case 0:
  24334. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24335. break;
  24336. case 1:
  24337. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24338. break;
  24339. case 2:
  24340. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24341. break;
  24342. }
  24343. }
  24344. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24345. window.setTimeout(function () {
  24346. 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);
  24347. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24348. if (_this._totalPointersPressed !== 0 &&
  24349. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24350. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24351. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24352. _this._startingPointerTime = 0;
  24353. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24354. }
  24355. }
  24356. }, Scene.LongPressDelay);
  24357. }
  24358. }
  24359. }
  24360. if (pickResult) {
  24361. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24362. if (this.onPointerDown) {
  24363. this.onPointerDown(evt, pickResult, type);
  24364. }
  24365. if (this.onPointerObservable.hasObservers()) {
  24366. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24367. this.onPointerObservable.notifyObservers(pi, type);
  24368. }
  24369. }
  24370. return this;
  24371. };
  24372. /**
  24373. * Use this method to simulate a pointer up on a mesh
  24374. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24375. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24376. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24377. * @returns the current scene
  24378. */
  24379. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24380. var evt = new PointerEvent("pointerup", pointerEventInit);
  24381. var clickInfo = new ClickInfo();
  24382. clickInfo.singleClick = true;
  24383. clickInfo.ignore = true;
  24384. return this._processPointerUp(pickResult, evt, clickInfo);
  24385. };
  24386. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24387. if (pickResult && pickResult && pickResult.pickedMesh) {
  24388. this._pickedUpMesh = pickResult.pickedMesh;
  24389. if (this._pickedDownMesh === this._pickedUpMesh) {
  24390. if (this.onPointerPick) {
  24391. this.onPointerPick(evt, pickResult);
  24392. }
  24393. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24394. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24395. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24396. this.onPointerObservable.notifyObservers(pi, type_1);
  24397. }
  24398. }
  24399. if (pickResult.pickedMesh.actionManager) {
  24400. if (clickInfo.ignore) {
  24401. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24402. }
  24403. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24404. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24405. }
  24406. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24407. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24408. }
  24409. }
  24410. }
  24411. if (this._pickedDownMesh &&
  24412. this._pickedDownMesh.actionManager &&
  24413. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24414. this._pickedDownMesh !== this._pickedUpMesh) {
  24415. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24416. }
  24417. var type = BABYLON.PointerEventTypes.POINTERUP;
  24418. if (this.onPointerObservable.hasObservers()) {
  24419. if (!clickInfo.ignore) {
  24420. if (!clickInfo.hasSwiped) {
  24421. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24422. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24423. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24424. this.onPointerObservable.notifyObservers(pi, type_2);
  24425. }
  24426. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24427. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24428. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24429. this.onPointerObservable.notifyObservers(pi, type_3);
  24430. }
  24431. }
  24432. }
  24433. else {
  24434. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24435. this.onPointerObservable.notifyObservers(pi, type);
  24436. }
  24437. }
  24438. if (this.onPointerUp) {
  24439. this.onPointerUp(evt, pickResult, type);
  24440. }
  24441. return this;
  24442. };
  24443. /**
  24444. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24445. * @param attachUp defines if you want to attach events to pointerup
  24446. * @param attachDown defines if you want to attach events to pointerdown
  24447. * @param attachMove defines if you want to attach events to pointermove
  24448. */
  24449. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24450. var _this = this;
  24451. if (attachUp === void 0) { attachUp = true; }
  24452. if (attachDown === void 0) { attachDown = true; }
  24453. if (attachMove === void 0) { attachMove = true; }
  24454. this._initActionManager = function (act, clickInfo) {
  24455. if (!_this._meshPickProceed) {
  24456. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24457. _this._currentPickResult = pickResult;
  24458. if (pickResult) {
  24459. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24460. }
  24461. _this._meshPickProceed = true;
  24462. }
  24463. return act;
  24464. };
  24465. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24466. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24467. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24468. btn !== _this._previousButtonPressed) {
  24469. _this._doubleClickOccured = false;
  24470. clickInfo.singleClick = true;
  24471. clickInfo.ignore = false;
  24472. cb(clickInfo, _this._currentPickResult);
  24473. }
  24474. };
  24475. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24476. var clickInfo = new ClickInfo();
  24477. _this._currentPickResult = null;
  24478. var act = null;
  24479. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24480. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24481. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24482. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24483. act = _this._initActionManager(act, clickInfo);
  24484. if (act)
  24485. checkPicking = act.hasPickTriggers;
  24486. }
  24487. if (checkPicking) {
  24488. var btn = evt.button;
  24489. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24490. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24491. if (!clickInfo.hasSwiped) {
  24492. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24493. if (!checkSingleClickImmediately) {
  24494. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24495. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24496. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24497. act = _this._initActionManager(act, clickInfo);
  24498. if (act)
  24499. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24500. }
  24501. }
  24502. if (checkSingleClickImmediately) {
  24503. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24504. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24505. btn !== _this._previousButtonPressed) {
  24506. clickInfo.singleClick = true;
  24507. cb(clickInfo, _this._currentPickResult);
  24508. }
  24509. }
  24510. else {
  24511. // wait that no double click has been raised during the double click delay
  24512. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24513. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24514. }
  24515. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24516. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24517. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24518. act = _this._initActionManager(act, clickInfo);
  24519. if (act)
  24520. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24521. }
  24522. if (checkDoubleClick) {
  24523. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24524. if (btn === _this._previousButtonPressed &&
  24525. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24526. !_this._doubleClickOccured) {
  24527. // pointer has not moved for 2 clicks, it's a double click
  24528. if (!clickInfo.hasSwiped &&
  24529. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24530. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24531. _this._previousStartingPointerTime = 0;
  24532. _this._doubleClickOccured = true;
  24533. clickInfo.doubleClick = true;
  24534. clickInfo.ignore = false;
  24535. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24536. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24537. }
  24538. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24539. cb(clickInfo, _this._currentPickResult);
  24540. }
  24541. else {
  24542. _this._doubleClickOccured = false;
  24543. _this._previousStartingPointerTime = _this._startingPointerTime;
  24544. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24545. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24546. _this._previousButtonPressed = btn;
  24547. if (Scene.ExclusiveDoubleClickMode) {
  24548. if (_this._previousDelayedSimpleClickTimeout) {
  24549. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24550. }
  24551. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24552. cb(clickInfo, _this._previousPickResult);
  24553. }
  24554. else {
  24555. cb(clickInfo, _this._currentPickResult);
  24556. }
  24557. }
  24558. }
  24559. else {
  24560. _this._doubleClickOccured = false;
  24561. _this._previousStartingPointerTime = _this._startingPointerTime;
  24562. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24563. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24564. _this._previousButtonPressed = btn;
  24565. }
  24566. }
  24567. }
  24568. }
  24569. clickInfo.ignore = true;
  24570. cb(clickInfo, _this._currentPickResult);
  24571. };
  24572. this._spritePredicate = function (sprite) {
  24573. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24574. };
  24575. this._onPointerMove = function (evt) {
  24576. _this._updatePointerPosition(evt);
  24577. // PreObservable support
  24578. if (_this.onPrePointerObservable.hasObservers()) {
  24579. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24580. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24581. _this.onPrePointerObservable.notifyObservers(pi, type);
  24582. if (pi.skipOnPointerObservable) {
  24583. return;
  24584. }
  24585. }
  24586. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24587. return;
  24588. }
  24589. if (!_this.pointerMovePredicate) {
  24590. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24591. }
  24592. // Meshes
  24593. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24594. _this._processPointerMove(pickResult, evt);
  24595. };
  24596. this._onPointerDown = function (evt) {
  24597. _this._totalPointersPressed++;
  24598. _this._pickedDownMesh = null;
  24599. _this._meshPickProceed = false;
  24600. _this._updatePointerPosition(evt);
  24601. if (_this.preventDefaultOnPointerDown && canvas) {
  24602. evt.preventDefault();
  24603. canvas.focus();
  24604. }
  24605. // PreObservable support
  24606. if (_this.onPrePointerObservable.hasObservers()) {
  24607. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24608. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24609. _this.onPrePointerObservable.notifyObservers(pi, type);
  24610. if (pi.skipOnPointerObservable) {
  24611. return;
  24612. }
  24613. }
  24614. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24615. return;
  24616. }
  24617. _this._startingPointerPosition.x = _this._pointerX;
  24618. _this._startingPointerPosition.y = _this._pointerY;
  24619. _this._startingPointerTime = new Date().getTime();
  24620. if (!_this.pointerDownPredicate) {
  24621. _this.pointerDownPredicate = function (mesh) {
  24622. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24623. };
  24624. }
  24625. // Meshes
  24626. _this._pickedDownMesh = null;
  24627. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24628. _this._processPointerDown(pickResult, evt);
  24629. // Sprites
  24630. _this._pickedDownSprite = null;
  24631. if (_this.spriteManagers.length > 0) {
  24632. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24633. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24634. if (pickResult.pickedSprite.actionManager) {
  24635. _this._pickedDownSprite = pickResult.pickedSprite;
  24636. switch (evt.button) {
  24637. case 0:
  24638. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24639. break;
  24640. case 1:
  24641. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24642. break;
  24643. case 2:
  24644. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24645. break;
  24646. }
  24647. if (pickResult.pickedSprite.actionManager) {
  24648. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24649. }
  24650. }
  24651. }
  24652. }
  24653. };
  24654. this._onPointerUp = function (evt) {
  24655. if (_this._totalPointersPressed === 0) {
  24656. return; // So we need to test it the pointer down was pressed before.
  24657. }
  24658. _this._totalPointersPressed--;
  24659. _this._pickedUpMesh = null;
  24660. _this._meshPickProceed = false;
  24661. _this._updatePointerPosition(evt);
  24662. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24663. // PreObservable support
  24664. if (_this.onPrePointerObservable.hasObservers()) {
  24665. if (!clickInfo.ignore) {
  24666. if (!clickInfo.hasSwiped) {
  24667. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24668. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24669. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24670. _this.onPrePointerObservable.notifyObservers(pi, type);
  24671. if (pi.skipOnPointerObservable) {
  24672. return;
  24673. }
  24674. }
  24675. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24676. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24677. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24678. _this.onPrePointerObservable.notifyObservers(pi, type);
  24679. if (pi.skipOnPointerObservable) {
  24680. return;
  24681. }
  24682. }
  24683. }
  24684. }
  24685. else {
  24686. var type = BABYLON.PointerEventTypes.POINTERUP;
  24687. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24688. _this.onPrePointerObservable.notifyObservers(pi, type);
  24689. if (pi.skipOnPointerObservable) {
  24690. return;
  24691. }
  24692. }
  24693. }
  24694. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24695. return;
  24696. }
  24697. if (!_this.pointerUpPredicate) {
  24698. _this.pointerUpPredicate = function (mesh) {
  24699. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24700. };
  24701. }
  24702. // Meshes
  24703. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24704. _this._initActionManager(null, clickInfo);
  24705. }
  24706. if (!pickResult) {
  24707. pickResult = _this._currentPickResult;
  24708. }
  24709. _this._processPointerUp(pickResult, evt, clickInfo);
  24710. // Sprites
  24711. if (_this.spriteManagers.length > 0) {
  24712. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24713. if (spritePickResult) {
  24714. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24715. if (spritePickResult.pickedSprite.actionManager) {
  24716. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24717. if (spritePickResult.pickedSprite.actionManager) {
  24718. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24719. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24720. }
  24721. }
  24722. }
  24723. }
  24724. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24725. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24726. }
  24727. }
  24728. }
  24729. _this._previousPickResult = _this._currentPickResult;
  24730. });
  24731. };
  24732. this._onKeyDown = function (evt) {
  24733. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24734. if (_this.onPreKeyboardObservable.hasObservers()) {
  24735. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24736. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24737. if (pi.skipOnPointerObservable) {
  24738. return;
  24739. }
  24740. }
  24741. if (_this.onKeyboardObservable.hasObservers()) {
  24742. var pi = new BABYLON.KeyboardInfo(type, evt);
  24743. _this.onKeyboardObservable.notifyObservers(pi, type);
  24744. }
  24745. if (_this.actionManager) {
  24746. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24747. }
  24748. };
  24749. this._onKeyUp = function (evt) {
  24750. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24751. if (_this.onPreKeyboardObservable.hasObservers()) {
  24752. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24753. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24754. if (pi.skipOnPointerObservable) {
  24755. return;
  24756. }
  24757. }
  24758. if (_this.onKeyboardObservable.hasObservers()) {
  24759. var pi = new BABYLON.KeyboardInfo(type, evt);
  24760. _this.onKeyboardObservable.notifyObservers(pi, type);
  24761. }
  24762. if (_this.actionManager) {
  24763. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24764. }
  24765. };
  24766. var engine = this.getEngine();
  24767. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24768. if (!canvas) {
  24769. return;
  24770. }
  24771. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24772. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24773. });
  24774. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24775. if (!canvas) {
  24776. return;
  24777. }
  24778. canvas.removeEventListener("keydown", _this._onKeyDown);
  24779. canvas.removeEventListener("keyup", _this._onKeyUp);
  24780. });
  24781. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24782. var canvas = this._engine.getRenderingCanvas();
  24783. if (!canvas) {
  24784. return;
  24785. }
  24786. if (attachMove) {
  24787. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  24788. // Wheel
  24789. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  24790. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  24791. }
  24792. if (attachDown) {
  24793. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  24794. }
  24795. if (attachUp) {
  24796. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  24797. }
  24798. canvas.tabIndex = 1;
  24799. };
  24800. /** Detaches all event handlers*/
  24801. Scene.prototype.detachControl = function () {
  24802. var engine = this.getEngine();
  24803. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24804. var canvas = engine.getRenderingCanvas();
  24805. if (!canvas) {
  24806. return;
  24807. }
  24808. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  24809. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  24810. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  24811. if (this._onCanvasBlurObserver) {
  24812. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  24813. }
  24814. if (this._onCanvasFocusObserver) {
  24815. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  24816. }
  24817. // Wheel
  24818. canvas.removeEventListener('mousewheel', this._onPointerMove);
  24819. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  24820. // Keyboard
  24821. canvas.removeEventListener("keydown", this._onKeyDown);
  24822. canvas.removeEventListener("keyup", this._onKeyUp);
  24823. // Observables
  24824. this.onKeyboardObservable.clear();
  24825. this.onPreKeyboardObservable.clear();
  24826. this.onPointerObservable.clear();
  24827. this.onPrePointerObservable.clear();
  24828. };
  24829. /**
  24830. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  24831. * Delay loaded resources are not taking in account
  24832. * @return true if all required resources are ready
  24833. */
  24834. Scene.prototype.isReady = function () {
  24835. if (this._isDisposed) {
  24836. return false;
  24837. }
  24838. if (this._pendingData.length > 0) {
  24839. return false;
  24840. }
  24841. var index;
  24842. var engine = this.getEngine();
  24843. // Geometries
  24844. for (index = 0; index < this._geometries.length; index++) {
  24845. var geometry = this._geometries[index];
  24846. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24847. return false;
  24848. }
  24849. }
  24850. // Meshes
  24851. for (index = 0; index < this.meshes.length; index++) {
  24852. var mesh = this.meshes[index];
  24853. if (!mesh.isEnabled()) {
  24854. continue;
  24855. }
  24856. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24857. continue;
  24858. }
  24859. if (!mesh.isReady(true)) {
  24860. return false;
  24861. }
  24862. // Effect layers
  24863. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  24864. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  24865. var layer = _a[_i];
  24866. if (!layer.hasMesh(mesh)) {
  24867. continue;
  24868. }
  24869. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24870. var subMesh = _c[_b];
  24871. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  24872. return false;
  24873. }
  24874. }
  24875. }
  24876. }
  24877. // Post-processes
  24878. if (this.activeCameras && this.activeCameras.length > 0) {
  24879. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  24880. var camera = _e[_d];
  24881. if (!camera.isReady(true)) {
  24882. return false;
  24883. }
  24884. }
  24885. }
  24886. else if (this.activeCamera) {
  24887. if (!this.activeCamera.isReady(true)) {
  24888. return false;
  24889. }
  24890. }
  24891. // Particles
  24892. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  24893. var particleSystem = _g[_f];
  24894. if (!particleSystem.isReady()) {
  24895. return false;
  24896. }
  24897. }
  24898. return true;
  24899. };
  24900. /** Resets all cached information relative to material (including effect and visibility) */
  24901. Scene.prototype.resetCachedMaterial = function () {
  24902. this._cachedMaterial = null;
  24903. this._cachedEffect = null;
  24904. this._cachedVisibility = null;
  24905. };
  24906. /**
  24907. * Registers a function to be called before every frame render
  24908. * @param func defines the function to register
  24909. */
  24910. Scene.prototype.registerBeforeRender = function (func) {
  24911. this.onBeforeRenderObservable.add(func);
  24912. };
  24913. /**
  24914. * Unregisters a function called before every frame render
  24915. * @param func defines the function to unregister
  24916. */
  24917. Scene.prototype.unregisterBeforeRender = function (func) {
  24918. this.onBeforeRenderObservable.removeCallback(func);
  24919. };
  24920. /**
  24921. * Registers a function to be called after every frame render
  24922. * @param func defines the function to register
  24923. */
  24924. Scene.prototype.registerAfterRender = function (func) {
  24925. this.onAfterRenderObservable.add(func);
  24926. };
  24927. /**
  24928. * Unregisters a function called after every frame render
  24929. * @param func defines the function to unregister
  24930. */
  24931. Scene.prototype.unregisterAfterRender = function (func) {
  24932. this.onAfterRenderObservable.removeCallback(func);
  24933. };
  24934. Scene.prototype._executeOnceBeforeRender = function (func) {
  24935. var _this = this;
  24936. var execFunc = function () {
  24937. func();
  24938. setTimeout(function () {
  24939. _this.unregisterBeforeRender(execFunc);
  24940. });
  24941. };
  24942. this.registerBeforeRender(execFunc);
  24943. };
  24944. /**
  24945. * The provided function will run before render once and will be disposed afterwards.
  24946. * A timeout delay can be provided so that the function will be executed in N ms.
  24947. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  24948. * @param func The function to be executed.
  24949. * @param timeout optional delay in ms
  24950. */
  24951. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  24952. var _this = this;
  24953. if (timeout !== undefined) {
  24954. setTimeout(function () {
  24955. _this._executeOnceBeforeRender(func);
  24956. }, timeout);
  24957. }
  24958. else {
  24959. this._executeOnceBeforeRender(func);
  24960. }
  24961. };
  24962. /** @ignore */
  24963. Scene.prototype._addPendingData = function (data) {
  24964. this._pendingData.push(data);
  24965. };
  24966. /** @ignore */
  24967. Scene.prototype._removePendingData = function (data) {
  24968. var wasLoading = this.isLoading;
  24969. var index = this._pendingData.indexOf(data);
  24970. if (index !== -1) {
  24971. this._pendingData.splice(index, 1);
  24972. }
  24973. if (wasLoading && !this.isLoading) {
  24974. this.onDataLoadedObservable.notifyObservers(this);
  24975. }
  24976. };
  24977. /**
  24978. * Returns the number of items waiting to be loaded
  24979. * @returns the number of items waiting to be loaded
  24980. */
  24981. Scene.prototype.getWaitingItemsCount = function () {
  24982. return this._pendingData.length;
  24983. };
  24984. Object.defineProperty(Scene.prototype, "isLoading", {
  24985. /**
  24986. * Returns a boolean indicating if the scene is still loading data
  24987. */
  24988. get: function () {
  24989. return this._pendingData.length > 0;
  24990. },
  24991. enumerable: true,
  24992. configurable: true
  24993. });
  24994. /**
  24995. * Registers a function to be executed when the scene is ready
  24996. * @param {Function} func - the function to be executed
  24997. */
  24998. Scene.prototype.executeWhenReady = function (func) {
  24999. var _this = this;
  25000. this.onReadyObservable.add(func);
  25001. if (this._executeWhenReadyTimeoutId !== -1) {
  25002. return;
  25003. }
  25004. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25005. _this._checkIsReady();
  25006. }, 150);
  25007. };
  25008. /**
  25009. * Returns a promise that resolves when the scene is ready
  25010. * @returns A promise that resolves when the scene is ready
  25011. */
  25012. Scene.prototype.whenReadyAsync = function () {
  25013. var _this = this;
  25014. return new Promise(function (resolve) {
  25015. _this.executeWhenReady(function () {
  25016. resolve();
  25017. });
  25018. });
  25019. };
  25020. /** @ignore */
  25021. Scene.prototype._checkIsReady = function () {
  25022. var _this = this;
  25023. if (this.isReady()) {
  25024. this.onReadyObservable.notifyObservers(this);
  25025. this.onReadyObservable.clear();
  25026. this._executeWhenReadyTimeoutId = -1;
  25027. return;
  25028. }
  25029. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25030. _this._checkIsReady();
  25031. }, 150);
  25032. };
  25033. // Animations
  25034. /**
  25035. * Will start the animation sequence of a given target
  25036. * @param target defines the target
  25037. * @param from defines from which frame should animation start
  25038. * @param to defines until which frame should animation run.
  25039. * @param weight defines the weight to apply to the animation (1.0 by default)
  25040. * @param loop defines if the animation loops
  25041. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25042. * @param onAnimationEnd defines the function to be executed when the animation ends
  25043. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25044. * @returns the animatable object created for this animation
  25045. */
  25046. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25047. if (weight === void 0) { weight = 1.0; }
  25048. if (speedRatio === void 0) { speedRatio = 1.0; }
  25049. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25050. returnedAnimatable.weight = weight;
  25051. return returnedAnimatable;
  25052. };
  25053. /**
  25054. * Will start the animation sequence of a given target
  25055. * @param target defines the target
  25056. * @param from defines from which frame should animation start
  25057. * @param to defines until which frame should animation run.
  25058. * @param loop defines if the animation loops
  25059. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25060. * @param onAnimationEnd defines the function to be executed when the animation ends
  25061. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25062. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25063. * @returns the animatable object created for this animation
  25064. */
  25065. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25066. if (speedRatio === void 0) { speedRatio = 1.0; }
  25067. if (stopCurrent === void 0) { stopCurrent = true; }
  25068. if (from > to && speedRatio > 0) {
  25069. speedRatio *= -1;
  25070. }
  25071. if (stopCurrent) {
  25072. this.stopAnimation(target);
  25073. }
  25074. if (!animatable) {
  25075. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25076. }
  25077. // Local animations
  25078. if (target.animations) {
  25079. animatable.appendAnimations(target, target.animations);
  25080. }
  25081. // Children animations
  25082. if (target.getAnimatables) {
  25083. var animatables = target.getAnimatables();
  25084. for (var index = 0; index < animatables.length; index++) {
  25085. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25086. }
  25087. }
  25088. animatable.reset();
  25089. return animatable;
  25090. };
  25091. /**
  25092. * Begin a new animation on a given node
  25093. * @param target defines the target where the animation will take place
  25094. * @param animations defines the list of animations to start
  25095. * @param from defines the initial value
  25096. * @param to defines the final value
  25097. * @param loop defines if you want animation to loop (off by default)
  25098. * @param speedRatio defines the speed ratio to apply to all animations
  25099. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25100. * @returns the list of created animatables
  25101. */
  25102. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25103. if (speedRatio === undefined) {
  25104. speedRatio = 1.0;
  25105. }
  25106. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25107. return animatable;
  25108. };
  25109. /**
  25110. * Begin a new animation on a given node and its hierarchy
  25111. * @param target defines the root node where the animation will take place
  25112. * @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.
  25113. * @param animations defines the list of animations to start
  25114. * @param from defines the initial value
  25115. * @param to defines the final value
  25116. * @param loop defines if you want animation to loop (off by default)
  25117. * @param speedRatio defines the speed ratio to apply to all animations
  25118. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25119. * @returns the list of animatables created for all nodes
  25120. */
  25121. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25122. var children = target.getDescendants(directDescendantsOnly);
  25123. var result = [];
  25124. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25125. var child = children_1[_i];
  25126. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25127. }
  25128. return result;
  25129. };
  25130. /**
  25131. * Gets the animatable associated with a specific target
  25132. * @param target defines the target of the animatable
  25133. * @returns the required animatable if found
  25134. */
  25135. Scene.prototype.getAnimatableByTarget = function (target) {
  25136. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25137. if (this._activeAnimatables[index].target === target) {
  25138. return this._activeAnimatables[index];
  25139. }
  25140. }
  25141. return null;
  25142. };
  25143. /**
  25144. * Gets all animatables associated with a given target
  25145. * @param target defines the target to look animatables for
  25146. * @returns an array of Animatables
  25147. */
  25148. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25149. var result = [];
  25150. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25151. if (this._activeAnimatables[index].target === target) {
  25152. result.push(this._activeAnimatables[index]);
  25153. }
  25154. }
  25155. return result;
  25156. };
  25157. Object.defineProperty(Scene.prototype, "animatables", {
  25158. /**
  25159. * Gets all animatable attached to the scene
  25160. */
  25161. get: function () {
  25162. return this._activeAnimatables;
  25163. },
  25164. enumerable: true,
  25165. configurable: true
  25166. });
  25167. /**
  25168. * Will stop the animation of the given target
  25169. * @param target - the target
  25170. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25171. */
  25172. Scene.prototype.stopAnimation = function (target, animationName) {
  25173. var animatables = this.getAllAnimatablesByTarget(target);
  25174. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25175. var animatable = animatables_1[_i];
  25176. animatable.stop(animationName);
  25177. }
  25178. };
  25179. /**
  25180. * Stops and removes all animations that have been applied to the scene
  25181. */
  25182. Scene.prototype.stopAllAnimations = function () {
  25183. if (this._activeAnimatables) {
  25184. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25185. this._activeAnimatables[i].stop();
  25186. }
  25187. this._activeAnimatables = [];
  25188. }
  25189. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25190. var group = _a[_i];
  25191. group.stop();
  25192. }
  25193. };
  25194. Scene.prototype._animate = function () {
  25195. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25196. return;
  25197. }
  25198. // Getting time
  25199. var now = BABYLON.Tools.Now;
  25200. if (!this._animationTimeLast) {
  25201. if (this._pendingData.length > 0) {
  25202. return;
  25203. }
  25204. this._animationTimeLast = now;
  25205. }
  25206. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25207. this._animationTime += deltaTime;
  25208. this._animationTimeLast = now;
  25209. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25210. this._activeAnimatables[index]._animate(this._animationTime);
  25211. }
  25212. // Late animation bindings
  25213. this._processLateAnimationBindings();
  25214. };
  25215. /** @ignore */
  25216. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25217. var target = runtimeAnimation.target;
  25218. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25219. if (!target._lateAnimationHolders) {
  25220. target._lateAnimationHolders = {};
  25221. }
  25222. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25223. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25224. totalWeight: 0,
  25225. animations: []
  25226. };
  25227. }
  25228. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25229. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25230. };
  25231. Scene.prototype._processLateAnimationBindings = function () {
  25232. if (!this._registeredForLateAnimationBindings.length) {
  25233. return;
  25234. }
  25235. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25236. var target = this._registeredForLateAnimationBindings.data[index];
  25237. for (var path in target._lateAnimationHolders) {
  25238. var holder = target._lateAnimationHolders[path];
  25239. var originalValue = holder.animations[0].originalValue;
  25240. // Sanity check
  25241. if (!originalValue.scaleAndAddToRef) {
  25242. continue;
  25243. }
  25244. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25245. var normalizer = 1.0;
  25246. var finalValue = void 0;
  25247. if (holder.totalWeight < 1.0) {
  25248. // We need to mix the original value in
  25249. if (matrixDecomposeMode) {
  25250. finalValue = originalValue.clone();
  25251. }
  25252. else {
  25253. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25254. }
  25255. }
  25256. else {
  25257. // We need to normalize the weights
  25258. normalizer = holder.totalWeight;
  25259. }
  25260. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25261. var runtimeAnimation = holder.animations[animIndex];
  25262. var scale = runtimeAnimation.weight / normalizer;
  25263. if (finalValue) {
  25264. if (matrixDecomposeMode) {
  25265. BABYLON.Matrix.DecomposeLerpToRef(finalValue, runtimeAnimation.currentValue, scale, finalValue);
  25266. }
  25267. else {
  25268. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25269. }
  25270. }
  25271. else {
  25272. if (scale !== 1) {
  25273. if (matrixDecomposeMode) {
  25274. finalValue = runtimeAnimation.currentValue.clone();
  25275. }
  25276. else {
  25277. finalValue = runtimeAnimation.currentValue.scale(scale);
  25278. }
  25279. }
  25280. else {
  25281. finalValue = runtimeAnimation.currentValue;
  25282. }
  25283. }
  25284. }
  25285. runtimeAnimation.target[path] = finalValue;
  25286. }
  25287. target._lateAnimationHolders = {};
  25288. }
  25289. this._registeredForLateAnimationBindings.reset();
  25290. };
  25291. // Matrix
  25292. /** @ignore */
  25293. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25294. this._useAlternateCameraConfiguration = active;
  25295. };
  25296. /**
  25297. * Gets the current view matrix
  25298. * @returns a Matrix
  25299. */
  25300. Scene.prototype.getViewMatrix = function () {
  25301. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25302. };
  25303. /**
  25304. * Gets the current projection matrix
  25305. * @returns a Matrix
  25306. */
  25307. Scene.prototype.getProjectionMatrix = function () {
  25308. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25309. };
  25310. /**
  25311. * Gets the current transform matrix
  25312. * @returns a Matrix made of View * Projection
  25313. */
  25314. Scene.prototype.getTransformMatrix = function () {
  25315. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25316. };
  25317. /**
  25318. * Sets the current transform matrix
  25319. * @param view defines the View matrix to use
  25320. * @param projection defines the Projection matrix to use
  25321. */
  25322. Scene.prototype.setTransformMatrix = function (view, projection) {
  25323. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25324. return;
  25325. }
  25326. this._viewUpdateFlag = view.updateFlag;
  25327. this._projectionUpdateFlag = projection.updateFlag;
  25328. this._viewMatrix = view;
  25329. this._projectionMatrix = projection;
  25330. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25331. // Update frustum
  25332. if (!this._frustumPlanes) {
  25333. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25334. }
  25335. else {
  25336. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25337. }
  25338. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25339. var otherCamera = this.activeCamera._alternateCamera;
  25340. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25341. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25342. }
  25343. if (this._sceneUbo.useUbo) {
  25344. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25345. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25346. this._sceneUbo.update();
  25347. }
  25348. };
  25349. /** @ignore */
  25350. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25351. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25352. return;
  25353. }
  25354. this._alternateViewUpdateFlag = view.updateFlag;
  25355. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25356. this._alternateViewMatrix = view;
  25357. this._alternateProjectionMatrix = projection;
  25358. if (!this._alternateTransformMatrix) {
  25359. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25360. }
  25361. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25362. if (!this._alternateSceneUbo) {
  25363. this._createAlternateUbo();
  25364. }
  25365. if (this._alternateSceneUbo.useUbo) {
  25366. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25367. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25368. this._alternateSceneUbo.update();
  25369. }
  25370. };
  25371. /**
  25372. * Gets the uniform buffer used to store scene data
  25373. * @returns a UniformBuffer
  25374. */
  25375. Scene.prototype.getSceneUniformBuffer = function () {
  25376. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25377. };
  25378. /**
  25379. * Gets an unique (relatively to the current scene) Id
  25380. * @returns an unique number for the scene
  25381. */
  25382. Scene.prototype.getUniqueId = function () {
  25383. var result = Scene._uniqueIdCounter;
  25384. Scene._uniqueIdCounter++;
  25385. return result;
  25386. };
  25387. /**
  25388. * Add a mesh to the list of scene's meshes
  25389. * @param newMesh defines the mesh to add
  25390. */
  25391. Scene.prototype.addMesh = function (newMesh) {
  25392. this.meshes.push(newMesh);
  25393. //notify the collision coordinator
  25394. if (this.collisionCoordinator) {
  25395. this.collisionCoordinator.onMeshAdded(newMesh);
  25396. }
  25397. newMesh._resyncLightSources();
  25398. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25399. };
  25400. /**
  25401. * Remove a mesh for the list of scene's meshes
  25402. * @param toRemove defines the mesh to remove
  25403. * @returns the index where the mesh was in the mesh list
  25404. */
  25405. Scene.prototype.removeMesh = function (toRemove) {
  25406. var index = this.meshes.indexOf(toRemove);
  25407. if (index !== -1) {
  25408. // Remove from the scene if mesh found
  25409. this.meshes.splice(index, 1);
  25410. }
  25411. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25412. return index;
  25413. };
  25414. /**
  25415. * Add a transform node to the list of scene's transform nodes
  25416. * @param newTransformNode defines the transform node to add
  25417. */
  25418. Scene.prototype.addTransformNode = function (newTransformNode) {
  25419. this.transformNodes.push(newTransformNode);
  25420. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25421. };
  25422. /**
  25423. * Remove a transform node for the list of scene's transform nodes
  25424. * @param toRemove defines the transform node to remove
  25425. * @returns the index where the transform node was in the transform node list
  25426. */
  25427. Scene.prototype.removeTransformNode = function (toRemove) {
  25428. var index = this.transformNodes.indexOf(toRemove);
  25429. if (index !== -1) {
  25430. // Remove from the scene if found
  25431. this.transformNodes.splice(index, 1);
  25432. }
  25433. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25434. return index;
  25435. };
  25436. /**
  25437. * Remove a skeleton for the list of scene's skeletons
  25438. * @param toRemove defines the skeleton to remove
  25439. * @returns the index where the skeleton was in the skeleton list
  25440. */
  25441. Scene.prototype.removeSkeleton = function (toRemove) {
  25442. var index = this.skeletons.indexOf(toRemove);
  25443. if (index !== -1) {
  25444. // Remove from the scene if found
  25445. this.skeletons.splice(index, 1);
  25446. }
  25447. return index;
  25448. };
  25449. /**
  25450. * Remove a morph target for the list of scene's morph targets
  25451. * @param toRemove defines the morph target to remove
  25452. * @returns the index where the morph target was in the morph target list
  25453. */
  25454. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25455. var index = this.morphTargetManagers.indexOf(toRemove);
  25456. if (index !== -1) {
  25457. // Remove from the scene if found
  25458. this.morphTargetManagers.splice(index, 1);
  25459. }
  25460. return index;
  25461. };
  25462. /**
  25463. * Remove a light for the list of scene's lights
  25464. * @param toRemove defines the light to remove
  25465. * @returns the index where the light was in the light list
  25466. */
  25467. Scene.prototype.removeLight = function (toRemove) {
  25468. var index = this.lights.indexOf(toRemove);
  25469. if (index !== -1) {
  25470. // Remove from meshes
  25471. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25472. var mesh = _a[_i];
  25473. mesh._removeLightSource(toRemove);
  25474. }
  25475. // Remove from the scene if mesh found
  25476. this.lights.splice(index, 1);
  25477. this.sortLightsByPriority();
  25478. }
  25479. this.onLightRemovedObservable.notifyObservers(toRemove);
  25480. return index;
  25481. };
  25482. /**
  25483. * Remove a camera for the list of scene's cameras
  25484. * @param toRemove defines the camera to remove
  25485. * @returns the index where the camera was in the camera list
  25486. */
  25487. Scene.prototype.removeCamera = function (toRemove) {
  25488. var index = this.cameras.indexOf(toRemove);
  25489. if (index !== -1) {
  25490. // Remove from the scene if mesh found
  25491. this.cameras.splice(index, 1);
  25492. }
  25493. // Remove from activeCameras
  25494. var index2 = this.activeCameras.indexOf(toRemove);
  25495. if (index2 !== -1) {
  25496. // Remove from the scene if mesh found
  25497. this.activeCameras.splice(index2, 1);
  25498. }
  25499. // Reset the activeCamera
  25500. if (this.activeCamera === toRemove) {
  25501. if (this.cameras.length > 0) {
  25502. this.activeCamera = this.cameras[0];
  25503. }
  25504. else {
  25505. this.activeCamera = null;
  25506. }
  25507. }
  25508. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25509. return index;
  25510. };
  25511. /**
  25512. * Remove a particle system for the list of scene's particle systems
  25513. * @param toRemove defines the particle system to remove
  25514. * @returns the index where the particle system was in the particle system list
  25515. */
  25516. Scene.prototype.removeParticleSystem = function (toRemove) {
  25517. var index = this.particleSystems.indexOf(toRemove);
  25518. if (index !== -1) {
  25519. this.particleSystems.splice(index, 1);
  25520. }
  25521. return index;
  25522. };
  25523. /**
  25524. * Remove a animation for the list of scene's animations
  25525. * @param toRemove defines the animation to remove
  25526. * @returns the index where the animation was in the animation list
  25527. */
  25528. Scene.prototype.removeAnimation = function (toRemove) {
  25529. var index = this.animations.indexOf(toRemove);
  25530. if (index !== -1) {
  25531. this.animations.splice(index, 1);
  25532. }
  25533. return index;
  25534. };
  25535. /**
  25536. * Removes the given animation group from this scene.
  25537. * @param toRemove The animation group to remove
  25538. * @returns The index of the removed animation group
  25539. */
  25540. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25541. var index = this.animationGroups.indexOf(toRemove);
  25542. if (index !== -1) {
  25543. this.animationGroups.splice(index, 1);
  25544. }
  25545. return index;
  25546. };
  25547. /**
  25548. * Removes the given multi-material from this scene.
  25549. * @param toRemove The multi-material to remove
  25550. * @returns The index of the removed multi-material
  25551. */
  25552. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25553. var index = this.multiMaterials.indexOf(toRemove);
  25554. if (index !== -1) {
  25555. this.multiMaterials.splice(index, 1);
  25556. }
  25557. return index;
  25558. };
  25559. /**
  25560. * Removes the given material from this scene.
  25561. * @param toRemove The material to remove
  25562. * @returns The index of the removed material
  25563. */
  25564. Scene.prototype.removeMaterial = function (toRemove) {
  25565. var index = this.materials.indexOf(toRemove);
  25566. if (index !== -1) {
  25567. this.materials.splice(index, 1);
  25568. }
  25569. return index;
  25570. };
  25571. /**
  25572. * Removes the given lens flare system from this scene.
  25573. * @param toRemove The lens flare system to remove
  25574. * @returns The index of the removed lens flare system
  25575. */
  25576. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25577. var index = this.lensFlareSystems.indexOf(toRemove);
  25578. if (index !== -1) {
  25579. this.lensFlareSystems.splice(index, 1);
  25580. }
  25581. return index;
  25582. };
  25583. /**
  25584. * Removes the given action manager from this scene.
  25585. * @param toRemove The action manager to remove
  25586. * @returns The index of the removed action manager
  25587. */
  25588. Scene.prototype.removeActionManager = function (toRemove) {
  25589. var index = this._actionManagers.indexOf(toRemove);
  25590. if (index !== -1) {
  25591. this._actionManagers.splice(index, 1);
  25592. }
  25593. return index;
  25594. };
  25595. /**
  25596. * Removes the given effect layer from this scene.
  25597. * @param toRemove defines the effect layer to remove
  25598. * @returns the index of the removed effect layer
  25599. */
  25600. Scene.prototype.removeEffectLayer = function (toRemove) {
  25601. var index = this.effectLayers.indexOf(toRemove);
  25602. if (index !== -1) {
  25603. this.effectLayers.splice(index, 1);
  25604. }
  25605. return index;
  25606. };
  25607. /**
  25608. * Removes the given texture from this scene.
  25609. * @param toRemove The texture to remove
  25610. * @returns The index of the removed texture
  25611. */
  25612. Scene.prototype.removeTexture = function (toRemove) {
  25613. var index = this.textures.indexOf(toRemove);
  25614. if (index !== -1) {
  25615. this.textures.splice(index, 1);
  25616. }
  25617. return index;
  25618. };
  25619. /**
  25620. * Adds the given light to this scene
  25621. * @param newLight The light to add
  25622. */
  25623. Scene.prototype.addLight = function (newLight) {
  25624. this.lights.push(newLight);
  25625. this.sortLightsByPriority();
  25626. // Add light to all meshes (To support if the light is removed and then readded)
  25627. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25628. var mesh = _a[_i];
  25629. if (mesh._lightSources.indexOf(newLight) === -1) {
  25630. mesh._lightSources.push(newLight);
  25631. mesh._resyncLightSources();
  25632. }
  25633. }
  25634. this.onNewLightAddedObservable.notifyObservers(newLight);
  25635. };
  25636. /**
  25637. * Sorts the list list based on light priorities
  25638. */
  25639. Scene.prototype.sortLightsByPriority = function () {
  25640. if (this.requireLightSorting) {
  25641. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25642. }
  25643. };
  25644. /**
  25645. * Adds the given camera to this scene
  25646. * @param newCamera The camera to add
  25647. */
  25648. Scene.prototype.addCamera = function (newCamera) {
  25649. this.cameras.push(newCamera);
  25650. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25651. };
  25652. /**
  25653. * Adds the given skeleton to this scene
  25654. * @param newSkeleton The skeleton to add
  25655. */
  25656. Scene.prototype.addSkeleton = function (newSkeleton) {
  25657. this.skeletons.push(newSkeleton);
  25658. };
  25659. /**
  25660. * Adds the given particle system to this scene
  25661. * @param newParticleSystem The particle system to add
  25662. */
  25663. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25664. this.particleSystems.push(newParticleSystem);
  25665. };
  25666. /**
  25667. * Adds the given animation to this scene
  25668. * @param newAnimation The animation to add
  25669. */
  25670. Scene.prototype.addAnimation = function (newAnimation) {
  25671. this.animations.push(newAnimation);
  25672. };
  25673. /**
  25674. * Adds the given animation group to this scene.
  25675. * @param newAnimationGroup The animation group to add
  25676. */
  25677. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25678. this.animationGroups.push(newAnimationGroup);
  25679. };
  25680. /**
  25681. * Adds the given multi-material to this scene
  25682. * @param newMultiMaterial The multi-material to add
  25683. */
  25684. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25685. this.multiMaterials.push(newMultiMaterial);
  25686. };
  25687. /**
  25688. * Adds the given material to this scene
  25689. * @param newMaterial The material to add
  25690. */
  25691. Scene.prototype.addMaterial = function (newMaterial) {
  25692. this.materials.push(newMaterial);
  25693. };
  25694. /**
  25695. * Adds the given morph target to this scene
  25696. * @param newMorphTargetManager The morph target to add
  25697. */
  25698. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25699. this.morphTargetManagers.push(newMorphTargetManager);
  25700. };
  25701. /**
  25702. * Adds the given geometry to this scene
  25703. * @param newGeometry The geometry to add
  25704. */
  25705. Scene.prototype.addGeometry = function (newGeometry) {
  25706. this._geometries.push(newGeometry);
  25707. };
  25708. /**
  25709. * Adds the given lens flare system to this scene
  25710. * @param newLensFlareSystem The lens flare system to add
  25711. */
  25712. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25713. this.lensFlareSystems.push(newLensFlareSystem);
  25714. };
  25715. /**
  25716. * Adds the given effect layer to this scene
  25717. * @param newEffectLayer defines the effect layer to add
  25718. */
  25719. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  25720. this.effectLayers.push(newEffectLayer);
  25721. };
  25722. /**
  25723. * Adds the given action manager to this scene
  25724. * @param newActionManager The action manager to add
  25725. */
  25726. Scene.prototype.addActionManager = function (newActionManager) {
  25727. this._actionManagers.push(newActionManager);
  25728. };
  25729. /**
  25730. * Adds the given texture to this scene.
  25731. * @param newTexture The texture to add
  25732. */
  25733. Scene.prototype.addTexture = function (newTexture) {
  25734. this.textures.push(newTexture);
  25735. };
  25736. /**
  25737. * Switch active camera
  25738. * @param newCamera defines the new active camera
  25739. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  25740. */
  25741. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  25742. if (attachControl === void 0) { attachControl = true; }
  25743. var canvas = this._engine.getRenderingCanvas();
  25744. if (!canvas) {
  25745. return;
  25746. }
  25747. if (this.activeCamera) {
  25748. this.activeCamera.detachControl(canvas);
  25749. }
  25750. this.activeCamera = newCamera;
  25751. if (attachControl) {
  25752. newCamera.attachControl(canvas);
  25753. }
  25754. };
  25755. /**
  25756. * sets the active camera of the scene using its ID
  25757. * @param id defines the camera's ID
  25758. * @return the new active camera or null if none found.
  25759. */
  25760. Scene.prototype.setActiveCameraByID = function (id) {
  25761. var camera = this.getCameraByID(id);
  25762. if (camera) {
  25763. this.activeCamera = camera;
  25764. return camera;
  25765. }
  25766. return null;
  25767. };
  25768. /**
  25769. * sets the active camera of the scene using its name
  25770. * @param name defines the camera's name
  25771. * @returns the new active camera or null if none found.
  25772. */
  25773. Scene.prototype.setActiveCameraByName = function (name) {
  25774. var camera = this.getCameraByName(name);
  25775. if (camera) {
  25776. this.activeCamera = camera;
  25777. return camera;
  25778. }
  25779. return null;
  25780. };
  25781. /**
  25782. * get an animation group using its name
  25783. * @param name defines the material's name
  25784. * @return the animation group or null if none found.
  25785. */
  25786. Scene.prototype.getAnimationGroupByName = function (name) {
  25787. for (var index = 0; index < this.animationGroups.length; index++) {
  25788. if (this.animationGroups[index].name === name) {
  25789. return this.animationGroups[index];
  25790. }
  25791. }
  25792. return null;
  25793. };
  25794. /**
  25795. * get a material using its id
  25796. * @param id defines the material's ID
  25797. * @return the material or null if none found.
  25798. */
  25799. Scene.prototype.getMaterialByID = function (id) {
  25800. for (var index = 0; index < this.materials.length; index++) {
  25801. if (this.materials[index].id === id) {
  25802. return this.materials[index];
  25803. }
  25804. }
  25805. return null;
  25806. };
  25807. /**
  25808. * Gets a material using its name
  25809. * @param name defines the material's name
  25810. * @return the material or null if none found.
  25811. */
  25812. Scene.prototype.getMaterialByName = function (name) {
  25813. for (var index = 0; index < this.materials.length; index++) {
  25814. if (this.materials[index].name === name) {
  25815. return this.materials[index];
  25816. }
  25817. }
  25818. return null;
  25819. };
  25820. /**
  25821. * Gets a lens flare system using its name
  25822. * @param name defines the name to look for
  25823. * @returns the lens flare system or null if not found
  25824. */
  25825. Scene.prototype.getLensFlareSystemByName = function (name) {
  25826. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25827. if (this.lensFlareSystems[index].name === name) {
  25828. return this.lensFlareSystems[index];
  25829. }
  25830. }
  25831. return null;
  25832. };
  25833. /**
  25834. * Gets a lens flare system using its id
  25835. * @param id defines the id to look for
  25836. * @returns the lens flare system or null if not found
  25837. */
  25838. Scene.prototype.getLensFlareSystemByID = function (id) {
  25839. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25840. if (this.lensFlareSystems[index].id === id) {
  25841. return this.lensFlareSystems[index];
  25842. }
  25843. }
  25844. return null;
  25845. };
  25846. /**
  25847. * Gets a camera using its id
  25848. * @param id defines the id to look for
  25849. * @returns the camera or null if not found
  25850. */
  25851. Scene.prototype.getCameraByID = function (id) {
  25852. for (var index = 0; index < this.cameras.length; index++) {
  25853. if (this.cameras[index].id === id) {
  25854. return this.cameras[index];
  25855. }
  25856. }
  25857. return null;
  25858. };
  25859. /**
  25860. * Gets a camera using its unique id
  25861. * @param uniqueId defines the unique id to look for
  25862. * @returns the camera or null if not found
  25863. */
  25864. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  25865. for (var index = 0; index < this.cameras.length; index++) {
  25866. if (this.cameras[index].uniqueId === uniqueId) {
  25867. return this.cameras[index];
  25868. }
  25869. }
  25870. return null;
  25871. };
  25872. /**
  25873. * Gets a camera using its name
  25874. * @param name defines the camera's name
  25875. * @return the camera or null if none found.
  25876. */
  25877. Scene.prototype.getCameraByName = function (name) {
  25878. for (var index = 0; index < this.cameras.length; index++) {
  25879. if (this.cameras[index].name === name) {
  25880. return this.cameras[index];
  25881. }
  25882. }
  25883. return null;
  25884. };
  25885. /**
  25886. * Gets a bone using its id
  25887. * @param id defines the bone's id
  25888. * @return the bone or null if not found
  25889. */
  25890. Scene.prototype.getBoneByID = function (id) {
  25891. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25892. var skeleton = this.skeletons[skeletonIndex];
  25893. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25894. if (skeleton.bones[boneIndex].id === id) {
  25895. return skeleton.bones[boneIndex];
  25896. }
  25897. }
  25898. }
  25899. return null;
  25900. };
  25901. /**
  25902. * Gets a bone using its id
  25903. * @param name defines the bone's name
  25904. * @return the bone or null if not found
  25905. */
  25906. Scene.prototype.getBoneByName = function (name) {
  25907. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25908. var skeleton = this.skeletons[skeletonIndex];
  25909. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25910. if (skeleton.bones[boneIndex].name === name) {
  25911. return skeleton.bones[boneIndex];
  25912. }
  25913. }
  25914. }
  25915. return null;
  25916. };
  25917. /**
  25918. * Gets a light node using its name
  25919. * @param name defines the the light's name
  25920. * @return the light or null if none found.
  25921. */
  25922. Scene.prototype.getLightByName = function (name) {
  25923. for (var index = 0; index < this.lights.length; index++) {
  25924. if (this.lights[index].name === name) {
  25925. return this.lights[index];
  25926. }
  25927. }
  25928. return null;
  25929. };
  25930. /**
  25931. * Gets a light node using its id
  25932. * @param id defines the light's id
  25933. * @return the light or null if none found.
  25934. */
  25935. Scene.prototype.getLightByID = function (id) {
  25936. for (var index = 0; index < this.lights.length; index++) {
  25937. if (this.lights[index].id === id) {
  25938. return this.lights[index];
  25939. }
  25940. }
  25941. return null;
  25942. };
  25943. /**
  25944. * Gets a light node using its scene-generated unique ID
  25945. * @param uniqueId defines the light's unique id
  25946. * @return the light or null if none found.
  25947. */
  25948. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  25949. for (var index = 0; index < this.lights.length; index++) {
  25950. if (this.lights[index].uniqueId === uniqueId) {
  25951. return this.lights[index];
  25952. }
  25953. }
  25954. return null;
  25955. };
  25956. /**
  25957. * Gets a particle system by id
  25958. * @param id defines the particle system id
  25959. * @return the corresponding system or null if none found
  25960. */
  25961. Scene.prototype.getParticleSystemByID = function (id) {
  25962. for (var index = 0; index < this.particleSystems.length; index++) {
  25963. if (this.particleSystems[index].id === id) {
  25964. return this.particleSystems[index];
  25965. }
  25966. }
  25967. return null;
  25968. };
  25969. /**
  25970. * Gets a geometry using its ID
  25971. * @param id defines the geometry's id
  25972. * @return the geometry or null if none found.
  25973. */
  25974. Scene.prototype.getGeometryByID = function (id) {
  25975. for (var index = 0; index < this._geometries.length; index++) {
  25976. if (this._geometries[index].id === id) {
  25977. return this._geometries[index];
  25978. }
  25979. }
  25980. return null;
  25981. };
  25982. /**
  25983. * Add a new geometry to this scene
  25984. * @param geometry defines the geometry to be added to the scene.
  25985. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  25986. * @return a boolean defining if the geometry was added or not
  25987. */
  25988. Scene.prototype.pushGeometry = function (geometry, force) {
  25989. if (!force && this.getGeometryByID(geometry.id)) {
  25990. return false;
  25991. }
  25992. this._geometries.push(geometry);
  25993. //notify the collision coordinator
  25994. if (this.collisionCoordinator) {
  25995. this.collisionCoordinator.onGeometryAdded(geometry);
  25996. }
  25997. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  25998. return true;
  25999. };
  26000. /**
  26001. * Removes an existing geometry
  26002. * @param geometry defines the geometry to be removed from the scene
  26003. * @return a boolean defining if the geometry was removed or not
  26004. */
  26005. Scene.prototype.removeGeometry = function (geometry) {
  26006. var index = this._geometries.indexOf(geometry);
  26007. if (index > -1) {
  26008. this._geometries.splice(index, 1);
  26009. //notify the collision coordinator
  26010. if (this.collisionCoordinator) {
  26011. this.collisionCoordinator.onGeometryDeleted(geometry);
  26012. }
  26013. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26014. return true;
  26015. }
  26016. return false;
  26017. };
  26018. /**
  26019. * Gets the list of geometries attached to the scene
  26020. * @returns an array of Geometry
  26021. */
  26022. Scene.prototype.getGeometries = function () {
  26023. return this._geometries;
  26024. };
  26025. /**
  26026. * Gets the first added mesh found of a given ID
  26027. * @param id defines the id to search for
  26028. * @return the mesh found or null if not found at all
  26029. */
  26030. Scene.prototype.getMeshByID = function (id) {
  26031. for (var index = 0; index < this.meshes.length; index++) {
  26032. if (this.meshes[index].id === id) {
  26033. return this.meshes[index];
  26034. }
  26035. }
  26036. return null;
  26037. };
  26038. /**
  26039. * Gets a list of meshes using their id
  26040. * @param id defines the id to search for
  26041. * @returns a list of meshes
  26042. */
  26043. Scene.prototype.getMeshesByID = function (id) {
  26044. return this.meshes.filter(function (m) {
  26045. return m.id === id;
  26046. });
  26047. };
  26048. /**
  26049. * Gets the first added transform node found of a given ID
  26050. * @param id defines the id to search for
  26051. * @return the found transform node or null if not found at all.
  26052. */
  26053. Scene.prototype.getTransformNodeByID = function (id) {
  26054. for (var index = 0; index < this.transformNodes.length; index++) {
  26055. if (this.transformNodes[index].id === id) {
  26056. return this.transformNodes[index];
  26057. }
  26058. }
  26059. return null;
  26060. };
  26061. /**
  26062. * Gets a list of transform nodes using their id
  26063. * @param id defines the id to search for
  26064. * @returns a list of transform nodes
  26065. */
  26066. Scene.prototype.getTransformNodesByID = function (id) {
  26067. return this.transformNodes.filter(function (m) {
  26068. return m.id === id;
  26069. });
  26070. };
  26071. /**
  26072. * Gets a mesh with its auto-generated unique id
  26073. * @param uniqueId defines the unique id to search for
  26074. * @return the found mesh or null if not found at all.
  26075. */
  26076. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26077. for (var index = 0; index < this.meshes.length; index++) {
  26078. if (this.meshes[index].uniqueId === uniqueId) {
  26079. return this.meshes[index];
  26080. }
  26081. }
  26082. return null;
  26083. };
  26084. /**
  26085. * Gets a the last added mesh using a given id
  26086. * @param id defines the id to search for
  26087. * @return the found mesh or null if not found at all.
  26088. */
  26089. Scene.prototype.getLastMeshByID = function (id) {
  26090. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26091. if (this.meshes[index].id === id) {
  26092. return this.meshes[index];
  26093. }
  26094. }
  26095. return null;
  26096. };
  26097. /**
  26098. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26099. * @param id defines the id to search for
  26100. * @return the found node or null if not found at all
  26101. */
  26102. Scene.prototype.getLastEntryByID = function (id) {
  26103. var index;
  26104. for (index = this.meshes.length - 1; index >= 0; index--) {
  26105. if (this.meshes[index].id === id) {
  26106. return this.meshes[index];
  26107. }
  26108. }
  26109. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26110. if (this.transformNodes[index].id === id) {
  26111. return this.transformNodes[index];
  26112. }
  26113. }
  26114. for (index = this.cameras.length - 1; index >= 0; index--) {
  26115. if (this.cameras[index].id === id) {
  26116. return this.cameras[index];
  26117. }
  26118. }
  26119. for (index = this.lights.length - 1; index >= 0; index--) {
  26120. if (this.lights[index].id === id) {
  26121. return this.lights[index];
  26122. }
  26123. }
  26124. return null;
  26125. };
  26126. /**
  26127. * Gets a node (Mesh, Camera, Light) using a given id
  26128. * @param id defines the id to search for
  26129. * @return the found node or null if not found at all
  26130. */
  26131. Scene.prototype.getNodeByID = function (id) {
  26132. var mesh = this.getMeshByID(id);
  26133. if (mesh) {
  26134. return mesh;
  26135. }
  26136. var light = this.getLightByID(id);
  26137. if (light) {
  26138. return light;
  26139. }
  26140. var camera = this.getCameraByID(id);
  26141. if (camera) {
  26142. return camera;
  26143. }
  26144. var bone = this.getBoneByID(id);
  26145. return bone;
  26146. };
  26147. /**
  26148. * Gets a node (Mesh, Camera, Light) using a given name
  26149. * @param name defines the name to search for
  26150. * @return the found node or null if not found at all.
  26151. */
  26152. Scene.prototype.getNodeByName = function (name) {
  26153. var mesh = this.getMeshByName(name);
  26154. if (mesh) {
  26155. return mesh;
  26156. }
  26157. var light = this.getLightByName(name);
  26158. if (light) {
  26159. return light;
  26160. }
  26161. var camera = this.getCameraByName(name);
  26162. if (camera) {
  26163. return camera;
  26164. }
  26165. var bone = this.getBoneByName(name);
  26166. return bone;
  26167. };
  26168. /**
  26169. * Gets a mesh using a given name
  26170. * @param name defines the name to search for
  26171. * @return the found mesh or null if not found at all.
  26172. */
  26173. Scene.prototype.getMeshByName = function (name) {
  26174. for (var index = 0; index < this.meshes.length; index++) {
  26175. if (this.meshes[index].name === name) {
  26176. return this.meshes[index];
  26177. }
  26178. }
  26179. return null;
  26180. };
  26181. /**
  26182. * Gets a transform node using a given name
  26183. * @param name defines the name to search for
  26184. * @return the found transform node or null if not found at all.
  26185. */
  26186. Scene.prototype.getTransformNodeByName = function (name) {
  26187. for (var index = 0; index < this.transformNodes.length; index++) {
  26188. if (this.transformNodes[index].name === name) {
  26189. return this.transformNodes[index];
  26190. }
  26191. }
  26192. return null;
  26193. };
  26194. /**
  26195. * Gets a sound using a given name
  26196. * @param name defines the name to search for
  26197. * @return the found sound or null if not found at all.
  26198. */
  26199. Scene.prototype.getSoundByName = function (name) {
  26200. var index;
  26201. if (BABYLON.AudioEngine) {
  26202. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26203. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26204. return this.mainSoundTrack.soundCollection[index];
  26205. }
  26206. }
  26207. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26208. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26209. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26210. return this.soundTracks[sdIndex].soundCollection[index];
  26211. }
  26212. }
  26213. }
  26214. }
  26215. return null;
  26216. };
  26217. /**
  26218. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26219. * @param id defines the id to search for
  26220. * @return the found skeleton or null if not found at all.
  26221. */
  26222. Scene.prototype.getLastSkeletonByID = function (id) {
  26223. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26224. if (this.skeletons[index].id === id) {
  26225. return this.skeletons[index];
  26226. }
  26227. }
  26228. return null;
  26229. };
  26230. /**
  26231. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26232. * @param id defines the id to search for
  26233. * @return the found skeleton or null if not found at all.
  26234. */
  26235. Scene.prototype.getSkeletonById = function (id) {
  26236. for (var index = 0; index < this.skeletons.length; index++) {
  26237. if (this.skeletons[index].id === id) {
  26238. return this.skeletons[index];
  26239. }
  26240. }
  26241. return null;
  26242. };
  26243. /**
  26244. * Gets a skeleton using a given name
  26245. * @param name defines the name to search for
  26246. * @return the found skeleton or null if not found at all.
  26247. */
  26248. Scene.prototype.getSkeletonByName = function (name) {
  26249. for (var index = 0; index < this.skeletons.length; index++) {
  26250. if (this.skeletons[index].name === name) {
  26251. return this.skeletons[index];
  26252. }
  26253. }
  26254. return null;
  26255. };
  26256. /**
  26257. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26258. * @param id defines the id to search for
  26259. * @return the found morph target manager or null if not found at all.
  26260. */
  26261. Scene.prototype.getMorphTargetManagerById = function (id) {
  26262. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26263. if (this.morphTargetManagers[index].uniqueId === id) {
  26264. return this.morphTargetManagers[index];
  26265. }
  26266. }
  26267. return null;
  26268. };
  26269. /**
  26270. * Gets a boolean indicating if the given mesh is active
  26271. * @param mesh defines the mesh to look for
  26272. * @returns true if the mesh is in the active list
  26273. */
  26274. Scene.prototype.isActiveMesh = function (mesh) {
  26275. return (this._activeMeshes.indexOf(mesh) !== -1);
  26276. };
  26277. /**
  26278. * Return a the first highlight layer of the scene with a given name.
  26279. * @param name The name of the highlight layer to look for.
  26280. * @return The highlight layer if found otherwise null.
  26281. */
  26282. Scene.prototype.getHighlightLayerByName = function (name) {
  26283. for (var index = 0; index < this.effectLayers.length; index++) {
  26284. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26285. return this.effectLayers[index];
  26286. }
  26287. }
  26288. return null;
  26289. };
  26290. /**
  26291. * Return a the first highlight layer of the scene with a given name.
  26292. * @param name The name of the highlight layer to look for.
  26293. * @return The highlight layer if found otherwise null.
  26294. */
  26295. Scene.prototype.getGlowLayerByName = function (name) {
  26296. for (var index = 0; index < this.effectLayers.length; index++) {
  26297. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26298. return this.effectLayers[index];
  26299. }
  26300. }
  26301. return null;
  26302. };
  26303. Object.defineProperty(Scene.prototype, "uid", {
  26304. /**
  26305. * Return a unique id as a string which can serve as an identifier for the scene
  26306. */
  26307. get: function () {
  26308. if (!this._uid) {
  26309. this._uid = BABYLON.Tools.RandomId();
  26310. }
  26311. return this._uid;
  26312. },
  26313. enumerable: true,
  26314. configurable: true
  26315. });
  26316. /**
  26317. * Add an externaly attached data from its key.
  26318. * This method call will fail and return false, if such key already exists.
  26319. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26320. * @param key the unique key that identifies the data
  26321. * @param data the data object to associate to the key for this Engine instance
  26322. * @return true if no such key were already present and the data was added successfully, false otherwise
  26323. */
  26324. Scene.prototype.addExternalData = function (key, data) {
  26325. if (!this._externalData) {
  26326. this._externalData = new BABYLON.StringDictionary();
  26327. }
  26328. return this._externalData.add(key, data);
  26329. };
  26330. /**
  26331. * Get an externaly attached data from its key
  26332. * @param key the unique key that identifies the data
  26333. * @return the associated data, if present (can be null), or undefined if not present
  26334. */
  26335. Scene.prototype.getExternalData = function (key) {
  26336. if (!this._externalData) {
  26337. return null;
  26338. }
  26339. return this._externalData.get(key);
  26340. };
  26341. /**
  26342. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26343. * @param key the unique key that identifies the data
  26344. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26345. * @return the associated data, can be null if the factory returned null.
  26346. */
  26347. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26348. if (!this._externalData) {
  26349. this._externalData = new BABYLON.StringDictionary();
  26350. }
  26351. return this._externalData.getOrAddWithFactory(key, factory);
  26352. };
  26353. /**
  26354. * Remove an externaly attached data from the Engine instance
  26355. * @param key the unique key that identifies the data
  26356. * @return true if the data was successfully removed, false if it doesn't exist
  26357. */
  26358. Scene.prototype.removeExternalData = function (key) {
  26359. return this._externalData.remove(key);
  26360. };
  26361. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26362. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26363. if (mesh.showSubMeshesBoundingBox) {
  26364. var boundingInfo = subMesh.getBoundingInfo();
  26365. if (boundingInfo !== null && boundingInfo !== undefined) {
  26366. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26367. }
  26368. }
  26369. var material = subMesh.getMaterial();
  26370. if (material !== null && material !== undefined) {
  26371. // Render targets
  26372. if (material.getRenderTargetTextures !== undefined) {
  26373. if (this._processedMaterials.indexOf(material) === -1) {
  26374. this._processedMaterials.push(material);
  26375. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26376. }
  26377. }
  26378. // Dispatch
  26379. this._activeIndices.addCount(subMesh.indexCount, false);
  26380. this._renderingManager.dispatch(subMesh, mesh, material);
  26381. }
  26382. }
  26383. };
  26384. /**
  26385. * Clear the processed materials smart array preventing retention point in material dispose.
  26386. */
  26387. Scene.prototype.freeProcessedMaterials = function () {
  26388. this._processedMaterials.dispose();
  26389. };
  26390. /**
  26391. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26392. */
  26393. Scene.prototype.freeActiveMeshes = function () {
  26394. this._activeMeshes.dispose();
  26395. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26396. this.activeCamera._activeMeshes.dispose();
  26397. }
  26398. if (this.activeCameras) {
  26399. for (var i = 0; i < this.activeCameras.length; i++) {
  26400. var activeCamera = this.activeCameras[i];
  26401. if (activeCamera && activeCamera._activeMeshes) {
  26402. activeCamera._activeMeshes.dispose();
  26403. }
  26404. }
  26405. }
  26406. };
  26407. /**
  26408. * Clear the info related to rendering groups preventing retention points during dispose.
  26409. */
  26410. Scene.prototype.freeRenderingGroups = function () {
  26411. if (this._renderingManager) {
  26412. this._renderingManager.freeRenderingGroups();
  26413. }
  26414. if (this.textures) {
  26415. for (var i = 0; i < this.textures.length; i++) {
  26416. var texture = this.textures[i];
  26417. if (texture && texture.renderList) {
  26418. texture.freeRenderingGroups();
  26419. }
  26420. }
  26421. }
  26422. };
  26423. /** @ignore */
  26424. Scene.prototype._isInIntermediateRendering = function () {
  26425. return this._intermediateRendering;
  26426. };
  26427. /**
  26428. * Defines the current active mesh candidate provider
  26429. * @param provider defines the provider to use
  26430. */
  26431. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26432. this._activeMeshCandidateProvider = provider;
  26433. };
  26434. /**
  26435. * Gets the current active mesh candidate provider
  26436. * @returns the current active mesh candidate provider
  26437. */
  26438. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26439. return this._activeMeshCandidateProvider;
  26440. };
  26441. /**
  26442. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26443. * @returns the current scene
  26444. */
  26445. Scene.prototype.freezeActiveMeshes = function () {
  26446. if (!this.activeCamera) {
  26447. return this;
  26448. }
  26449. if (!this._frustumPlanes) {
  26450. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26451. }
  26452. this._evaluateActiveMeshes();
  26453. this._activeMeshesFrozen = true;
  26454. return this;
  26455. };
  26456. /**
  26457. * Use this function to restart evaluating active meshes on every frame
  26458. * @returns the current scene
  26459. */
  26460. Scene.prototype.unfreezeActiveMeshes = function () {
  26461. this._activeMeshesFrozen = false;
  26462. return this;
  26463. };
  26464. Scene.prototype._evaluateActiveMeshes = function () {
  26465. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26466. return;
  26467. }
  26468. if (!this.activeCamera) {
  26469. return;
  26470. }
  26471. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26472. this.activeCamera._activeMeshes.reset();
  26473. this._activeMeshes.reset();
  26474. this._renderingManager.reset();
  26475. this._processedMaterials.reset();
  26476. this._activeParticleSystems.reset();
  26477. this._activeSkeletons.reset();
  26478. this._softwareSkinnedMeshes.reset();
  26479. if (this._boundingBoxRenderer) {
  26480. this._boundingBoxRenderer.reset();
  26481. }
  26482. // Meshes
  26483. var meshes;
  26484. var len;
  26485. var checkIsEnabled = true;
  26486. // Determine mesh candidates
  26487. if (this._activeMeshCandidateProvider !== undefined) {
  26488. // Use _activeMeshCandidateProvider
  26489. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26490. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26491. if (meshes !== undefined) {
  26492. len = meshes.length;
  26493. }
  26494. else {
  26495. len = 0;
  26496. }
  26497. }
  26498. else if (this._selectionOctree !== undefined) {
  26499. // Octree
  26500. var selection = this._selectionOctree.select(this._frustumPlanes);
  26501. meshes = selection.data;
  26502. len = selection.length;
  26503. }
  26504. else {
  26505. // Full scene traversal
  26506. len = this.meshes.length;
  26507. meshes = this.meshes;
  26508. }
  26509. // Check each mesh
  26510. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26511. mesh = meshes[meshIndex];
  26512. if (mesh.isBlocked) {
  26513. continue;
  26514. }
  26515. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26516. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26517. continue;
  26518. }
  26519. mesh.computeWorldMatrix();
  26520. // Intersections
  26521. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26522. this._meshesForIntersections.pushNoDuplicate(mesh);
  26523. }
  26524. // Switch to current LOD
  26525. meshLOD = mesh.getLOD(this.activeCamera);
  26526. if (meshLOD === undefined || meshLOD === null) {
  26527. continue;
  26528. }
  26529. mesh._preActivate();
  26530. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26531. this._activeMeshes.push(mesh);
  26532. this.activeCamera._activeMeshes.push(mesh);
  26533. mesh._activate(this._renderId);
  26534. if (meshLOD !== mesh) {
  26535. meshLOD._activate(this._renderId);
  26536. }
  26537. this._activeMesh(mesh, meshLOD);
  26538. }
  26539. }
  26540. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26541. // Particle systems
  26542. if (this.particlesEnabled) {
  26543. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26544. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26545. var particleSystem = this.particleSystems[particleIndex];
  26546. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26547. continue;
  26548. }
  26549. var emitter = particleSystem.emitter;
  26550. if (!emitter.position || emitter.isEnabled()) {
  26551. this._activeParticleSystems.push(particleSystem);
  26552. particleSystem.animate();
  26553. this._renderingManager.dispatchParticles(particleSystem);
  26554. }
  26555. }
  26556. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26557. }
  26558. };
  26559. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26560. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26561. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26562. mesh.skeleton.prepare();
  26563. }
  26564. if (!mesh.computeBonesUsingShaders) {
  26565. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26566. }
  26567. }
  26568. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26569. var boundingInfo = sourceMesh.getBoundingInfo();
  26570. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26571. }
  26572. if (mesh !== undefined && mesh !== null
  26573. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26574. // Submeshes Octrees
  26575. var len;
  26576. var subMeshes;
  26577. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26578. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26579. len = intersections.length;
  26580. subMeshes = intersections.data;
  26581. }
  26582. else {
  26583. subMeshes = mesh.subMeshes;
  26584. len = subMeshes.length;
  26585. }
  26586. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26587. subMesh = subMeshes[subIndex];
  26588. this._evaluateSubMesh(subMesh, mesh);
  26589. }
  26590. }
  26591. };
  26592. /**
  26593. * Update the transform matrix to update from the current active camera
  26594. * @param force defines a boolean used to force the update even if cache is up to date
  26595. */
  26596. Scene.prototype.updateTransformMatrix = function (force) {
  26597. if (!this.activeCamera) {
  26598. return;
  26599. }
  26600. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26601. };
  26602. /**
  26603. * 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)
  26604. * @param alternateCamera defines the camera to use
  26605. */
  26606. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26607. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26608. };
  26609. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26610. if (camera && camera._skipRendering) {
  26611. return;
  26612. }
  26613. var engine = this._engine;
  26614. this.activeCamera = camera;
  26615. if (!this.activeCamera)
  26616. throw new Error("Active camera not set");
  26617. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26618. // Viewport
  26619. engine.setViewport(this.activeCamera.viewport);
  26620. // Camera
  26621. this.resetCachedMaterial();
  26622. this._renderId++;
  26623. this.updateTransformMatrix();
  26624. if (camera._alternateCamera) {
  26625. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26626. this._alternateRendering = true;
  26627. }
  26628. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26629. // Meshes
  26630. this._evaluateActiveMeshes();
  26631. // Software skinning
  26632. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26633. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26634. mesh.applySkeleton(mesh.skeleton);
  26635. }
  26636. // Render targets
  26637. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26638. var needsRestoreFrameBuffer = false;
  26639. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26640. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26641. }
  26642. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26643. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26644. }
  26645. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26646. this._intermediateRendering = true;
  26647. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26648. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26649. var renderTarget = this._renderTargets.data[renderIndex];
  26650. if (renderTarget._shouldRender()) {
  26651. this._renderId++;
  26652. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26653. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26654. }
  26655. }
  26656. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26657. this._intermediateRendering = false;
  26658. this._renderId++;
  26659. needsRestoreFrameBuffer = true; // Restore back buffer
  26660. }
  26661. // Render EffecttLayer Texture
  26662. var stencilState = this._engine.getStencilBuffer();
  26663. var renderEffects = false;
  26664. var needStencil = false;
  26665. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26666. this._intermediateRendering = true;
  26667. for (var i = 0; i < this.effectLayers.length; i++) {
  26668. var effectLayer = this.effectLayers[i];
  26669. if (effectLayer.shouldRender() &&
  26670. (!effectLayer.camera ||
  26671. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26672. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26673. renderEffects = true;
  26674. needStencil = needStencil || effectLayer.needStencil();
  26675. var renderTarget = effectLayer._mainTexture;
  26676. if (renderTarget._shouldRender()) {
  26677. this._renderId++;
  26678. renderTarget.render(false, false);
  26679. needsRestoreFrameBuffer = true;
  26680. }
  26681. }
  26682. }
  26683. this._intermediateRendering = false;
  26684. this._renderId++;
  26685. }
  26686. if (needsRestoreFrameBuffer) {
  26687. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26688. }
  26689. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26690. // Prepare Frame
  26691. this.postProcessManager._prepareFrame();
  26692. // Backgrounds
  26693. var layerIndex;
  26694. var layer;
  26695. if (this.layers.length) {
  26696. engine.setDepthBuffer(false);
  26697. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26698. layer = this.layers[layerIndex];
  26699. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26700. layer.render();
  26701. }
  26702. }
  26703. engine.setDepthBuffer(true);
  26704. }
  26705. // Activate effect Layer stencil
  26706. if (needStencil) {
  26707. this._engine.setStencilBuffer(true);
  26708. }
  26709. // Render
  26710. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26711. this._renderingManager.render(null, null, true, true);
  26712. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26713. // Restore effect Layer stencil
  26714. if (needStencil) {
  26715. this._engine.setStencilBuffer(stencilState);
  26716. }
  26717. // Bounding boxes
  26718. if (this._boundingBoxRenderer) {
  26719. this._boundingBoxRenderer.render();
  26720. }
  26721. // Lens flares
  26722. if (this.lensFlaresEnabled) {
  26723. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26724. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26725. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26726. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26727. lensFlareSystem.render();
  26728. }
  26729. }
  26730. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26731. }
  26732. // Effect Layer
  26733. if (renderEffects) {
  26734. engine.setDepthBuffer(false);
  26735. for (var i = 0; i < this.effectLayers.length; i++) {
  26736. if (this.effectLayers[i].shouldRender()) {
  26737. this.effectLayers[i].render();
  26738. }
  26739. }
  26740. engine.setDepthBuffer(true);
  26741. }
  26742. // Foregrounds
  26743. if (this.layers.length) {
  26744. engine.setDepthBuffer(false);
  26745. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26746. layer = this.layers[layerIndex];
  26747. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26748. layer.render();
  26749. }
  26750. }
  26751. engine.setDepthBuffer(true);
  26752. }
  26753. // Finalize frame
  26754. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  26755. // Reset some special arrays
  26756. this._renderTargets.reset();
  26757. this._alternateRendering = false;
  26758. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  26759. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26760. };
  26761. Scene.prototype._processSubCameras = function (camera) {
  26762. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  26763. this._renderForCamera(camera);
  26764. return;
  26765. }
  26766. // rig cameras
  26767. for (var index = 0; index < camera._rigCameras.length; index++) {
  26768. this._renderForCamera(camera._rigCameras[index], camera);
  26769. }
  26770. this.activeCamera = camera;
  26771. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26772. };
  26773. Scene.prototype._checkIntersections = function () {
  26774. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  26775. var sourceMesh = this._meshesForIntersections.data[index];
  26776. if (!sourceMesh.actionManager) {
  26777. continue;
  26778. }
  26779. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  26780. var action = sourceMesh.actionManager.actions[actionIndex];
  26781. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26782. var parameters = action.getTriggerParameter();
  26783. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  26784. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  26785. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  26786. if (areIntersecting && currentIntersectionInProgress === -1) {
  26787. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  26788. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26789. sourceMesh._intersectionsInProgress.push(otherMesh);
  26790. }
  26791. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26792. sourceMesh._intersectionsInProgress.push(otherMesh);
  26793. }
  26794. }
  26795. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  26796. //They intersected, and now they don't.
  26797. //is this trigger an exit trigger? execute an event.
  26798. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26799. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26800. }
  26801. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  26802. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  26803. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  26804. return otherMesh === parameterMesh;
  26805. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26806. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  26807. }
  26808. }
  26809. }
  26810. }
  26811. }
  26812. };
  26813. /**
  26814. * Render the scene
  26815. */
  26816. Scene.prototype.render = function () {
  26817. if (this.isDisposed) {
  26818. return;
  26819. }
  26820. this._activeParticles.fetchNewFrame();
  26821. this._totalVertices.fetchNewFrame();
  26822. this._activeIndices.fetchNewFrame();
  26823. this._activeBones.fetchNewFrame();
  26824. this._meshesForIntersections.reset();
  26825. this.resetCachedMaterial();
  26826. this.onBeforeAnimationsObservable.notifyObservers(this);
  26827. // Actions
  26828. if (this.actionManager) {
  26829. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  26830. }
  26831. //Simplification Queue
  26832. if (this.simplificationQueue && !this.simplificationQueue.running) {
  26833. this.simplificationQueue.executeNext();
  26834. }
  26835. if (this._engine.isDeterministicLockStep()) {
  26836. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  26837. var defaultFPS = (60.0 / 1000.0);
  26838. var defaultFrameTime = 1000 / 60; // frame time in MS
  26839. if (this._physicsEngine) {
  26840. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  26841. }
  26842. var stepsTaken = 0;
  26843. var maxSubSteps = this._engine.getLockstepMaxSteps();
  26844. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  26845. internalSteps = Math.min(internalSteps, maxSubSteps);
  26846. do {
  26847. this.onBeforeStepObservable.notifyObservers(this);
  26848. // Animations
  26849. this._animationRatio = defaultFrameTime * defaultFPS;
  26850. this._animate();
  26851. this.onAfterAnimationsObservable.notifyObservers(this);
  26852. // Physics
  26853. if (this._physicsEngine) {
  26854. this.onBeforePhysicsObservable.notifyObservers(this);
  26855. this._physicsEngine._step(defaultFrameTime / 1000);
  26856. this.onAfterPhysicsObservable.notifyObservers(this);
  26857. }
  26858. this.onAfterStepObservable.notifyObservers(this);
  26859. this._currentStepId++;
  26860. stepsTaken++;
  26861. deltaTime -= defaultFrameTime;
  26862. } while (deltaTime > 0 && stepsTaken < internalSteps);
  26863. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  26864. }
  26865. else {
  26866. // Animations
  26867. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  26868. this._animationRatio = deltaTime * (60.0 / 1000.0);
  26869. this._animate();
  26870. this.onAfterAnimationsObservable.notifyObservers(this);
  26871. // Physics
  26872. if (this._physicsEngine) {
  26873. this.onBeforePhysicsObservable.notifyObservers(this);
  26874. this._physicsEngine._step(deltaTime / 1000.0);
  26875. this.onAfterPhysicsObservable.notifyObservers(this);
  26876. }
  26877. }
  26878. // update gamepad manager
  26879. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  26880. this._gamepadManager._checkGamepadsStatus();
  26881. }
  26882. // Update Cameras
  26883. if (this.activeCameras.length > 0) {
  26884. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26885. var camera = this.activeCameras[cameraIndex];
  26886. camera.update();
  26887. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26888. // rig cameras
  26889. for (var index = 0; index < camera._rigCameras.length; index++) {
  26890. camera._rigCameras[index].update();
  26891. }
  26892. }
  26893. }
  26894. }
  26895. else if (this.activeCamera) {
  26896. this.activeCamera.update();
  26897. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26898. // rig cameras
  26899. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  26900. this.activeCamera._rigCameras[index].update();
  26901. }
  26902. }
  26903. }
  26904. // Before render
  26905. this.onBeforeRenderObservable.notifyObservers(this);
  26906. // Customs render targets
  26907. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26908. var engine = this.getEngine();
  26909. var currentActiveCamera = this.activeCamera;
  26910. if (this.renderTargetsEnabled) {
  26911. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26912. this._intermediateRendering = true;
  26913. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  26914. var renderTarget = this.customRenderTargets[customIndex];
  26915. if (renderTarget._shouldRender()) {
  26916. this._renderId++;
  26917. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  26918. if (!this.activeCamera)
  26919. throw new Error("Active camera not set");
  26920. // Viewport
  26921. engine.setViewport(this.activeCamera.viewport);
  26922. // Camera
  26923. this.updateTransformMatrix();
  26924. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  26925. }
  26926. }
  26927. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26928. this._intermediateRendering = false;
  26929. this._renderId++;
  26930. }
  26931. // Restore back buffer
  26932. if (this.customRenderTargets.length > 0) {
  26933. engine.restoreDefaultFramebuffer();
  26934. }
  26935. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26936. this.activeCamera = currentActiveCamera;
  26937. // Procedural textures
  26938. if (this.proceduralTexturesEnabled) {
  26939. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26940. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  26941. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  26942. if (proceduralTexture._shouldRender()) {
  26943. proceduralTexture.render();
  26944. }
  26945. }
  26946. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26947. }
  26948. // Clear
  26949. if (this.autoClearDepthAndStencil || this.autoClear) {
  26950. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  26951. }
  26952. // Shadows
  26953. if (this.shadowsEnabled) {
  26954. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  26955. var light = this.lights[lightIndex];
  26956. var shadowGenerator = light.getShadowGenerator();
  26957. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  26958. var shadowMap = (shadowGenerator.getShadowMap());
  26959. if (this.textures.indexOf(shadowMap) !== -1) {
  26960. this._renderTargets.push(shadowMap);
  26961. }
  26962. }
  26963. }
  26964. }
  26965. // Depth renderer
  26966. for (var key in this._depthRenderer) {
  26967. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  26968. }
  26969. // Geometry renderer
  26970. if (this._geometryBufferRenderer) {
  26971. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  26972. }
  26973. // RenderPipeline
  26974. if (this._postProcessRenderPipelineManager) {
  26975. this._postProcessRenderPipelineManager.update();
  26976. }
  26977. // Multi-cameras?
  26978. if (this.activeCameras.length > 0) {
  26979. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26980. if (cameraIndex > 0) {
  26981. this._engine.clear(null, false, true, true);
  26982. }
  26983. this._processSubCameras(this.activeCameras[cameraIndex]);
  26984. }
  26985. }
  26986. else {
  26987. if (!this.activeCamera) {
  26988. throw new Error("No camera defined");
  26989. }
  26990. this._processSubCameras(this.activeCamera);
  26991. }
  26992. // Intersection checks
  26993. this._checkIntersections();
  26994. // Update the audio listener attached to the camera
  26995. if (BABYLON.AudioEngine) {
  26996. this._updateAudioParameters();
  26997. }
  26998. // After render
  26999. if (this.afterRender) {
  27000. this.afterRender();
  27001. }
  27002. this.onAfterRenderObservable.notifyObservers(this);
  27003. // Cleaning
  27004. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27005. var data = this._toBeDisposed.data[index];
  27006. if (data) {
  27007. data.dispose();
  27008. }
  27009. this._toBeDisposed[index] = null;
  27010. }
  27011. this._toBeDisposed.reset();
  27012. if (this.dumpNextRenderTargets) {
  27013. this.dumpNextRenderTargets = false;
  27014. }
  27015. this._activeBones.addCount(0, true);
  27016. this._activeIndices.addCount(0, true);
  27017. this._activeParticles.addCount(0, true);
  27018. };
  27019. Scene.prototype._updateAudioParameters = function () {
  27020. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27021. return;
  27022. }
  27023. var listeningCamera;
  27024. var audioEngine = BABYLON.Engine.audioEngine;
  27025. if (this.activeCameras.length > 0) {
  27026. listeningCamera = this.activeCameras[0];
  27027. }
  27028. else {
  27029. listeningCamera = this.activeCamera;
  27030. }
  27031. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27032. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27033. // for VR cameras
  27034. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27035. listeningCamera = listeningCamera.rigCameras[0];
  27036. }
  27037. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27038. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27039. cameraDirection.normalize();
  27040. // To avoid some errors on GearVR
  27041. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27042. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27043. }
  27044. var i;
  27045. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27046. var sound = this.mainSoundTrack.soundCollection[i];
  27047. if (sound.useCustomAttenuation) {
  27048. sound.updateDistanceFromListener();
  27049. }
  27050. }
  27051. for (i = 0; i < this.soundTracks.length; i++) {
  27052. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27053. sound = this.soundTracks[i].soundCollection[j];
  27054. if (sound.useCustomAttenuation) {
  27055. sound.updateDistanceFromListener();
  27056. }
  27057. }
  27058. }
  27059. }
  27060. };
  27061. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27062. // Audio
  27063. /**
  27064. * Gets or sets if audio support is enabled
  27065. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27066. */
  27067. get: function () {
  27068. return this._audioEnabled;
  27069. },
  27070. set: function (value) {
  27071. this._audioEnabled = value;
  27072. if (BABYLON.AudioEngine) {
  27073. if (this._audioEnabled) {
  27074. this._enableAudio();
  27075. }
  27076. else {
  27077. this._disableAudio();
  27078. }
  27079. }
  27080. },
  27081. enumerable: true,
  27082. configurable: true
  27083. });
  27084. Scene.prototype._disableAudio = function () {
  27085. var i;
  27086. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27087. this.mainSoundTrack.soundCollection[i].pause();
  27088. }
  27089. for (i = 0; i < this.soundTracks.length; i++) {
  27090. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27091. this.soundTracks[i].soundCollection[j].pause();
  27092. }
  27093. }
  27094. };
  27095. Scene.prototype._enableAudio = function () {
  27096. var i;
  27097. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27098. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27099. this.mainSoundTrack.soundCollection[i].play();
  27100. }
  27101. }
  27102. for (i = 0; i < this.soundTracks.length; i++) {
  27103. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27104. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27105. this.soundTracks[i].soundCollection[j].play();
  27106. }
  27107. }
  27108. }
  27109. };
  27110. Object.defineProperty(Scene.prototype, "headphone", {
  27111. /**
  27112. * Gets or sets if audio will be output to headphones
  27113. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27114. */
  27115. get: function () {
  27116. return this._headphone;
  27117. },
  27118. set: function (value) {
  27119. this._headphone = value;
  27120. if (BABYLON.AudioEngine) {
  27121. if (this._headphone) {
  27122. this._switchAudioModeForHeadphones();
  27123. }
  27124. else {
  27125. this._switchAudioModeForNormalSpeakers();
  27126. }
  27127. }
  27128. },
  27129. enumerable: true,
  27130. configurable: true
  27131. });
  27132. Scene.prototype._switchAudioModeForHeadphones = function () {
  27133. this.mainSoundTrack.switchPanningModelToHRTF();
  27134. for (var i = 0; i < this.soundTracks.length; i++) {
  27135. this.soundTracks[i].switchPanningModelToHRTF();
  27136. }
  27137. };
  27138. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27139. this.mainSoundTrack.switchPanningModelToEqualPower();
  27140. for (var i = 0; i < this.soundTracks.length; i++) {
  27141. this.soundTracks[i].switchPanningModelToEqualPower();
  27142. }
  27143. };
  27144. /**
  27145. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27146. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27147. * @returns the created depth renderer
  27148. */
  27149. Scene.prototype.enableDepthRenderer = function (camera) {
  27150. camera = camera || this.activeCamera;
  27151. if (!camera) {
  27152. throw "No camera available to enable depth renderer";
  27153. }
  27154. if (!this._depthRenderer[camera.id]) {
  27155. var textureType = 0;
  27156. if (this._engine.getCaps().textureHalfFloatRender) {
  27157. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27158. }
  27159. else if (this._engine.getCaps().textureFloatRender) {
  27160. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27161. }
  27162. else {
  27163. throw "Depth renderer does not support int texture type";
  27164. }
  27165. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27166. }
  27167. return this._depthRenderer[camera.id];
  27168. };
  27169. /**
  27170. * Disables a depth renderer for a given camera
  27171. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27172. */
  27173. Scene.prototype.disableDepthRenderer = function (camera) {
  27174. camera = camera || this.activeCamera;
  27175. if (!camera || !this._depthRenderer[camera.id]) {
  27176. return;
  27177. }
  27178. this._depthRenderer[camera.id].dispose();
  27179. delete this._depthRenderer[camera.id];
  27180. };
  27181. /**
  27182. * Enables a GeometryBufferRender and associates it with the scene
  27183. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27184. * @returns the GeometryBufferRenderer
  27185. */
  27186. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27187. if (ratio === void 0) { ratio = 1; }
  27188. if (this._geometryBufferRenderer) {
  27189. return this._geometryBufferRenderer;
  27190. }
  27191. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27192. if (!this._geometryBufferRenderer.isSupported) {
  27193. this._geometryBufferRenderer = null;
  27194. }
  27195. return this._geometryBufferRenderer;
  27196. };
  27197. /**
  27198. * Disables the GeometryBufferRender associated with the scene
  27199. */
  27200. Scene.prototype.disableGeometryBufferRenderer = function () {
  27201. if (!this._geometryBufferRenderer) {
  27202. return;
  27203. }
  27204. this._geometryBufferRenderer.dispose();
  27205. this._geometryBufferRenderer = null;
  27206. };
  27207. /**
  27208. * Freeze all materials
  27209. * A frozen material will not be updatable but should be faster to render
  27210. */
  27211. Scene.prototype.freezeMaterials = function () {
  27212. for (var i = 0; i < this.materials.length; i++) {
  27213. this.materials[i].freeze();
  27214. }
  27215. };
  27216. /**
  27217. * Unfreeze all materials
  27218. * A frozen material will not be updatable but should be faster to render
  27219. */
  27220. Scene.prototype.unfreezeMaterials = function () {
  27221. for (var i = 0; i < this.materials.length; i++) {
  27222. this.materials[i].unfreeze();
  27223. }
  27224. };
  27225. /**
  27226. * Releases all held ressources
  27227. */
  27228. Scene.prototype.dispose = function () {
  27229. this.beforeRender = null;
  27230. this.afterRender = null;
  27231. this.skeletons = [];
  27232. this.morphTargetManagers = [];
  27233. this.importedMeshesFiles = new Array();
  27234. this.stopAllAnimations();
  27235. this.resetCachedMaterial();
  27236. for (var key in this._depthRenderer) {
  27237. this._depthRenderer[key].dispose();
  27238. }
  27239. if (this._gamepadManager) {
  27240. this._gamepadManager.dispose();
  27241. this._gamepadManager = null;
  27242. }
  27243. // Smart arrays
  27244. if (this.activeCamera) {
  27245. this.activeCamera._activeMeshes.dispose();
  27246. this.activeCamera = null;
  27247. }
  27248. this._activeMeshes.dispose();
  27249. this._renderingManager.dispose();
  27250. this._processedMaterials.dispose();
  27251. this._activeParticleSystems.dispose();
  27252. this._activeSkeletons.dispose();
  27253. this._softwareSkinnedMeshes.dispose();
  27254. this._renderTargets.dispose();
  27255. this._registeredForLateAnimationBindings.dispose();
  27256. if (this._boundingBoxRenderer) {
  27257. this._boundingBoxRenderer.dispose();
  27258. }
  27259. this._meshesForIntersections.dispose();
  27260. this._toBeDisposed.dispose();
  27261. // Abort active requests
  27262. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27263. var request = _a[_i];
  27264. request.abort();
  27265. }
  27266. // Debug layer
  27267. if (this._debugLayer) {
  27268. this._debugLayer.hide();
  27269. }
  27270. // Events
  27271. this.onDisposeObservable.notifyObservers(this);
  27272. this.onDisposeObservable.clear();
  27273. this.onBeforeRenderObservable.clear();
  27274. this.onAfterRenderObservable.clear();
  27275. this.onBeforeRenderTargetsRenderObservable.clear();
  27276. this.onAfterRenderTargetsRenderObservable.clear();
  27277. this.onAfterStepObservable.clear();
  27278. this.onBeforeStepObservable.clear();
  27279. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27280. this.onAfterActiveMeshesEvaluationObservable.clear();
  27281. this.onBeforeParticlesRenderingObservable.clear();
  27282. this.onAfterParticlesRenderingObservable.clear();
  27283. this.onBeforeSpritesRenderingObservable.clear();
  27284. this.onAfterSpritesRenderingObservable.clear();
  27285. this.onBeforeDrawPhaseObservable.clear();
  27286. this.onAfterDrawPhaseObservable.clear();
  27287. this.onBeforePhysicsObservable.clear();
  27288. this.onAfterPhysicsObservable.clear();
  27289. this.onBeforeAnimationsObservable.clear();
  27290. this.onAfterAnimationsObservable.clear();
  27291. this.onDataLoadedObservable.clear();
  27292. this.detachControl();
  27293. // Release sounds & sounds tracks
  27294. if (BABYLON.AudioEngine) {
  27295. this.disposeSounds();
  27296. }
  27297. // VR Helper
  27298. if (this.VRHelper) {
  27299. this.VRHelper.dispose();
  27300. }
  27301. // Detach cameras
  27302. var canvas = this._engine.getRenderingCanvas();
  27303. if (canvas) {
  27304. var index;
  27305. for (index = 0; index < this.cameras.length; index++) {
  27306. this.cameras[index].detachControl(canvas);
  27307. }
  27308. }
  27309. // Release animation groups
  27310. while (this.animationGroups.length) {
  27311. this.animationGroups[0].dispose();
  27312. }
  27313. // Release lights
  27314. while (this.lights.length) {
  27315. this.lights[0].dispose();
  27316. }
  27317. // Release meshes
  27318. while (this.meshes.length) {
  27319. this.meshes[0].dispose(true);
  27320. }
  27321. while (this.transformNodes.length) {
  27322. this.removeTransformNode(this.transformNodes[0]);
  27323. }
  27324. // Release cameras
  27325. while (this.cameras.length) {
  27326. this.cameras[0].dispose();
  27327. }
  27328. // Release materials
  27329. if (this.defaultMaterial) {
  27330. this.defaultMaterial.dispose();
  27331. }
  27332. while (this.multiMaterials.length) {
  27333. this.multiMaterials[0].dispose();
  27334. }
  27335. while (this.materials.length) {
  27336. this.materials[0].dispose();
  27337. }
  27338. // Release particles
  27339. while (this.particleSystems.length) {
  27340. this.particleSystems[0].dispose();
  27341. }
  27342. // Release sprites
  27343. while (this.spriteManagers.length) {
  27344. this.spriteManagers[0].dispose();
  27345. }
  27346. // Release postProcesses
  27347. while (this.postProcesses.length) {
  27348. this.postProcesses[0].dispose();
  27349. }
  27350. // Release layers
  27351. while (this.layers.length) {
  27352. this.layers[0].dispose();
  27353. }
  27354. while (this.effectLayers.length) {
  27355. this.effectLayers[0].dispose();
  27356. }
  27357. // Release textures
  27358. while (this.textures.length) {
  27359. this.textures[0].dispose();
  27360. }
  27361. // Release UBO
  27362. this._sceneUbo.dispose();
  27363. if (this._alternateSceneUbo) {
  27364. this._alternateSceneUbo.dispose();
  27365. }
  27366. // Post-processes
  27367. this.postProcessManager.dispose();
  27368. if (this._postProcessRenderPipelineManager) {
  27369. this._postProcessRenderPipelineManager.dispose();
  27370. }
  27371. // Physics
  27372. if (this._physicsEngine) {
  27373. this.disablePhysicsEngine();
  27374. }
  27375. // Remove from engine
  27376. index = this._engine.scenes.indexOf(this);
  27377. if (index > -1) {
  27378. this._engine.scenes.splice(index, 1);
  27379. }
  27380. this._engine.wipeCaches(true);
  27381. this._isDisposed = true;
  27382. };
  27383. Object.defineProperty(Scene.prototype, "isDisposed", {
  27384. /**
  27385. * Gets if the scene is already disposed
  27386. */
  27387. get: function () {
  27388. return this._isDisposed;
  27389. },
  27390. enumerable: true,
  27391. configurable: true
  27392. });
  27393. /**
  27394. * Releases sounds & soundtracks
  27395. */
  27396. Scene.prototype.disposeSounds = function () {
  27397. if (!this._mainSoundTrack) {
  27398. return;
  27399. }
  27400. this.mainSoundTrack.dispose();
  27401. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27402. this.soundTracks[scIndex].dispose();
  27403. }
  27404. };
  27405. // Octrees
  27406. /**
  27407. * Get the world extend vectors with an optional filter
  27408. *
  27409. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27410. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27411. */
  27412. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27413. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27414. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27415. filterPredicate = filterPredicate || (function () { return true; });
  27416. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27417. mesh.computeWorldMatrix(true);
  27418. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27419. return;
  27420. }
  27421. var boundingInfo = mesh.getBoundingInfo();
  27422. var minBox = boundingInfo.boundingBox.minimumWorld;
  27423. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27424. BABYLON.Tools.CheckExtends(minBox, min, max);
  27425. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27426. });
  27427. return {
  27428. min: min,
  27429. max: max
  27430. };
  27431. };
  27432. /**
  27433. * Creates or updates the octree used to boost selection (picking)
  27434. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27435. * @param maxCapacity defines the maximum capacity per leaf
  27436. * @param maxDepth defines the maximum depth of the octree
  27437. * @returns an octree of AbstractMesh
  27438. */
  27439. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27440. if (maxCapacity === void 0) { maxCapacity = 64; }
  27441. if (maxDepth === void 0) { maxDepth = 2; }
  27442. if (!this._selectionOctree) {
  27443. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27444. }
  27445. var worldExtends = this.getWorldExtends();
  27446. // Update octree
  27447. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27448. return this._selectionOctree;
  27449. };
  27450. // Picking
  27451. /**
  27452. * Creates a ray that can be used to pick in the scene
  27453. * @param x defines the x coordinate of the origin (on-screen)
  27454. * @param y defines the y coordinate of the origin (on-screen)
  27455. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27456. * @param camera defines the camera to use for the picking
  27457. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27458. * @returns a Ray
  27459. */
  27460. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27461. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27462. var result = BABYLON.Ray.Zero();
  27463. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27464. return result;
  27465. };
  27466. /**
  27467. * Creates a ray that can be used to pick in the scene
  27468. * @param x defines the x coordinate of the origin (on-screen)
  27469. * @param y defines the y coordinate of the origin (on-screen)
  27470. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27471. * @param result defines the ray where to store the picking ray
  27472. * @param camera defines the camera to use for the picking
  27473. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27474. * @returns the current scene
  27475. */
  27476. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27477. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27478. var engine = this._engine;
  27479. if (!camera) {
  27480. if (!this.activeCamera)
  27481. throw new Error("Active camera not set");
  27482. camera = this.activeCamera;
  27483. }
  27484. var cameraViewport = camera.viewport;
  27485. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27486. // Moving coordinates to local viewport world
  27487. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27488. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27489. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27490. return this;
  27491. };
  27492. /**
  27493. * Creates a ray that can be used to pick in the scene
  27494. * @param x defines the x coordinate of the origin (on-screen)
  27495. * @param y defines the y coordinate of the origin (on-screen)
  27496. * @param camera defines the camera to use for the picking
  27497. * @returns a Ray
  27498. */
  27499. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27500. var result = BABYLON.Ray.Zero();
  27501. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27502. return result;
  27503. };
  27504. /**
  27505. * Creates a ray that can be used to pick in the scene
  27506. * @param x defines the x coordinate of the origin (on-screen)
  27507. * @param y defines the y coordinate of the origin (on-screen)
  27508. * @param result defines the ray where to store the picking ray
  27509. * @param camera defines the camera to use for the picking
  27510. * @returns the current scene
  27511. */
  27512. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27513. if (!BABYLON.PickingInfo) {
  27514. return this;
  27515. }
  27516. var engine = this._engine;
  27517. if (!camera) {
  27518. if (!this.activeCamera)
  27519. throw new Error("Active camera not set");
  27520. camera = this.activeCamera;
  27521. }
  27522. var cameraViewport = camera.viewport;
  27523. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27524. var identity = BABYLON.Matrix.Identity();
  27525. // Moving coordinates to local viewport world
  27526. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27527. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27528. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27529. return this;
  27530. };
  27531. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27532. if (!BABYLON.PickingInfo) {
  27533. return null;
  27534. }
  27535. var pickingInfo = null;
  27536. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27537. var mesh = this.meshes[meshIndex];
  27538. if (predicate) {
  27539. if (!predicate(mesh)) {
  27540. continue;
  27541. }
  27542. }
  27543. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27544. continue;
  27545. }
  27546. var world = mesh.getWorldMatrix();
  27547. var ray = rayFunction(world);
  27548. var result = mesh.intersects(ray, fastCheck);
  27549. if (!result || !result.hit)
  27550. continue;
  27551. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27552. continue;
  27553. pickingInfo = result;
  27554. if (fastCheck) {
  27555. break;
  27556. }
  27557. }
  27558. return pickingInfo || new BABYLON.PickingInfo();
  27559. };
  27560. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27561. if (!BABYLON.PickingInfo) {
  27562. return null;
  27563. }
  27564. var pickingInfos = new Array();
  27565. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27566. var mesh = this.meshes[meshIndex];
  27567. if (predicate) {
  27568. if (!predicate(mesh)) {
  27569. continue;
  27570. }
  27571. }
  27572. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27573. continue;
  27574. }
  27575. var world = mesh.getWorldMatrix();
  27576. var ray = rayFunction(world);
  27577. var result = mesh.intersects(ray, false);
  27578. if (!result || !result.hit)
  27579. continue;
  27580. pickingInfos.push(result);
  27581. }
  27582. return pickingInfos;
  27583. };
  27584. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27585. if (!BABYLON.PickingInfo) {
  27586. return null;
  27587. }
  27588. var pickingInfo = null;
  27589. if (!camera) {
  27590. if (!this.activeCamera) {
  27591. return null;
  27592. }
  27593. camera = this.activeCamera;
  27594. }
  27595. if (this.spriteManagers.length > 0) {
  27596. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27597. var spriteManager = this.spriteManagers[spriteIndex];
  27598. if (!spriteManager.isPickable) {
  27599. continue;
  27600. }
  27601. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27602. if (!result || !result.hit)
  27603. continue;
  27604. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27605. continue;
  27606. pickingInfo = result;
  27607. if (fastCheck) {
  27608. break;
  27609. }
  27610. }
  27611. }
  27612. return pickingInfo || new BABYLON.PickingInfo();
  27613. };
  27614. /** Launch a ray to try to pick a mesh in the scene
  27615. * @param x position on screen
  27616. * @param y position on screen
  27617. * @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
  27618. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27619. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27620. * @returns a PickingInfo
  27621. */
  27622. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27623. var _this = this;
  27624. if (!BABYLON.PickingInfo) {
  27625. return null;
  27626. }
  27627. return this._internalPick(function (world) {
  27628. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27629. return _this._tempPickingRay;
  27630. }, predicate, fastCheck);
  27631. };
  27632. /** Launch a ray to try to pick a sprite in the scene
  27633. * @param x position on screen
  27634. * @param y position on screen
  27635. * @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
  27636. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27637. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27638. * @returns a PickingInfo
  27639. */
  27640. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27641. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27642. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27643. };
  27644. /** Use the given ray to pick a mesh in the scene
  27645. * @param ray The ray to use to pick meshes
  27646. * @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
  27647. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27648. * @returns a PickingInfo
  27649. */
  27650. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27651. var _this = this;
  27652. return this._internalPick(function (world) {
  27653. if (!_this._pickWithRayInverseMatrix) {
  27654. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27655. }
  27656. world.invertToRef(_this._pickWithRayInverseMatrix);
  27657. if (!_this._cachedRayForTransform) {
  27658. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27659. }
  27660. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27661. return _this._cachedRayForTransform;
  27662. }, predicate, fastCheck);
  27663. };
  27664. /**
  27665. * Launch a ray to try to pick a mesh in the scene
  27666. * @param x X position on screen
  27667. * @param y Y position on screen
  27668. * @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
  27669. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27670. * @returns an array of PickingInfo
  27671. */
  27672. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27673. var _this = this;
  27674. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27675. };
  27676. /**
  27677. * Launch a ray to try to pick a mesh in the scene
  27678. * @param ray Ray to use
  27679. * @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
  27680. * @returns an array of PickingInfo
  27681. */
  27682. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27683. var _this = this;
  27684. return this._internalMultiPick(function (world) {
  27685. if (!_this._pickWithRayInverseMatrix) {
  27686. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27687. }
  27688. world.invertToRef(_this._pickWithRayInverseMatrix);
  27689. if (!_this._cachedRayForTransform) {
  27690. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27691. }
  27692. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27693. return _this._cachedRayForTransform;
  27694. }, predicate);
  27695. };
  27696. /**
  27697. * Force the value of meshUnderPointer
  27698. * @param mesh defines the mesh to use
  27699. */
  27700. Scene.prototype.setPointerOverMesh = function (mesh) {
  27701. if (this._pointerOverMesh === mesh) {
  27702. return;
  27703. }
  27704. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27705. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27706. }
  27707. this._pointerOverMesh = mesh;
  27708. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27709. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27710. }
  27711. };
  27712. /**
  27713. * Gets the mesh under the pointer
  27714. * @returns a Mesh or null if no mesh is under the pointer
  27715. */
  27716. Scene.prototype.getPointerOverMesh = function () {
  27717. return this._pointerOverMesh;
  27718. };
  27719. /**
  27720. * Force the sprite under the pointer
  27721. * @param sprite defines the sprite to use
  27722. */
  27723. Scene.prototype.setPointerOverSprite = function (sprite) {
  27724. if (this._pointerOverSprite === sprite) {
  27725. return;
  27726. }
  27727. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27728. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27729. }
  27730. this._pointerOverSprite = sprite;
  27731. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27732. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27733. }
  27734. };
  27735. /**
  27736. * Gets the sprite under the pointer
  27737. * @returns a Sprite or null if no sprite is under the pointer
  27738. */
  27739. Scene.prototype.getPointerOverSprite = function () {
  27740. return this._pointerOverSprite;
  27741. };
  27742. // Physics
  27743. /**
  27744. * Gets the current physics engine
  27745. * @returns a PhysicsEngine or null if none attached
  27746. */
  27747. Scene.prototype.getPhysicsEngine = function () {
  27748. return this._physicsEngine;
  27749. };
  27750. /**
  27751. * Enables physics to the current scene
  27752. * @param gravity defines the scene's gravity for the physics engine
  27753. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  27754. * @return a boolean indicating if the physics engine was initialized
  27755. */
  27756. Scene.prototype.enablePhysics = function (gravity, plugin) {
  27757. if (gravity === void 0) { gravity = null; }
  27758. if (this._physicsEngine) {
  27759. return true;
  27760. }
  27761. try {
  27762. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  27763. return true;
  27764. }
  27765. catch (e) {
  27766. BABYLON.Tools.Error(e.message);
  27767. return false;
  27768. }
  27769. };
  27770. /**
  27771. * Disables and disposes the physics engine associated with the scene
  27772. */
  27773. Scene.prototype.disablePhysicsEngine = function () {
  27774. if (!this._physicsEngine) {
  27775. return;
  27776. }
  27777. this._physicsEngine.dispose();
  27778. this._physicsEngine = null;
  27779. };
  27780. /**
  27781. * Gets a boolean indicating if there is an active physics engine
  27782. * @returns a boolean indicating if there is an active physics engine
  27783. */
  27784. Scene.prototype.isPhysicsEnabled = function () {
  27785. return this._physicsEngine !== undefined;
  27786. };
  27787. /**
  27788. * Deletes a physics compound impostor
  27789. * @param compound defines the compound to delete
  27790. */
  27791. Scene.prototype.deleteCompoundImpostor = function (compound) {
  27792. var mesh = compound.parts[0].mesh;
  27793. if (mesh.physicsImpostor) {
  27794. mesh.physicsImpostor.dispose();
  27795. mesh.physicsImpostor = null;
  27796. }
  27797. };
  27798. // Misc.
  27799. /** @ignore */
  27800. Scene.prototype._rebuildGeometries = function () {
  27801. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  27802. var geometry = _a[_i];
  27803. geometry._rebuild();
  27804. }
  27805. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  27806. var mesh = _c[_b];
  27807. mesh._rebuild();
  27808. }
  27809. if (this.postProcessManager) {
  27810. this.postProcessManager._rebuild();
  27811. }
  27812. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  27813. var layer = _e[_d];
  27814. layer._rebuild();
  27815. }
  27816. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  27817. var effectLayer = _g[_f];
  27818. effectLayer._rebuild();
  27819. }
  27820. if (this._boundingBoxRenderer) {
  27821. this._boundingBoxRenderer._rebuild();
  27822. }
  27823. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  27824. var system = _j[_h];
  27825. system.rebuild();
  27826. }
  27827. if (this._postProcessRenderPipelineManager) {
  27828. this._postProcessRenderPipelineManager._rebuild();
  27829. }
  27830. };
  27831. /** @ignore */
  27832. Scene.prototype._rebuildTextures = function () {
  27833. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27834. var texture = _a[_i];
  27835. texture._rebuild();
  27836. }
  27837. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27838. };
  27839. /**
  27840. * Creates a default light for the scene.
  27841. * @param replace Whether to replace the existing lights in the scene.
  27842. */
  27843. Scene.prototype.createDefaultLight = function (replace) {
  27844. if (replace === void 0) { replace = false; }
  27845. // Dispose existing light in replace mode.
  27846. if (replace) {
  27847. if (this.lights) {
  27848. for (var i = 0; i < this.lights.length; i++) {
  27849. this.lights[i].dispose();
  27850. }
  27851. }
  27852. }
  27853. // Light
  27854. if (this.lights.length === 0) {
  27855. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  27856. }
  27857. };
  27858. /**
  27859. * Creates a default camera for the scene.
  27860. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  27861. * @param replace Whether to replace the existing active camera in the scene.
  27862. * @param attachCameraControls Whether to attach camera controls to the canvas.
  27863. */
  27864. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  27865. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27866. if (replace === void 0) { replace = false; }
  27867. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27868. // Dispose existing camera in replace mode.
  27869. if (replace) {
  27870. if (this.activeCamera) {
  27871. this.activeCamera.dispose();
  27872. this.activeCamera = null;
  27873. }
  27874. }
  27875. // Camera
  27876. if (!this.activeCamera) {
  27877. var worldExtends = this.getWorldExtends();
  27878. var worldSize = worldExtends.max.subtract(worldExtends.min);
  27879. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  27880. var camera;
  27881. var radius = worldSize.length() * 1.5;
  27882. // empty scene scenario!
  27883. if (!isFinite(radius)) {
  27884. radius = 1;
  27885. worldCenter.copyFromFloats(0, 0, 0);
  27886. }
  27887. if (createArcRotateCamera) {
  27888. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  27889. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  27890. arcRotateCamera.wheelPrecision = 100 / radius;
  27891. camera = arcRotateCamera;
  27892. }
  27893. else {
  27894. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  27895. freeCamera.setTarget(worldCenter);
  27896. camera = freeCamera;
  27897. }
  27898. camera.minZ = radius * 0.01;
  27899. camera.maxZ = radius * 1000;
  27900. camera.speed = radius * 0.2;
  27901. this.activeCamera = camera;
  27902. var canvas = this.getEngine().getRenderingCanvas();
  27903. if (attachCameraControls && canvas) {
  27904. camera.attachControl(canvas);
  27905. }
  27906. }
  27907. };
  27908. /**
  27909. * Creates a default camera and a default light
  27910. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  27911. * @param replace defines if the camera and/or light will replace the existing ones
  27912. * @param attachCameraControls defines if attachControl will be called on the new camera
  27913. */
  27914. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  27915. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27916. if (replace === void 0) { replace = false; }
  27917. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27918. this.createDefaultLight(replace);
  27919. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  27920. };
  27921. /**
  27922. * Creates a new sky box
  27923. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27924. * @param environmentTexture defines the texture to use as environment texture
  27925. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  27926. * @param scale defines the overall scale of the skybox
  27927. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  27928. * @returns a new mesh holding the sky box
  27929. */
  27930. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  27931. if (pbr === void 0) { pbr = false; }
  27932. if (scale === void 0) { scale = 1000; }
  27933. if (blur === void 0) { blur = 0; }
  27934. if (environmentTexture) {
  27935. this.environmentTexture = environmentTexture;
  27936. }
  27937. if (!this.environmentTexture) {
  27938. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  27939. return null;
  27940. }
  27941. // Skybox
  27942. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  27943. if (pbr) {
  27944. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  27945. hdrSkyboxMaterial.backFaceCulling = false;
  27946. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27947. if (hdrSkyboxMaterial.reflectionTexture) {
  27948. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27949. }
  27950. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  27951. hdrSkyboxMaterial.disableLighting = true;
  27952. hdrSkyboxMaterial.twoSidedLighting = true;
  27953. hdrSkybox.infiniteDistance = true;
  27954. hdrSkybox.material = hdrSkyboxMaterial;
  27955. }
  27956. else {
  27957. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  27958. skyboxMaterial.backFaceCulling = false;
  27959. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27960. if (skyboxMaterial.reflectionTexture) {
  27961. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27962. }
  27963. skyboxMaterial.disableLighting = true;
  27964. hdrSkybox.infiniteDistance = true;
  27965. hdrSkybox.material = skyboxMaterial;
  27966. }
  27967. return hdrSkybox;
  27968. };
  27969. /**
  27970. * Creates a new environment
  27971. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27972. * @param options defines the options you can use to configure the environment
  27973. * @returns the new EnvironmentHelper
  27974. */
  27975. Scene.prototype.createDefaultEnvironment = function (options) {
  27976. if (BABYLON.EnvironmentHelper) {
  27977. return new BABYLON.EnvironmentHelper(options, this);
  27978. }
  27979. return null;
  27980. };
  27981. /**
  27982. * Creates a new VREXperienceHelper
  27983. * @see http://doc.babylonjs.com/how_to/webvr_helper
  27984. * @param webVROptions defines the options used to create the new VREXperienceHelper
  27985. * @returns a new VREXperienceHelper
  27986. */
  27987. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  27988. if (webVROptions === void 0) { webVROptions = {}; }
  27989. return new BABYLON.VRExperienceHelper(this, webVROptions);
  27990. };
  27991. // Tags
  27992. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  27993. if (tagsQuery === undefined) {
  27994. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  27995. return list;
  27996. }
  27997. var listByTags = [];
  27998. forEach = forEach || (function (item) { return; });
  27999. for (var i in list) {
  28000. var item = list[i];
  28001. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28002. listByTags.push(item);
  28003. forEach(item);
  28004. }
  28005. }
  28006. return listByTags;
  28007. };
  28008. /**
  28009. * Get a list of meshes by tags
  28010. * @param tagsQuery defines the tags query to use
  28011. * @param forEach defines a predicate used to filter results
  28012. * @returns an array of Mesh
  28013. */
  28014. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28015. return this._getByTags(this.meshes, tagsQuery, forEach);
  28016. };
  28017. /**
  28018. * Get a list of cameras by tags
  28019. * @param tagsQuery defines the tags query to use
  28020. * @param forEach defines a predicate used to filter results
  28021. * @returns an array of Camera
  28022. */
  28023. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28024. return this._getByTags(this.cameras, tagsQuery, forEach);
  28025. };
  28026. /**
  28027. * Get a list of lights by tags
  28028. * @param tagsQuery defines the tags query to use
  28029. * @param forEach defines a predicate used to filter results
  28030. * @returns an array of Light
  28031. */
  28032. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28033. return this._getByTags(this.lights, tagsQuery, forEach);
  28034. };
  28035. /**
  28036. * Get a list of materials by tags
  28037. * @param tagsQuery defines the tags query to use
  28038. * @param forEach defines a predicate used to filter results
  28039. * @returns an array of Material
  28040. */
  28041. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28042. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28043. };
  28044. /**
  28045. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28046. * This allowed control for front to back rendering or reversly depending of the special needs.
  28047. *
  28048. * @param renderingGroupId The rendering group id corresponding to its index
  28049. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28050. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28051. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28052. */
  28053. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28054. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28055. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28056. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28057. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28058. };
  28059. /**
  28060. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28061. *
  28062. * @param renderingGroupId The rendering group id corresponding to its index
  28063. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28064. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28065. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28066. */
  28067. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28068. if (depth === void 0) { depth = true; }
  28069. if (stencil === void 0) { stencil = true; }
  28070. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28071. };
  28072. /**
  28073. * Will flag all materials as dirty to trigger new shader compilation
  28074. * @param flag defines the flag used to specify which material part must be marked as dirty
  28075. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28076. */
  28077. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28078. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28079. var material = _a[_i];
  28080. if (predicate && !predicate(material)) {
  28081. continue;
  28082. }
  28083. material.markAsDirty(flag);
  28084. }
  28085. };
  28086. /** @ignore */
  28087. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28088. var _this = this;
  28089. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28090. this._activeRequests.push(request);
  28091. request.onCompleteObservable.add(function (request) {
  28092. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28093. });
  28094. return request;
  28095. };
  28096. /** @ignore */
  28097. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28098. var _this = this;
  28099. return new Promise(function (resolve, reject) {
  28100. _this._loadFile(url, function (data) {
  28101. resolve(data);
  28102. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28103. reject(exception);
  28104. });
  28105. });
  28106. };
  28107. // Statics
  28108. Scene._FOGMODE_NONE = 0;
  28109. Scene._FOGMODE_EXP = 1;
  28110. Scene._FOGMODE_EXP2 = 2;
  28111. Scene._FOGMODE_LINEAR = 3;
  28112. Scene._uniqueIdCounter = 0;
  28113. /**
  28114. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28115. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28116. */
  28117. Scene.MinDeltaTime = 1.0;
  28118. /**
  28119. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28120. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28121. */
  28122. Scene.MaxDeltaTime = 1000.0;
  28123. /** The distance in pixel that you have to move to prevent some events */
  28124. Scene.DragMovementThreshold = 10; // in pixels
  28125. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28126. Scene.LongPressDelay = 500; // in milliseconds
  28127. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28128. Scene.DoubleClickDelay = 300; // in milliseconds
  28129. /** If you need to check double click without raising a single click at first click, enable this flag */
  28130. Scene.ExclusiveDoubleClickMode = false;
  28131. return Scene;
  28132. }());
  28133. BABYLON.Scene = Scene;
  28134. })(BABYLON || (BABYLON = {}));
  28135. //# sourceMappingURL=babylon.scene.js.map
  28136. "use strict";
  28137. var BABYLON;
  28138. (function (BABYLON) {
  28139. /**
  28140. * Set of assets to keep when moving a scene into an asset container.
  28141. */
  28142. var KeepAssets = /** @class */ (function () {
  28143. function KeepAssets() {
  28144. /**
  28145. * Cameras to keep.
  28146. */
  28147. this.cameras = new Array();
  28148. /**
  28149. * Lights to keep.
  28150. */
  28151. this.lights = new Array();
  28152. /**
  28153. * Meshes to keep.
  28154. */
  28155. this.meshes = new Array();
  28156. /**
  28157. * Skeletons to keep.
  28158. */
  28159. this.skeletons = new Array();
  28160. /**
  28161. * ParticleSystems to keep.
  28162. */
  28163. this.particleSystems = new Array();
  28164. /**
  28165. * Animations to keep.
  28166. */
  28167. this.animations = new Array();
  28168. /**
  28169. * AnimationGroups to keep.
  28170. */
  28171. this.animationGroups = new Array();
  28172. /**
  28173. * MultiMaterials to keep.
  28174. */
  28175. this.multiMaterials = new Array();
  28176. /**
  28177. * Materials to keep.
  28178. */
  28179. this.materials = new Array();
  28180. /**
  28181. * MorphTargetManagers to keep.
  28182. */
  28183. this.morphTargetManagers = new Array();
  28184. /**
  28185. * Geometries to keep.
  28186. */
  28187. this.geometries = new Array();
  28188. /**
  28189. * TransformNodes to keep.
  28190. */
  28191. this.transformNodes = new Array();
  28192. /**
  28193. * LensFlareSystems to keep.
  28194. */
  28195. this.lensFlareSystems = new Array();
  28196. /**
  28197. * ShadowGenerators to keep.
  28198. */
  28199. this.shadowGenerators = new Array();
  28200. /**
  28201. * ActionManagers to keep.
  28202. */
  28203. this.actionManagers = new Array();
  28204. /**
  28205. * Sounds to keep.
  28206. */
  28207. this.sounds = new Array();
  28208. /**
  28209. * Textures to keep.
  28210. */
  28211. this.textures = new Array();
  28212. /**
  28213. * Effect layers to keep.
  28214. */
  28215. this.effectLayers = new Array();
  28216. }
  28217. return KeepAssets;
  28218. }());
  28219. BABYLON.KeepAssets = KeepAssets;
  28220. /**
  28221. * Container with a set of assets that can be added or removed from a scene.
  28222. */
  28223. var AssetContainer = /** @class */ (function () {
  28224. /**
  28225. * Instantiates an AssetContainer.
  28226. * @param scene The scene the AssetContainer belongs to.
  28227. */
  28228. function AssetContainer(scene) {
  28229. // Objects
  28230. /**
  28231. * Cameras populated in the container.
  28232. */
  28233. this.cameras = new Array();
  28234. /**
  28235. * Lights populated in the container.
  28236. */
  28237. this.lights = new Array();
  28238. /**
  28239. * Meshes populated in the container.
  28240. */
  28241. this.meshes = new Array();
  28242. /**
  28243. * Skeletons populated in the container.
  28244. */
  28245. this.skeletons = new Array();
  28246. /**
  28247. * ParticleSystems populated in the container.
  28248. */
  28249. this.particleSystems = new Array();
  28250. /**
  28251. * Animations populated in the container.
  28252. */
  28253. this.animations = new Array();
  28254. /**
  28255. * AnimationGroups populated in the container.
  28256. */
  28257. this.animationGroups = new Array();
  28258. /**
  28259. * MultiMaterials populated in the container.
  28260. */
  28261. this.multiMaterials = new Array();
  28262. /**
  28263. * Materials populated in the container.
  28264. */
  28265. this.materials = new Array();
  28266. /**
  28267. * MorphTargetManagers populated in the container.
  28268. */
  28269. this.morphTargetManagers = new Array();
  28270. /**
  28271. * Geometries populated in the container.
  28272. */
  28273. this.geometries = new Array();
  28274. /**
  28275. * TransformNodes populated in the container.
  28276. */
  28277. this.transformNodes = new Array();
  28278. /**
  28279. * LensFlareSystems populated in the container.
  28280. */
  28281. this.lensFlareSystems = new Array();
  28282. /**
  28283. * ShadowGenerators populated in the container.
  28284. */
  28285. this.shadowGenerators = new Array();
  28286. /**
  28287. * ActionManagers populated in the container.
  28288. */
  28289. this.actionManagers = new Array();
  28290. /**
  28291. * Sounds populated in the container.
  28292. */
  28293. this.sounds = new Array();
  28294. /**
  28295. * Textures populated in the container.
  28296. */
  28297. this.textures = new Array();
  28298. /**
  28299. * Effect layers populated in the container.
  28300. */
  28301. this.effectLayers = new Array();
  28302. this.scene = scene;
  28303. }
  28304. /**
  28305. * Adds all the assets from the container to the scene.
  28306. */
  28307. AssetContainer.prototype.addAllToScene = function () {
  28308. var _this = this;
  28309. this.cameras.forEach(function (o) {
  28310. _this.scene.addCamera(o);
  28311. });
  28312. this.lights.forEach(function (o) {
  28313. _this.scene.addLight(o);
  28314. });
  28315. this.meshes.forEach(function (o) {
  28316. _this.scene.addMesh(o);
  28317. });
  28318. this.skeletons.forEach(function (o) {
  28319. _this.scene.addSkeleton(o);
  28320. });
  28321. this.particleSystems.forEach(function (o) {
  28322. _this.scene.addParticleSystem(o);
  28323. });
  28324. this.animations.forEach(function (o) {
  28325. _this.scene.addAnimation(o);
  28326. });
  28327. this.animationGroups.forEach(function (o) {
  28328. _this.scene.addAnimationGroup(o);
  28329. });
  28330. this.multiMaterials.forEach(function (o) {
  28331. _this.scene.addMultiMaterial(o);
  28332. });
  28333. this.materials.forEach(function (o) {
  28334. _this.scene.addMaterial(o);
  28335. });
  28336. this.morphTargetManagers.forEach(function (o) {
  28337. _this.scene.addMorphTargetManager(o);
  28338. });
  28339. this.geometries.forEach(function (o) {
  28340. _this.scene.addGeometry(o);
  28341. });
  28342. this.transformNodes.forEach(function (o) {
  28343. _this.scene.addTransformNode(o);
  28344. });
  28345. this.lensFlareSystems.forEach(function (o) {
  28346. _this.scene.addLensFlareSystem(o);
  28347. });
  28348. this.actionManagers.forEach(function (o) {
  28349. _this.scene.addActionManager(o);
  28350. });
  28351. this.sounds.forEach(function (o) {
  28352. o.play();
  28353. o.autoplay = true;
  28354. _this.scene.mainSoundTrack.AddSound(o);
  28355. });
  28356. this.textures.forEach(function (o) {
  28357. _this.scene.addTexture(o);
  28358. });
  28359. this.effectLayers.forEach(function (o) {
  28360. _this.scene.addEffectLayer(o);
  28361. });
  28362. };
  28363. /**
  28364. * Removes all the assets in the container from the scene
  28365. */
  28366. AssetContainer.prototype.removeAllFromScene = function () {
  28367. var _this = this;
  28368. this.cameras.forEach(function (o) {
  28369. _this.scene.removeCamera(o);
  28370. });
  28371. this.lights.forEach(function (o) {
  28372. _this.scene.removeLight(o);
  28373. });
  28374. this.meshes.forEach(function (o) {
  28375. _this.scene.removeMesh(o);
  28376. });
  28377. this.skeletons.forEach(function (o) {
  28378. _this.scene.removeSkeleton(o);
  28379. });
  28380. this.particleSystems.forEach(function (o) {
  28381. _this.scene.removeParticleSystem(o);
  28382. });
  28383. this.animations.forEach(function (o) {
  28384. _this.scene.removeAnimation(o);
  28385. });
  28386. this.animationGroups.forEach(function (o) {
  28387. _this.scene.removeAnimationGroup(o);
  28388. });
  28389. this.multiMaterials.forEach(function (o) {
  28390. _this.scene.removeMultiMaterial(o);
  28391. });
  28392. this.materials.forEach(function (o) {
  28393. _this.scene.removeMaterial(o);
  28394. });
  28395. this.morphTargetManagers.forEach(function (o) {
  28396. _this.scene.removeMorphTargetManager(o);
  28397. });
  28398. this.geometries.forEach(function (o) {
  28399. _this.scene.removeGeometry(o);
  28400. });
  28401. this.transformNodes.forEach(function (o) {
  28402. _this.scene.removeTransformNode(o);
  28403. });
  28404. this.lensFlareSystems.forEach(function (o) {
  28405. _this.scene.removeLensFlareSystem(o);
  28406. });
  28407. this.actionManagers.forEach(function (o) {
  28408. _this.scene.removeActionManager(o);
  28409. });
  28410. this.sounds.forEach(function (o) {
  28411. o.stop();
  28412. o.autoplay = false;
  28413. _this.scene.mainSoundTrack.RemoveSound(o);
  28414. });
  28415. this.textures.forEach(function (o) {
  28416. _this.scene.removeTexture(o);
  28417. });
  28418. this.effectLayers.forEach(function (o) {
  28419. _this.scene.removeEffectLayer(o);
  28420. });
  28421. };
  28422. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28423. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28424. var asset = sourceAssets_1[_i];
  28425. var move = true;
  28426. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28427. var keepAsset = keepAssets_1[_a];
  28428. if (asset === keepAsset) {
  28429. move = false;
  28430. break;
  28431. }
  28432. }
  28433. if (move) {
  28434. targetAssets.push(asset);
  28435. }
  28436. }
  28437. };
  28438. /**
  28439. * Removes all the assets contained in the scene and adds them to the container.
  28440. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28441. */
  28442. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28443. if (keepAssets === undefined) {
  28444. keepAssets = new KeepAssets();
  28445. }
  28446. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28447. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28448. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28449. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28450. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28451. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28452. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28453. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28454. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28455. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28456. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28457. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28458. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28459. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28460. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28461. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28462. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28463. this.removeAllFromScene();
  28464. };
  28465. return AssetContainer;
  28466. }());
  28467. BABYLON.AssetContainer = AssetContainer;
  28468. })(BABYLON || (BABYLON = {}));
  28469. //# sourceMappingURL=babylon.assetContainer.js.map
  28470. "use strict";
  28471. var BABYLON;
  28472. (function (BABYLON) {
  28473. var Buffer = /** @class */ (function () {
  28474. /**
  28475. * Constructor
  28476. * @param engine the engine
  28477. * @param data the data to use for this buffer
  28478. * @param updatable whether the data is updatable
  28479. * @param stride the stride (optional)
  28480. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28481. * @param instanced whether the buffer is instanced (optional)
  28482. * @param useBytes set to true if the stride in in bytes (optional)
  28483. */
  28484. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28485. if (stride === void 0) { stride = 0; }
  28486. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28487. if (instanced === void 0) { instanced = false; }
  28488. if (useBytes === void 0) { useBytes = false; }
  28489. if (engine instanceof BABYLON.Mesh) {
  28490. this._engine = engine.getScene().getEngine();
  28491. }
  28492. else {
  28493. this._engine = engine;
  28494. }
  28495. this._updatable = updatable;
  28496. this._instanced = instanced;
  28497. this._data = data;
  28498. this.byteStride = useBytes ? stride : stride * 4;
  28499. if (!postponeInternalCreation) {
  28500. this.create();
  28501. }
  28502. }
  28503. /**
  28504. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28505. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28506. * @param offset defines offset in the buffer (0 by default)
  28507. * @param size defines the size in floats of attributes (position is 3 for instance)
  28508. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28509. * @param instanced defines if the vertex buffer contains indexed data
  28510. * @param useBytes defines if the offset and stride are in bytes
  28511. * @returns the new vertex buffer
  28512. */
  28513. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28514. if (useBytes === void 0) { useBytes = false; }
  28515. var byteOffset = useBytes ? offset : offset * 4;
  28516. var byteStride = stride ? (useBytes ? stride : stride * 4) : this.byteStride;
  28517. // a lot of these parameters are ignored as they are overriden by the buffer
  28518. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28519. };
  28520. // Properties
  28521. Buffer.prototype.isUpdatable = function () {
  28522. return this._updatable;
  28523. };
  28524. Buffer.prototype.getData = function () {
  28525. return this._data;
  28526. };
  28527. Buffer.prototype.getBuffer = function () {
  28528. return this._buffer;
  28529. };
  28530. /**
  28531. * Gets the stride in float32 units (i.e. byte stride / 4).
  28532. * May not be an integer if the byte stride is not divisible by 4.
  28533. * DEPRECATED. Use byteStride instead.
  28534. * @returns the stride in float32 units
  28535. */
  28536. Buffer.prototype.getStrideSize = function () {
  28537. return this.byteStride / 4;
  28538. };
  28539. // Methods
  28540. Buffer.prototype.create = function (data) {
  28541. if (data === void 0) { data = null; }
  28542. if (!data && this._buffer) {
  28543. return; // nothing to do
  28544. }
  28545. data = data || this._data;
  28546. if (!data) {
  28547. return;
  28548. }
  28549. if (!this._buffer) {
  28550. if (this._updatable) {
  28551. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28552. this._data = data;
  28553. }
  28554. else {
  28555. this._buffer = this._engine.createVertexBuffer(data);
  28556. }
  28557. }
  28558. else if (this._updatable) {
  28559. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28560. this._data = data;
  28561. }
  28562. };
  28563. Buffer.prototype._rebuild = function () {
  28564. this._buffer = null;
  28565. this.create(this._data);
  28566. };
  28567. Buffer.prototype.update = function (data) {
  28568. this.create(data);
  28569. };
  28570. /**
  28571. * Updates the data directly.
  28572. * @param data the new data
  28573. * @param offset the new offset
  28574. * @param vertexCount the vertex count (optional)
  28575. * @param useBytes set to true if the offset is in bytes
  28576. */
  28577. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28578. if (useBytes === void 0) { useBytes = false; }
  28579. if (!this._buffer) {
  28580. return;
  28581. }
  28582. if (this._updatable) {
  28583. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * 4, (vertexCount ? vertexCount * this.byteStride : undefined));
  28584. this._data = null;
  28585. }
  28586. };
  28587. Buffer.prototype.dispose = function () {
  28588. if (!this._buffer) {
  28589. return;
  28590. }
  28591. if (this._engine._releaseBuffer(this._buffer)) {
  28592. this._buffer = null;
  28593. }
  28594. };
  28595. return Buffer;
  28596. }());
  28597. BABYLON.Buffer = Buffer;
  28598. })(BABYLON || (BABYLON = {}));
  28599. //# sourceMappingURL=babylon.buffer.js.map
  28600. "use strict";
  28601. var BABYLON;
  28602. (function (BABYLON) {
  28603. var VertexBuffer = /** @class */ (function () {
  28604. /**
  28605. * Constructor
  28606. * @param engine the engine
  28607. * @param data the data to use for this vertex buffer
  28608. * @param kind the vertex buffer kind
  28609. * @param updatable whether the data is updatable
  28610. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28611. * @param stride the stride (optional)
  28612. * @param instanced whether the buffer is instanced (optional)
  28613. * @param offset the offset of the data (optional)
  28614. * @param size the number of components (optional)
  28615. * @param type the type of the component (optional)
  28616. * @param normalized whether the data contains normalized data (optional)
  28617. * @param useBytes set to true if stride and offset are in bytes (optional)
  28618. */
  28619. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28620. if (normalized === void 0) { normalized = false; }
  28621. if (useBytes === void 0) { useBytes = false; }
  28622. if (data instanceof BABYLON.Buffer) {
  28623. this._buffer = data;
  28624. this._ownsBuffer = false;
  28625. }
  28626. else {
  28627. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28628. this._ownsBuffer = true;
  28629. }
  28630. this._kind = kind;
  28631. if (type == undefined) {
  28632. var data_1 = this.getData();
  28633. this.type = VertexBuffer.FLOAT;
  28634. if (data_1 instanceof Int8Array)
  28635. this.type = VertexBuffer.BYTE;
  28636. else if (data_1 instanceof Uint8Array)
  28637. this.type = VertexBuffer.UNSIGNED_BYTE;
  28638. else if (data_1 instanceof Int16Array)
  28639. this.type = VertexBuffer.SHORT;
  28640. else if (data_1 instanceof Uint16Array)
  28641. this.type = VertexBuffer.UNSIGNED_SHORT;
  28642. else if (data_1 instanceof Int32Array)
  28643. this.type = VertexBuffer.INT;
  28644. else if (data_1 instanceof Uint32Array)
  28645. this.type = VertexBuffer.UNSIGNED_INT;
  28646. }
  28647. else {
  28648. this.type = type;
  28649. }
  28650. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28651. if (useBytes) {
  28652. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28653. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28654. this.byteOffset = offset || 0;
  28655. }
  28656. else {
  28657. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28658. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28659. this.byteOffset = (offset || 0) * typeByteLength;
  28660. }
  28661. this.normalized = normalized;
  28662. this._instanced = instanced !== undefined ? instanced : false;
  28663. this._instanceDivisor = instanced ? 1 : 0;
  28664. }
  28665. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28666. /**
  28667. * Gets or sets the instance divisor when in instanced mode
  28668. */
  28669. get: function () {
  28670. return this._instanceDivisor;
  28671. },
  28672. set: function (value) {
  28673. this._instanceDivisor = value;
  28674. if (value == 0) {
  28675. this._instanced = false;
  28676. }
  28677. else {
  28678. this._instanced = true;
  28679. }
  28680. },
  28681. enumerable: true,
  28682. configurable: true
  28683. });
  28684. VertexBuffer.prototype._rebuild = function () {
  28685. if (!this._buffer) {
  28686. return;
  28687. }
  28688. this._buffer._rebuild();
  28689. };
  28690. /**
  28691. * Returns the kind of the VertexBuffer (string).
  28692. */
  28693. VertexBuffer.prototype.getKind = function () {
  28694. return this._kind;
  28695. };
  28696. // Properties
  28697. /**
  28698. * Boolean : is the VertexBuffer updatable ?
  28699. */
  28700. VertexBuffer.prototype.isUpdatable = function () {
  28701. return this._buffer.isUpdatable();
  28702. };
  28703. /**
  28704. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28705. */
  28706. VertexBuffer.prototype.getData = function () {
  28707. return this._buffer.getData();
  28708. };
  28709. /**
  28710. * Returns the WebGLBuffer associated to the VertexBuffer.
  28711. */
  28712. VertexBuffer.prototype.getBuffer = function () {
  28713. return this._buffer.getBuffer();
  28714. };
  28715. /**
  28716. * Returns the stride as a multiple of the type byte length.
  28717. * DEPRECATED. Use byteStride instead.
  28718. */
  28719. VertexBuffer.prototype.getStrideSize = function () {
  28720. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28721. };
  28722. /**
  28723. * Returns the offset as a multiple of the type byte length.
  28724. * DEPRECATED. Use byteOffset instead.
  28725. */
  28726. VertexBuffer.prototype.getOffset = function () {
  28727. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28728. };
  28729. /**
  28730. * Returns the number of components per vertex attribute (integer).
  28731. */
  28732. VertexBuffer.prototype.getSize = function () {
  28733. return this._size;
  28734. };
  28735. /**
  28736. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28737. */
  28738. VertexBuffer.prototype.getIsInstanced = function () {
  28739. return this._instanced;
  28740. };
  28741. /**
  28742. * Returns the instancing divisor, zero for non-instanced (integer).
  28743. */
  28744. VertexBuffer.prototype.getInstanceDivisor = function () {
  28745. return this._instanceDivisor;
  28746. };
  28747. // Methods
  28748. /**
  28749. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28750. * Returns the created WebGLBuffer.
  28751. */
  28752. VertexBuffer.prototype.create = function (data) {
  28753. return this._buffer.create(data);
  28754. };
  28755. /**
  28756. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28757. * This function will create a new buffer if the current one is not updatable
  28758. * Returns the updated WebGLBuffer.
  28759. */
  28760. VertexBuffer.prototype.update = function (data) {
  28761. return this._buffer.update(data);
  28762. };
  28763. /**
  28764. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28765. * Returns the directly updated WebGLBuffer.
  28766. */
  28767. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  28768. return this._buffer.updateDirectly(data, offset);
  28769. };
  28770. /**
  28771. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28772. */
  28773. VertexBuffer.prototype.dispose = function () {
  28774. if (this._ownsBuffer) {
  28775. this._buffer.dispose();
  28776. }
  28777. };
  28778. /**
  28779. * Enumerates each value of this vertex buffer as numbers.
  28780. * @param count the number of values to enumerate
  28781. * @param callback the callback function called for each value
  28782. */
  28783. VertexBuffer.prototype.forEach = function (count, callback) {
  28784. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28785. };
  28786. Object.defineProperty(VertexBuffer, "PositionKind", {
  28787. get: function () {
  28788. return VertexBuffer._PositionKind;
  28789. },
  28790. enumerable: true,
  28791. configurable: true
  28792. });
  28793. Object.defineProperty(VertexBuffer, "NormalKind", {
  28794. get: function () {
  28795. return VertexBuffer._NormalKind;
  28796. },
  28797. enumerable: true,
  28798. configurable: true
  28799. });
  28800. Object.defineProperty(VertexBuffer, "TangentKind", {
  28801. get: function () {
  28802. return VertexBuffer._TangentKind;
  28803. },
  28804. enumerable: true,
  28805. configurable: true
  28806. });
  28807. Object.defineProperty(VertexBuffer, "UVKind", {
  28808. get: function () {
  28809. return VertexBuffer._UVKind;
  28810. },
  28811. enumerable: true,
  28812. configurable: true
  28813. });
  28814. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28815. get: function () {
  28816. return VertexBuffer._UV2Kind;
  28817. },
  28818. enumerable: true,
  28819. configurable: true
  28820. });
  28821. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28822. get: function () {
  28823. return VertexBuffer._UV3Kind;
  28824. },
  28825. enumerable: true,
  28826. configurable: true
  28827. });
  28828. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28829. get: function () {
  28830. return VertexBuffer._UV4Kind;
  28831. },
  28832. enumerable: true,
  28833. configurable: true
  28834. });
  28835. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28836. get: function () {
  28837. return VertexBuffer._UV5Kind;
  28838. },
  28839. enumerable: true,
  28840. configurable: true
  28841. });
  28842. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28843. get: function () {
  28844. return VertexBuffer._UV6Kind;
  28845. },
  28846. enumerable: true,
  28847. configurable: true
  28848. });
  28849. Object.defineProperty(VertexBuffer, "ColorKind", {
  28850. get: function () {
  28851. return VertexBuffer._ColorKind;
  28852. },
  28853. enumerable: true,
  28854. configurable: true
  28855. });
  28856. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28857. get: function () {
  28858. return VertexBuffer._MatricesIndicesKind;
  28859. },
  28860. enumerable: true,
  28861. configurable: true
  28862. });
  28863. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28864. get: function () {
  28865. return VertexBuffer._MatricesWeightsKind;
  28866. },
  28867. enumerable: true,
  28868. configurable: true
  28869. });
  28870. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  28871. get: function () {
  28872. return VertexBuffer._MatricesIndicesExtraKind;
  28873. },
  28874. enumerable: true,
  28875. configurable: true
  28876. });
  28877. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  28878. get: function () {
  28879. return VertexBuffer._MatricesWeightsExtraKind;
  28880. },
  28881. enumerable: true,
  28882. configurable: true
  28883. });
  28884. /**
  28885. * Deduces the stride given a kind.
  28886. * @param kind The kind string to deduce
  28887. * @returns The deduced stride
  28888. */
  28889. VertexBuffer.DeduceStride = function (kind) {
  28890. switch (kind) {
  28891. case VertexBuffer.UVKind:
  28892. case VertexBuffer.UV2Kind:
  28893. case VertexBuffer.UV3Kind:
  28894. case VertexBuffer.UV4Kind:
  28895. case VertexBuffer.UV5Kind:
  28896. case VertexBuffer.UV6Kind:
  28897. return 2;
  28898. case VertexBuffer.NormalKind:
  28899. case VertexBuffer.PositionKind:
  28900. return 3;
  28901. case VertexBuffer.ColorKind:
  28902. case VertexBuffer.MatricesIndicesKind:
  28903. case VertexBuffer.MatricesIndicesExtraKind:
  28904. case VertexBuffer.MatricesWeightsKind:
  28905. case VertexBuffer.MatricesWeightsExtraKind:
  28906. case VertexBuffer.TangentKind:
  28907. return 4;
  28908. default:
  28909. throw new Error("Invalid kind '" + kind + "'");
  28910. }
  28911. };
  28912. /**
  28913. * Gets the byte length of the given type.
  28914. * @param type the type
  28915. * @returns the number of bytes
  28916. */
  28917. VertexBuffer.GetTypeByteLength = function (type) {
  28918. switch (type) {
  28919. case VertexBuffer.BYTE:
  28920. case VertexBuffer.UNSIGNED_BYTE:
  28921. return 1;
  28922. case VertexBuffer.SHORT:
  28923. case VertexBuffer.UNSIGNED_SHORT:
  28924. return 2;
  28925. case VertexBuffer.INT:
  28926. case VertexBuffer.FLOAT:
  28927. return 4;
  28928. default:
  28929. throw new Error("Invalid type '" + type + "'");
  28930. }
  28931. };
  28932. /**
  28933. * Enumerates each value of the given parameters as numbers.
  28934. * @param data the data to enumerate
  28935. * @param byteOffset the byte offset of the data
  28936. * @param byteStride the byte stride of the data
  28937. * @param componentCount the number of components per element
  28938. * @param componentType the type of the component
  28939. * @param count the total number of components
  28940. * @param normalized whether the data is normalized
  28941. * @param callback the callback function called for each value
  28942. */
  28943. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  28944. if (data instanceof Array) {
  28945. var offset = byteOffset / 4;
  28946. var stride = byteStride / 4;
  28947. for (var index = 0; index < count; index += componentCount) {
  28948. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28949. callback(data[offset + componentIndex], index + componentIndex);
  28950. }
  28951. offset += stride;
  28952. }
  28953. }
  28954. else {
  28955. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  28956. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  28957. for (var index = 0; index < count; index += componentCount) {
  28958. var componentByteOffset = byteOffset;
  28959. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28960. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  28961. callback(value, index + componentIndex);
  28962. componentByteOffset += componentByteLength;
  28963. }
  28964. byteOffset += byteStride;
  28965. }
  28966. }
  28967. };
  28968. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  28969. switch (type) {
  28970. case VertexBuffer.BYTE: {
  28971. var value = dataView.getInt8(byteOffset);
  28972. if (normalized) {
  28973. value = (value + 0.5) / 127.5;
  28974. }
  28975. return value;
  28976. }
  28977. case VertexBuffer.UNSIGNED_BYTE: {
  28978. var value = dataView.getUint8(byteOffset);
  28979. if (normalized) {
  28980. value = value / 255;
  28981. }
  28982. return value;
  28983. }
  28984. case VertexBuffer.SHORT: {
  28985. var value = dataView.getInt16(byteOffset, true);
  28986. if (normalized) {
  28987. value = (value + 0.5) / 16383.5;
  28988. }
  28989. return value;
  28990. }
  28991. case VertexBuffer.UNSIGNED_SHORT: {
  28992. var value = dataView.getUint16(byteOffset, true);
  28993. if (normalized) {
  28994. value = value / 65535;
  28995. }
  28996. return value;
  28997. }
  28998. case VertexBuffer.FLOAT: {
  28999. return dataView.getFloat32(byteOffset, true);
  29000. }
  29001. default: {
  29002. throw new Error("Invalid component type " + type);
  29003. }
  29004. }
  29005. };
  29006. /**
  29007. * The byte type.
  29008. */
  29009. VertexBuffer.BYTE = 5120;
  29010. /**
  29011. * The unsigned byte type.
  29012. */
  29013. VertexBuffer.UNSIGNED_BYTE = 5121;
  29014. /**
  29015. * The short type.
  29016. */
  29017. VertexBuffer.SHORT = 5122;
  29018. /**
  29019. * The unsigned short type.
  29020. */
  29021. VertexBuffer.UNSIGNED_SHORT = 5123;
  29022. /**
  29023. * The integer type.
  29024. */
  29025. VertexBuffer.INT = 5124;
  29026. /**
  29027. * The unsigned integer type.
  29028. */
  29029. VertexBuffer.UNSIGNED_INT = 5125;
  29030. /**
  29031. * The float type.
  29032. */
  29033. VertexBuffer.FLOAT = 5126;
  29034. // Enums
  29035. VertexBuffer._PositionKind = "position";
  29036. VertexBuffer._NormalKind = "normal";
  29037. VertexBuffer._TangentKind = "tangent";
  29038. VertexBuffer._UVKind = "uv";
  29039. VertexBuffer._UV2Kind = "uv2";
  29040. VertexBuffer._UV3Kind = "uv3";
  29041. VertexBuffer._UV4Kind = "uv4";
  29042. VertexBuffer._UV5Kind = "uv5";
  29043. VertexBuffer._UV6Kind = "uv6";
  29044. VertexBuffer._ColorKind = "color";
  29045. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29046. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29047. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29048. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29049. return VertexBuffer;
  29050. }());
  29051. BABYLON.VertexBuffer = VertexBuffer;
  29052. })(BABYLON || (BABYLON = {}));
  29053. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29054. "use strict";
  29055. var BABYLON;
  29056. (function (BABYLON) {
  29057. /**
  29058. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29059. */
  29060. var DummyInternalTextureTracker = /** @class */ (function () {
  29061. function DummyInternalTextureTracker() {
  29062. /**
  29063. * Gets or set the previous tracker in the list
  29064. */
  29065. this.previous = null;
  29066. /**
  29067. * Gets or set the next tracker in the list
  29068. */
  29069. this.next = null;
  29070. }
  29071. return DummyInternalTextureTracker;
  29072. }());
  29073. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29074. })(BABYLON || (BABYLON = {}));
  29075. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29076. "use strict";
  29077. var BABYLON;
  29078. (function (BABYLON) {
  29079. /**
  29080. * Class used to store data associated with WebGL texture data for the engine
  29081. * This class should not be used directly
  29082. */
  29083. var InternalTexture = /** @class */ (function () {
  29084. /**
  29085. * Creates a new InternalTexture
  29086. * @param engine defines the engine to use
  29087. * @param dataSource defines the type of data that will be used
  29088. */
  29089. function InternalTexture(engine, dataSource) {
  29090. /**
  29091. * Observable called when the texture is loaded
  29092. */
  29093. this.onLoadedObservable = new BABYLON.Observable();
  29094. /**
  29095. * Gets or set the previous tracker in the list
  29096. */
  29097. this.previous = null;
  29098. /**
  29099. * Gets or set the next tracker in the list
  29100. */
  29101. this.next = null;
  29102. // Private
  29103. /** @ignore */
  29104. this._initialSlot = -1;
  29105. /** @ignore */
  29106. this._designatedSlot = -1;
  29107. /** @ignore */
  29108. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29109. /** @ignore */
  29110. this._comparisonFunction = 0;
  29111. /** @ignore */
  29112. this._references = 1;
  29113. this._engine = engine;
  29114. this._dataSource = dataSource;
  29115. this._webGLTexture = engine._createTexture();
  29116. }
  29117. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29118. /**
  29119. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29120. */
  29121. get: function () {
  29122. return this._dataSource;
  29123. },
  29124. enumerable: true,
  29125. configurable: true
  29126. });
  29127. /**
  29128. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29129. */
  29130. InternalTexture.prototype.incrementReferences = function () {
  29131. this._references++;
  29132. };
  29133. /**
  29134. * Change the size of the texture (not the size of the content)
  29135. * @param width defines the new width
  29136. * @param height defines the new height
  29137. * @param depth defines the new depth (1 by default)
  29138. */
  29139. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29140. if (depth === void 0) { depth = 1; }
  29141. this.width = width;
  29142. this.height = height;
  29143. this.depth = depth;
  29144. this.baseWidth = width;
  29145. this.baseHeight = height;
  29146. this.baseDepth = depth;
  29147. this._size = width * height * depth;
  29148. };
  29149. /** @ignore */
  29150. InternalTexture.prototype._rebuild = function () {
  29151. var _this = this;
  29152. var proxy;
  29153. this.isReady = false;
  29154. this._cachedCoordinatesMode = null;
  29155. this._cachedWrapU = null;
  29156. this._cachedWrapV = null;
  29157. this._cachedAnisotropicFilteringLevel = null;
  29158. switch (this._dataSource) {
  29159. case InternalTexture.DATASOURCE_TEMP:
  29160. return;
  29161. case InternalTexture.DATASOURCE_URL:
  29162. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29163. _this.isReady = true;
  29164. }, null, this._buffer, undefined, this.format);
  29165. proxy._swapAndDie(this);
  29166. return;
  29167. case InternalTexture.DATASOURCE_RAW:
  29168. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29169. proxy._swapAndDie(this);
  29170. this.isReady = true;
  29171. return;
  29172. case InternalTexture.DATASOURCE_RAW3D:
  29173. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29174. proxy._swapAndDie(this);
  29175. this.isReady = true;
  29176. return;
  29177. case InternalTexture.DATASOURCE_DYNAMIC:
  29178. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29179. proxy._swapAndDie(this);
  29180. // The engine will make sure to update content so no need to flag it as isReady = true
  29181. return;
  29182. case InternalTexture.DATASOURCE_RENDERTARGET:
  29183. var options = new BABYLON.RenderTargetCreationOptions();
  29184. options.generateDepthBuffer = this._generateDepthBuffer;
  29185. options.generateMipMaps = this.generateMipMaps;
  29186. options.generateStencilBuffer = this._generateStencilBuffer;
  29187. options.samplingMode = this.samplingMode;
  29188. options.type = this.type;
  29189. if (this.isCube) {
  29190. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29191. }
  29192. else {
  29193. var size = {
  29194. width: this.width,
  29195. height: this.height
  29196. };
  29197. proxy = this._engine.createRenderTargetTexture(size, options);
  29198. }
  29199. proxy._swapAndDie(this);
  29200. this.isReady = true;
  29201. return;
  29202. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29203. var depthTextureOptions = {
  29204. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29205. comparisonFunction: this._comparisonFunction,
  29206. generateStencil: this._generateStencilBuffer,
  29207. isCube: this.isCube
  29208. };
  29209. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29210. proxy._swapAndDie(this);
  29211. this.isReady = true;
  29212. return;
  29213. case InternalTexture.DATASOURCE_CUBE:
  29214. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29215. _this.isReady = true;
  29216. }, null, this.format, this._extension);
  29217. proxy._swapAndDie(this);
  29218. return;
  29219. case InternalTexture.DATASOURCE_CUBERAW:
  29220. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29221. proxy._swapAndDie(this);
  29222. this.isReady = true;
  29223. return;
  29224. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29225. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29226. if (proxy) {
  29227. proxy._swapAndDie(_this);
  29228. }
  29229. _this.isReady = true;
  29230. }, null, this.format, this._extension);
  29231. return;
  29232. }
  29233. };
  29234. InternalTexture.prototype._swapAndDie = function (target) {
  29235. target._webGLTexture = this._webGLTexture;
  29236. if (this._framebuffer) {
  29237. target._framebuffer = this._framebuffer;
  29238. }
  29239. if (this._depthStencilBuffer) {
  29240. target._depthStencilBuffer = this._depthStencilBuffer;
  29241. }
  29242. if (this._lodTextureHigh) {
  29243. if (target._lodTextureHigh) {
  29244. target._lodTextureHigh.dispose();
  29245. }
  29246. target._lodTextureHigh = this._lodTextureHigh;
  29247. }
  29248. if (this._lodTextureMid) {
  29249. if (target._lodTextureMid) {
  29250. target._lodTextureMid.dispose();
  29251. }
  29252. target._lodTextureMid = this._lodTextureMid;
  29253. }
  29254. if (this._lodTextureLow) {
  29255. if (target._lodTextureLow) {
  29256. target._lodTextureLow.dispose();
  29257. }
  29258. target._lodTextureLow = this._lodTextureLow;
  29259. }
  29260. var cache = this._engine.getLoadedTexturesCache();
  29261. var index = cache.indexOf(this);
  29262. if (index !== -1) {
  29263. cache.splice(index, 1);
  29264. }
  29265. };
  29266. /**
  29267. * Dispose the current allocated resources
  29268. */
  29269. InternalTexture.prototype.dispose = function () {
  29270. if (!this._webGLTexture) {
  29271. return;
  29272. }
  29273. this._references--;
  29274. if (this._references === 0) {
  29275. this._engine._releaseTexture(this);
  29276. this._webGLTexture = null;
  29277. this.previous = null;
  29278. this.next = null;
  29279. }
  29280. };
  29281. /**
  29282. * The source of the texture data is unknown
  29283. */
  29284. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29285. /**
  29286. * Texture data comes from an URL
  29287. */
  29288. InternalTexture.DATASOURCE_URL = 1;
  29289. /**
  29290. * Texture data is only used for temporary storage
  29291. */
  29292. InternalTexture.DATASOURCE_TEMP = 2;
  29293. /**
  29294. * Texture data comes from raw data (ArrayBuffer)
  29295. */
  29296. InternalTexture.DATASOURCE_RAW = 3;
  29297. /**
  29298. * Texture content is dynamic (video or dynamic texture)
  29299. */
  29300. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29301. /**
  29302. * Texture content is generated by rendering to it
  29303. */
  29304. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29305. /**
  29306. * Texture content is part of a multi render target process
  29307. */
  29308. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29309. /**
  29310. * Texture data comes from a cube data file
  29311. */
  29312. InternalTexture.DATASOURCE_CUBE = 7;
  29313. /**
  29314. * Texture data comes from a raw cube data
  29315. */
  29316. InternalTexture.DATASOURCE_CUBERAW = 8;
  29317. /**
  29318. * Texture data come from a prefiltered cube data file
  29319. */
  29320. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29321. /**
  29322. * Texture content is raw 3D data
  29323. */
  29324. InternalTexture.DATASOURCE_RAW3D = 10;
  29325. /**
  29326. * Texture content is a depth texture
  29327. */
  29328. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29329. return InternalTexture;
  29330. }());
  29331. BABYLON.InternalTexture = InternalTexture;
  29332. })(BABYLON || (BABYLON = {}));
  29333. //# sourceMappingURL=babylon.internalTexture.js.map
  29334. "use strict";
  29335. var BABYLON;
  29336. (function (BABYLON) {
  29337. var BaseTexture = /** @class */ (function () {
  29338. function BaseTexture(scene) {
  29339. this._hasAlpha = false;
  29340. this.getAlphaFromRGB = false;
  29341. this.level = 1;
  29342. this.coordinatesIndex = 0;
  29343. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29344. /**
  29345. * | Value | Type | Description |
  29346. * | ----- | ------------------ | ----------- |
  29347. * | 0 | CLAMP_ADDRESSMODE | |
  29348. * | 1 | WRAP_ADDRESSMODE | |
  29349. * | 2 | MIRROR_ADDRESSMODE | |
  29350. */
  29351. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29352. /**
  29353. * | Value | Type | Description |
  29354. * | ----- | ------------------ | ----------- |
  29355. * | 0 | CLAMP_ADDRESSMODE | |
  29356. * | 1 | WRAP_ADDRESSMODE | |
  29357. * | 2 | MIRROR_ADDRESSMODE | |
  29358. */
  29359. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29360. /**
  29361. * | Value | Type | Description |
  29362. * | ----- | ------------------ | ----------- |
  29363. * | 0 | CLAMP_ADDRESSMODE | |
  29364. * | 1 | WRAP_ADDRESSMODE | |
  29365. * | 2 | MIRROR_ADDRESSMODE | |
  29366. */
  29367. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29368. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29369. this.isCube = false;
  29370. this.is3D = false;
  29371. this.gammaSpace = true;
  29372. this.invertZ = false;
  29373. this.lodLevelInAlpha = false;
  29374. this.lodGenerationOffset = 0.0;
  29375. this.lodGenerationScale = 0.8;
  29376. this.isRenderTarget = false;
  29377. this.animations = new Array();
  29378. /**
  29379. * An event triggered when the texture is disposed.
  29380. */
  29381. this.onDisposeObservable = new BABYLON.Observable();
  29382. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29383. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29384. if (this._scene) {
  29385. this._scene.textures.push(this);
  29386. }
  29387. this._uid = null;
  29388. }
  29389. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29390. get: function () {
  29391. return this._hasAlpha;
  29392. },
  29393. set: function (value) {
  29394. if (this._hasAlpha === value) {
  29395. return;
  29396. }
  29397. this._hasAlpha = value;
  29398. if (this._scene) {
  29399. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29400. }
  29401. },
  29402. enumerable: true,
  29403. configurable: true
  29404. });
  29405. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29406. get: function () {
  29407. return this._coordinatesMode;
  29408. },
  29409. /**
  29410. * How a texture is mapped.
  29411. *
  29412. * | Value | Type | Description |
  29413. * | ----- | ----------------------------------- | ----------- |
  29414. * | 0 | EXPLICIT_MODE | |
  29415. * | 1 | SPHERICAL_MODE | |
  29416. * | 2 | PLANAR_MODE | |
  29417. * | 3 | CUBIC_MODE | |
  29418. * | 4 | PROJECTION_MODE | |
  29419. * | 5 | SKYBOX_MODE | |
  29420. * | 6 | INVCUBIC_MODE | |
  29421. * | 7 | EQUIRECTANGULAR_MODE | |
  29422. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29423. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29424. */
  29425. set: function (value) {
  29426. if (this._coordinatesMode === value) {
  29427. return;
  29428. }
  29429. this._coordinatesMode = value;
  29430. if (this._scene) {
  29431. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29432. }
  29433. },
  29434. enumerable: true,
  29435. configurable: true
  29436. });
  29437. Object.defineProperty(BaseTexture.prototype, "uid", {
  29438. get: function () {
  29439. if (!this._uid) {
  29440. this._uid = BABYLON.Tools.RandomId();
  29441. }
  29442. return this._uid;
  29443. },
  29444. enumerable: true,
  29445. configurable: true
  29446. });
  29447. BaseTexture.prototype.toString = function () {
  29448. return this.name;
  29449. };
  29450. BaseTexture.prototype.getClassName = function () {
  29451. return "BaseTexture";
  29452. };
  29453. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29454. set: function (callback) {
  29455. if (this._onDisposeObserver) {
  29456. this.onDisposeObservable.remove(this._onDisposeObserver);
  29457. }
  29458. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29459. },
  29460. enumerable: true,
  29461. configurable: true
  29462. });
  29463. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29464. get: function () {
  29465. return true;
  29466. },
  29467. enumerable: true,
  29468. configurable: true
  29469. });
  29470. BaseTexture.prototype.getScene = function () {
  29471. return this._scene;
  29472. };
  29473. BaseTexture.prototype.getTextureMatrix = function () {
  29474. return BABYLON.Matrix.IdentityReadOnly;
  29475. };
  29476. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29477. return BABYLON.Matrix.IdentityReadOnly;
  29478. };
  29479. BaseTexture.prototype.getInternalTexture = function () {
  29480. return this._texture;
  29481. };
  29482. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29483. return !this.isBlocking || this.isReady();
  29484. };
  29485. BaseTexture.prototype.isReady = function () {
  29486. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29487. this.delayLoad();
  29488. return false;
  29489. }
  29490. if (this._texture) {
  29491. return this._texture.isReady;
  29492. }
  29493. return false;
  29494. };
  29495. BaseTexture.prototype.getSize = function () {
  29496. if (this._texture && this._texture.width) {
  29497. return new BABYLON.Size(this._texture.width, this._texture.height);
  29498. }
  29499. if (this._texture && this._texture._size) {
  29500. return new BABYLON.Size(this._texture._size, this._texture._size);
  29501. }
  29502. return BABYLON.Size.Zero();
  29503. };
  29504. BaseTexture.prototype.getBaseSize = function () {
  29505. if (!this.isReady() || !this._texture)
  29506. return BABYLON.Size.Zero();
  29507. if (this._texture._size) {
  29508. return new BABYLON.Size(this._texture._size, this._texture._size);
  29509. }
  29510. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29511. };
  29512. BaseTexture.prototype.scale = function (ratio) {
  29513. };
  29514. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29515. get: function () {
  29516. return false;
  29517. },
  29518. enumerable: true,
  29519. configurable: true
  29520. });
  29521. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29522. if (!this._scene) {
  29523. return null;
  29524. }
  29525. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29526. for (var index = 0; index < texturesCache.length; index++) {
  29527. var texturesCacheEntry = texturesCache[index];
  29528. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29529. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29530. texturesCacheEntry.incrementReferences();
  29531. return texturesCacheEntry;
  29532. }
  29533. }
  29534. }
  29535. return null;
  29536. };
  29537. BaseTexture.prototype._rebuild = function () {
  29538. };
  29539. BaseTexture.prototype.delayLoad = function () {
  29540. };
  29541. BaseTexture.prototype.clone = function () {
  29542. return null;
  29543. };
  29544. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29545. get: function () {
  29546. if (!this._texture) {
  29547. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29548. }
  29549. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29550. },
  29551. enumerable: true,
  29552. configurable: true
  29553. });
  29554. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29555. get: function () {
  29556. if (!this._texture) {
  29557. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29558. }
  29559. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29560. },
  29561. enumerable: true,
  29562. configurable: true
  29563. });
  29564. BaseTexture.prototype.readPixels = function (faceIndex) {
  29565. if (faceIndex === void 0) { faceIndex = 0; }
  29566. if (!this._texture) {
  29567. return null;
  29568. }
  29569. var size = this.getSize();
  29570. var scene = this.getScene();
  29571. if (!scene) {
  29572. return null;
  29573. }
  29574. var engine = scene.getEngine();
  29575. if (this._texture.isCube) {
  29576. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29577. }
  29578. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29579. };
  29580. BaseTexture.prototype.releaseInternalTexture = function () {
  29581. if (this._texture) {
  29582. this._texture.dispose();
  29583. this._texture = null;
  29584. }
  29585. };
  29586. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29587. get: function () {
  29588. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29589. return null;
  29590. }
  29591. if (!this._texture._sphericalPolynomial) {
  29592. this._texture._sphericalPolynomial =
  29593. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29594. }
  29595. return this._texture._sphericalPolynomial;
  29596. },
  29597. set: function (value) {
  29598. if (this._texture) {
  29599. this._texture._sphericalPolynomial = value;
  29600. }
  29601. },
  29602. enumerable: true,
  29603. configurable: true
  29604. });
  29605. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29606. get: function () {
  29607. if (this._texture) {
  29608. return this._texture._lodTextureHigh;
  29609. }
  29610. return null;
  29611. },
  29612. enumerable: true,
  29613. configurable: true
  29614. });
  29615. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29616. get: function () {
  29617. if (this._texture) {
  29618. return this._texture._lodTextureMid;
  29619. }
  29620. return null;
  29621. },
  29622. enumerable: true,
  29623. configurable: true
  29624. });
  29625. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29626. get: function () {
  29627. if (this._texture) {
  29628. return this._texture._lodTextureLow;
  29629. }
  29630. return null;
  29631. },
  29632. enumerable: true,
  29633. configurable: true
  29634. });
  29635. BaseTexture.prototype.dispose = function () {
  29636. if (!this._scene) {
  29637. return;
  29638. }
  29639. // Animations
  29640. this._scene.stopAnimation(this);
  29641. // Remove from scene
  29642. this._scene._removePendingData(this);
  29643. var index = this._scene.textures.indexOf(this);
  29644. if (index >= 0) {
  29645. this._scene.textures.splice(index, 1);
  29646. }
  29647. if (this._texture === undefined) {
  29648. return;
  29649. }
  29650. // Release
  29651. this.releaseInternalTexture();
  29652. // Callback
  29653. this.onDisposeObservable.notifyObservers(this);
  29654. this.onDisposeObservable.clear();
  29655. };
  29656. BaseTexture.prototype.serialize = function () {
  29657. if (!this.name) {
  29658. return null;
  29659. }
  29660. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29661. // Animations
  29662. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29663. return serializationObject;
  29664. };
  29665. BaseTexture.WhenAllReady = function (textures, callback) {
  29666. var numRemaining = textures.length;
  29667. if (numRemaining === 0) {
  29668. callback();
  29669. return;
  29670. }
  29671. var _loop_1 = function () {
  29672. texture = textures[i];
  29673. if (texture.isReady()) {
  29674. if (--numRemaining === 0) {
  29675. callback();
  29676. }
  29677. }
  29678. else {
  29679. onLoadObservable = texture.onLoadObservable;
  29680. var onLoadCallback_1 = function () {
  29681. onLoadObservable.removeCallback(onLoadCallback_1);
  29682. if (--numRemaining === 0) {
  29683. callback();
  29684. }
  29685. };
  29686. onLoadObservable.add(onLoadCallback_1);
  29687. }
  29688. };
  29689. var texture, onLoadObservable;
  29690. for (var i = 0; i < textures.length; i++) {
  29691. _loop_1();
  29692. }
  29693. };
  29694. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29695. __decorate([
  29696. BABYLON.serialize()
  29697. ], BaseTexture.prototype, "name", void 0);
  29698. __decorate([
  29699. BABYLON.serialize("hasAlpha")
  29700. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29701. __decorate([
  29702. BABYLON.serialize()
  29703. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29704. __decorate([
  29705. BABYLON.serialize()
  29706. ], BaseTexture.prototype, "level", void 0);
  29707. __decorate([
  29708. BABYLON.serialize()
  29709. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29710. __decorate([
  29711. BABYLON.serialize("coordinatesMode")
  29712. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29713. __decorate([
  29714. BABYLON.serialize()
  29715. ], BaseTexture.prototype, "wrapU", void 0);
  29716. __decorate([
  29717. BABYLON.serialize()
  29718. ], BaseTexture.prototype, "wrapV", void 0);
  29719. __decorate([
  29720. BABYLON.serialize()
  29721. ], BaseTexture.prototype, "wrapR", void 0);
  29722. __decorate([
  29723. BABYLON.serialize()
  29724. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29725. __decorate([
  29726. BABYLON.serialize()
  29727. ], BaseTexture.prototype, "isCube", void 0);
  29728. __decorate([
  29729. BABYLON.serialize()
  29730. ], BaseTexture.prototype, "is3D", void 0);
  29731. __decorate([
  29732. BABYLON.serialize()
  29733. ], BaseTexture.prototype, "gammaSpace", void 0);
  29734. __decorate([
  29735. BABYLON.serialize()
  29736. ], BaseTexture.prototype, "invertZ", void 0);
  29737. __decorate([
  29738. BABYLON.serialize()
  29739. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29740. __decorate([
  29741. BABYLON.serialize()
  29742. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  29743. __decorate([
  29744. BABYLON.serialize()
  29745. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  29746. __decorate([
  29747. BABYLON.serialize()
  29748. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29749. return BaseTexture;
  29750. }());
  29751. BABYLON.BaseTexture = BaseTexture;
  29752. })(BABYLON || (BABYLON = {}));
  29753. //# sourceMappingURL=babylon.baseTexture.js.map
  29754. "use strict";
  29755. var BABYLON;
  29756. (function (BABYLON) {
  29757. var Texture = /** @class */ (function (_super) {
  29758. __extends(Texture, _super);
  29759. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29760. if (noMipmap === void 0) { noMipmap = false; }
  29761. if (invertY === void 0) { invertY = true; }
  29762. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29763. if (onLoad === void 0) { onLoad = null; }
  29764. if (onError === void 0) { onError = null; }
  29765. if (buffer === void 0) { buffer = null; }
  29766. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29767. var _this = _super.call(this, scene) || this;
  29768. _this.uOffset = 0;
  29769. _this.vOffset = 0;
  29770. _this.uScale = 1.0;
  29771. _this.vScale = 1.0;
  29772. _this.uAng = 0;
  29773. _this.vAng = 0;
  29774. _this.wAng = 0;
  29775. _this._isBlocking = true;
  29776. _this.name = url || "";
  29777. _this.url = url;
  29778. _this._noMipmap = noMipmap;
  29779. _this._invertY = invertY;
  29780. _this._samplingMode = samplingMode;
  29781. _this._buffer = buffer;
  29782. _this._deleteBuffer = deleteBuffer;
  29783. if (format) {
  29784. _this._format = format;
  29785. }
  29786. scene = _this.getScene();
  29787. if (!scene) {
  29788. return _this;
  29789. }
  29790. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  29791. var load = function () {
  29792. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  29793. _this.onLoadObservable.notifyObservers(_this);
  29794. }
  29795. if (onLoad) {
  29796. onLoad();
  29797. }
  29798. if (!_this.isBlocking && scene) {
  29799. scene.resetCachedMaterial();
  29800. }
  29801. };
  29802. if (!_this.url) {
  29803. _this._delayedOnLoad = load;
  29804. _this._delayedOnError = onError;
  29805. return _this;
  29806. }
  29807. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  29808. if (!_this._texture) {
  29809. if (!scene.useDelayedTextureLoading) {
  29810. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  29811. if (deleteBuffer) {
  29812. delete _this._buffer;
  29813. }
  29814. }
  29815. else {
  29816. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29817. _this._delayedOnLoad = load;
  29818. _this._delayedOnError = onError;
  29819. }
  29820. }
  29821. else {
  29822. if (_this._texture.isReady) {
  29823. BABYLON.Tools.SetImmediate(function () { return load(); });
  29824. }
  29825. else {
  29826. _this._texture.onLoadedObservable.add(load);
  29827. }
  29828. }
  29829. return _this;
  29830. }
  29831. Object.defineProperty(Texture.prototype, "noMipmap", {
  29832. get: function () {
  29833. return this._noMipmap;
  29834. },
  29835. enumerable: true,
  29836. configurable: true
  29837. });
  29838. Object.defineProperty(Texture.prototype, "isBlocking", {
  29839. get: function () {
  29840. return this._isBlocking;
  29841. },
  29842. set: function (value) {
  29843. this._isBlocking = value;
  29844. },
  29845. enumerable: true,
  29846. configurable: true
  29847. });
  29848. Object.defineProperty(Texture.prototype, "samplingMode", {
  29849. get: function () {
  29850. return this._samplingMode;
  29851. },
  29852. enumerable: true,
  29853. configurable: true
  29854. });
  29855. Texture.prototype.updateURL = function (url) {
  29856. this.url = url;
  29857. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29858. this.delayLoad();
  29859. };
  29860. Texture.prototype.delayLoad = function () {
  29861. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29862. return;
  29863. }
  29864. var scene = this.getScene();
  29865. if (!scene) {
  29866. return;
  29867. }
  29868. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29869. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  29870. if (!this._texture) {
  29871. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  29872. if (this._deleteBuffer) {
  29873. delete this._buffer;
  29874. }
  29875. }
  29876. else {
  29877. if (this._delayedOnLoad) {
  29878. if (this._texture.isReady) {
  29879. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  29880. }
  29881. else {
  29882. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  29883. }
  29884. }
  29885. }
  29886. this._delayedOnLoad = null;
  29887. this._delayedOnError = null;
  29888. };
  29889. Texture.prototype.updateSamplingMode = function (samplingMode) {
  29890. if (!this._texture) {
  29891. return;
  29892. }
  29893. var scene = this.getScene();
  29894. if (!scene) {
  29895. return;
  29896. }
  29897. this._samplingMode = samplingMode;
  29898. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  29899. };
  29900. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  29901. x *= this.uScale;
  29902. y *= this.vScale;
  29903. x -= 0.5 * this.uScale;
  29904. y -= 0.5 * this.vScale;
  29905. z -= 0.5;
  29906. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  29907. t.x += 0.5 * this.uScale + this.uOffset;
  29908. t.y += 0.5 * this.vScale + this.vOffset;
  29909. t.z += 0.5;
  29910. };
  29911. Texture.prototype.getTextureMatrix = function () {
  29912. var _this = this;
  29913. if (this.uOffset === this._cachedUOffset &&
  29914. this.vOffset === this._cachedVOffset &&
  29915. this.uScale === this._cachedUScale &&
  29916. this.vScale === this._cachedVScale &&
  29917. this.uAng === this._cachedUAng &&
  29918. this.vAng === this._cachedVAng &&
  29919. this.wAng === this._cachedWAng) {
  29920. return this._cachedTextureMatrix;
  29921. }
  29922. this._cachedUOffset = this.uOffset;
  29923. this._cachedVOffset = this.vOffset;
  29924. this._cachedUScale = this.uScale;
  29925. this._cachedVScale = this.vScale;
  29926. this._cachedUAng = this.uAng;
  29927. this._cachedVAng = this.vAng;
  29928. this._cachedWAng = this.wAng;
  29929. if (!this._cachedTextureMatrix) {
  29930. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29931. this._rowGenerationMatrix = new BABYLON.Matrix();
  29932. this._t0 = BABYLON.Vector3.Zero();
  29933. this._t1 = BABYLON.Vector3.Zero();
  29934. this._t2 = BABYLON.Vector3.Zero();
  29935. }
  29936. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  29937. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  29938. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  29939. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  29940. this._t1.subtractInPlace(this._t0);
  29941. this._t2.subtractInPlace(this._t0);
  29942. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29943. this._cachedTextureMatrix.m[0] = this._t1.x;
  29944. this._cachedTextureMatrix.m[1] = this._t1.y;
  29945. this._cachedTextureMatrix.m[2] = this._t1.z;
  29946. this._cachedTextureMatrix.m[4] = this._t2.x;
  29947. this._cachedTextureMatrix.m[5] = this._t2.y;
  29948. this._cachedTextureMatrix.m[6] = this._t2.z;
  29949. this._cachedTextureMatrix.m[8] = this._t0.x;
  29950. this._cachedTextureMatrix.m[9] = this._t0.y;
  29951. this._cachedTextureMatrix.m[10] = this._t0.z;
  29952. var scene = this.getScene();
  29953. if (!scene) {
  29954. return this._cachedTextureMatrix;
  29955. }
  29956. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  29957. return mat.hasTexture(_this);
  29958. });
  29959. return this._cachedTextureMatrix;
  29960. };
  29961. Texture.prototype.getReflectionTextureMatrix = function () {
  29962. var _this = this;
  29963. var scene = this.getScene();
  29964. if (!scene) {
  29965. return this._cachedTextureMatrix;
  29966. }
  29967. if (this.uOffset === this._cachedUOffset &&
  29968. this.vOffset === this._cachedVOffset &&
  29969. this.uScale === this._cachedUScale &&
  29970. this.vScale === this._cachedVScale &&
  29971. this.coordinatesMode === this._cachedCoordinatesMode) {
  29972. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  29973. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  29974. return this._cachedTextureMatrix;
  29975. }
  29976. }
  29977. else {
  29978. return this._cachedTextureMatrix;
  29979. }
  29980. }
  29981. if (!this._cachedTextureMatrix) {
  29982. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29983. }
  29984. if (!this._projectionModeMatrix) {
  29985. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  29986. }
  29987. this._cachedUOffset = this.uOffset;
  29988. this._cachedVOffset = this.vOffset;
  29989. this._cachedUScale = this.uScale;
  29990. this._cachedVScale = this.vScale;
  29991. this._cachedCoordinatesMode = this.coordinatesMode;
  29992. switch (this.coordinatesMode) {
  29993. case Texture.PLANAR_MODE:
  29994. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29995. this._cachedTextureMatrix[0] = this.uScale;
  29996. this._cachedTextureMatrix[5] = this.vScale;
  29997. this._cachedTextureMatrix[12] = this.uOffset;
  29998. this._cachedTextureMatrix[13] = this.vOffset;
  29999. break;
  30000. case Texture.PROJECTION_MODE:
  30001. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30002. this._projectionModeMatrix.m[0] = 0.5;
  30003. this._projectionModeMatrix.m[5] = -0.5;
  30004. this._projectionModeMatrix.m[10] = 0.0;
  30005. this._projectionModeMatrix.m[12] = 0.5;
  30006. this._projectionModeMatrix.m[13] = 0.5;
  30007. this._projectionModeMatrix.m[14] = 1.0;
  30008. this._projectionModeMatrix.m[15] = 1.0;
  30009. var projectionMatrix = scene.getProjectionMatrix();
  30010. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30011. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30012. break;
  30013. default:
  30014. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30015. break;
  30016. }
  30017. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30018. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30019. });
  30020. return this._cachedTextureMatrix;
  30021. };
  30022. Texture.prototype.clone = function () {
  30023. var _this = this;
  30024. return BABYLON.SerializationHelper.Clone(function () {
  30025. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30026. }, this);
  30027. };
  30028. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30029. get: function () {
  30030. if (!this._onLoadObservable) {
  30031. this._onLoadObservable = new BABYLON.Observable();
  30032. }
  30033. return this._onLoadObservable;
  30034. },
  30035. enumerable: true,
  30036. configurable: true
  30037. });
  30038. Texture.prototype.serialize = function () {
  30039. var serializationObject = _super.prototype.serialize.call(this);
  30040. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30041. serializationObject.base64String = this._buffer;
  30042. serializationObject.name = serializationObject.name.replace("data:", "");
  30043. }
  30044. serializationObject.invertY = this._invertY;
  30045. serializationObject.samplingMode = this.samplingMode;
  30046. return serializationObject;
  30047. };
  30048. Texture.prototype.getClassName = function () {
  30049. return "Texture";
  30050. };
  30051. Texture.prototype.dispose = function () {
  30052. _super.prototype.dispose.call(this);
  30053. if (this.onLoadObservable) {
  30054. this.onLoadObservable.clear();
  30055. this._onLoadObservable = null;
  30056. }
  30057. this._delayedOnLoad = null;
  30058. this._delayedOnError = null;
  30059. };
  30060. // Statics
  30061. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30062. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30063. if (onLoad === void 0) { onLoad = null; }
  30064. if (onError === void 0) { onError = null; }
  30065. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30066. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30067. };
  30068. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30069. if (parsedTexture.customType) {
  30070. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30071. // Update Sampling Mode
  30072. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30073. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30074. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30075. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30076. }
  30077. }
  30078. return parsedCustomTexture;
  30079. }
  30080. if (parsedTexture.isCube) {
  30081. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30082. }
  30083. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30084. return null;
  30085. }
  30086. var texture = BABYLON.SerializationHelper.Parse(function () {
  30087. var generateMipMaps = true;
  30088. if (parsedTexture.noMipmap) {
  30089. generateMipMaps = false;
  30090. }
  30091. if (parsedTexture.mirrorPlane) {
  30092. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30093. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30094. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30095. return mirrorTexture;
  30096. }
  30097. else if (parsedTexture.isRenderTarget) {
  30098. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30099. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30100. return renderTargetTexture;
  30101. }
  30102. else {
  30103. var texture;
  30104. if (parsedTexture.base64String) {
  30105. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30106. }
  30107. else {
  30108. var url = rootUrl + parsedTexture.name;
  30109. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30110. url = parsedTexture.url;
  30111. }
  30112. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30113. }
  30114. return texture;
  30115. }
  30116. }, parsedTexture, scene);
  30117. // Update Sampling Mode
  30118. if (parsedTexture.samplingMode) {
  30119. var sampling = parsedTexture.samplingMode;
  30120. if (texture._samplingMode !== sampling) {
  30121. texture.updateSamplingMode(sampling);
  30122. }
  30123. }
  30124. // Animations
  30125. if (parsedTexture.animations) {
  30126. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30127. var parsedAnimation = parsedTexture.animations[animationIndex];
  30128. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30129. }
  30130. }
  30131. return texture;
  30132. };
  30133. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30134. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30135. if (noMipmap === void 0) { noMipmap = false; }
  30136. if (invertY === void 0) { invertY = true; }
  30137. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30138. if (onLoad === void 0) { onLoad = null; }
  30139. if (onError === void 0) { onError = null; }
  30140. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30141. if (name.substr(0, 5) !== "data:") {
  30142. name = "data:" + name;
  30143. }
  30144. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30145. };
  30146. // Constants
  30147. Texture.NEAREST_SAMPLINGMODE = 1;
  30148. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30149. Texture.BILINEAR_SAMPLINGMODE = 2;
  30150. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30151. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30152. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30153. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30154. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30155. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30156. Texture.NEAREST_LINEAR = 7;
  30157. Texture.NEAREST_NEAREST = 8;
  30158. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30159. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30160. Texture.LINEAR_LINEAR = 11;
  30161. Texture.LINEAR_NEAREST = 12;
  30162. Texture.EXPLICIT_MODE = 0;
  30163. Texture.SPHERICAL_MODE = 1;
  30164. Texture.PLANAR_MODE = 2;
  30165. Texture.CUBIC_MODE = 3;
  30166. Texture.PROJECTION_MODE = 4;
  30167. Texture.SKYBOX_MODE = 5;
  30168. Texture.INVCUBIC_MODE = 6;
  30169. Texture.EQUIRECTANGULAR_MODE = 7;
  30170. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30171. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30172. Texture.CLAMP_ADDRESSMODE = 0;
  30173. Texture.WRAP_ADDRESSMODE = 1;
  30174. Texture.MIRROR_ADDRESSMODE = 2;
  30175. /**
  30176. * 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
  30177. */
  30178. Texture.UseSerializedUrlIfAny = false;
  30179. __decorate([
  30180. BABYLON.serialize()
  30181. ], Texture.prototype, "url", void 0);
  30182. __decorate([
  30183. BABYLON.serialize()
  30184. ], Texture.prototype, "uOffset", void 0);
  30185. __decorate([
  30186. BABYLON.serialize()
  30187. ], Texture.prototype, "vOffset", void 0);
  30188. __decorate([
  30189. BABYLON.serialize()
  30190. ], Texture.prototype, "uScale", void 0);
  30191. __decorate([
  30192. BABYLON.serialize()
  30193. ], Texture.prototype, "vScale", void 0);
  30194. __decorate([
  30195. BABYLON.serialize()
  30196. ], Texture.prototype, "uAng", void 0);
  30197. __decorate([
  30198. BABYLON.serialize()
  30199. ], Texture.prototype, "vAng", void 0);
  30200. __decorate([
  30201. BABYLON.serialize()
  30202. ], Texture.prototype, "wAng", void 0);
  30203. __decorate([
  30204. BABYLON.serialize()
  30205. ], Texture.prototype, "isBlocking", null);
  30206. return Texture;
  30207. }(BABYLON.BaseTexture));
  30208. BABYLON.Texture = Texture;
  30209. })(BABYLON || (BABYLON = {}));
  30210. //# sourceMappingURL=babylon.texture.js.map
  30211. "use strict";
  30212. var BABYLON;
  30213. (function (BABYLON) {
  30214. var _InstancesBatch = /** @class */ (function () {
  30215. function _InstancesBatch() {
  30216. this.mustReturn = false;
  30217. this.visibleInstances = new Array();
  30218. this.renderSelf = new Array();
  30219. }
  30220. return _InstancesBatch;
  30221. }());
  30222. BABYLON._InstancesBatch = _InstancesBatch;
  30223. var Mesh = /** @class */ (function (_super) {
  30224. __extends(Mesh, _super);
  30225. /**
  30226. * @constructor
  30227. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30228. * @param {Scene} scene The scene to add this mesh to.
  30229. * @param {Node} parent The parent of this mesh, if it has one
  30230. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30231. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30232. * When false, achieved by calling a clone(), also passing False.
  30233. * This will make creation of children, recursive.
  30234. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30235. */
  30236. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30237. if (scene === void 0) { scene = null; }
  30238. if (parent === void 0) { parent = null; }
  30239. if (source === void 0) { source = null; }
  30240. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30241. var _this = _super.call(this, name, scene) || this;
  30242. // Events
  30243. /**
  30244. * An event triggered before rendering the mesh
  30245. */
  30246. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30247. /**
  30248. * An event triggered after rendering the mesh
  30249. */
  30250. _this.onAfterRenderObservable = new BABYLON.Observable();
  30251. /**
  30252. * An event triggered before drawing the mesh
  30253. */
  30254. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30255. // Members
  30256. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30257. _this.instances = new Array();
  30258. _this._LODLevels = new Array();
  30259. _this._visibleInstances = {};
  30260. _this._renderIdForInstances = new Array();
  30261. _this._batchCache = new _InstancesBatch();
  30262. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30263. // Use by builder only to know what orientation were the mesh build in.
  30264. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30265. _this.overrideMaterialSideOrientation = null;
  30266. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30267. // Will be used to save a source mesh reference, If any
  30268. _this._source = null;
  30269. scene = _this.getScene();
  30270. if (source) {
  30271. // Source mesh
  30272. _this._source = source;
  30273. // Geometry
  30274. if (source._geometry) {
  30275. source._geometry.applyToMesh(_this);
  30276. }
  30277. // Deep copy
  30278. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30279. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30280. // Metadata
  30281. if (source.metadata && source.metadata.clone) {
  30282. _this.metadata = source.metadata.clone();
  30283. }
  30284. else {
  30285. _this.metadata = source.metadata;
  30286. }
  30287. // Tags
  30288. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30289. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30290. }
  30291. // Parent
  30292. _this.parent = source.parent;
  30293. // Pivot
  30294. _this.setPivotMatrix(source.getPivotMatrix());
  30295. _this.id = name + "." + source.id;
  30296. // Material
  30297. _this.material = source.material;
  30298. var index;
  30299. if (!doNotCloneChildren) {
  30300. // Children
  30301. var directDescendants = source.getDescendants(true);
  30302. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30303. var child = directDescendants[index_1];
  30304. if (child.clone) {
  30305. child.clone(name + "." + child.name, _this);
  30306. }
  30307. }
  30308. }
  30309. // Physics clone
  30310. var physicsEngine = _this.getScene().getPhysicsEngine();
  30311. if (clonePhysicsImpostor && physicsEngine) {
  30312. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30313. if (impostor) {
  30314. _this.physicsImpostor = impostor.clone(_this);
  30315. }
  30316. }
  30317. // Particles
  30318. for (index = 0; index < scene.particleSystems.length; index++) {
  30319. var system = scene.particleSystems[index];
  30320. if (system.emitter === source) {
  30321. system.clone(system.name, _this);
  30322. }
  30323. }
  30324. _this.computeWorldMatrix(true);
  30325. }
  30326. // Parent
  30327. if (parent !== null) {
  30328. _this.parent = parent;
  30329. }
  30330. return _this;
  30331. }
  30332. Object.defineProperty(Mesh, "FRONTSIDE", {
  30333. /**
  30334. * Mesh side orientation : usually the external or front surface
  30335. */
  30336. get: function () {
  30337. return Mesh._FRONTSIDE;
  30338. },
  30339. enumerable: true,
  30340. configurable: true
  30341. });
  30342. Object.defineProperty(Mesh, "BACKSIDE", {
  30343. /**
  30344. * Mesh side orientation : usually the internal or back surface
  30345. */
  30346. get: function () {
  30347. return Mesh._BACKSIDE;
  30348. },
  30349. enumerable: true,
  30350. configurable: true
  30351. });
  30352. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30353. /**
  30354. * Mesh side orientation : both internal and external or front and back surfaces
  30355. */
  30356. get: function () {
  30357. return Mesh._DOUBLESIDE;
  30358. },
  30359. enumerable: true,
  30360. configurable: true
  30361. });
  30362. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30363. /**
  30364. * Mesh side orientation : by default, `FRONTSIDE`
  30365. */
  30366. get: function () {
  30367. return Mesh._DEFAULTSIDE;
  30368. },
  30369. enumerable: true,
  30370. configurable: true
  30371. });
  30372. Object.defineProperty(Mesh, "NO_CAP", {
  30373. /**
  30374. * Mesh cap setting : no cap
  30375. */
  30376. get: function () {
  30377. return Mesh._NO_CAP;
  30378. },
  30379. enumerable: true,
  30380. configurable: true
  30381. });
  30382. Object.defineProperty(Mesh, "CAP_START", {
  30383. /**
  30384. * Mesh cap setting : one cap at the beginning of the mesh
  30385. */
  30386. get: function () {
  30387. return Mesh._CAP_START;
  30388. },
  30389. enumerable: true,
  30390. configurable: true
  30391. });
  30392. Object.defineProperty(Mesh, "CAP_END", {
  30393. /**
  30394. * Mesh cap setting : one cap at the end of the mesh
  30395. */
  30396. get: function () {
  30397. return Mesh._CAP_END;
  30398. },
  30399. enumerable: true,
  30400. configurable: true
  30401. });
  30402. Object.defineProperty(Mesh, "CAP_ALL", {
  30403. /**
  30404. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30405. */
  30406. get: function () {
  30407. return Mesh._CAP_ALL;
  30408. },
  30409. enumerable: true,
  30410. configurable: true
  30411. });
  30412. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30413. set: function (callback) {
  30414. if (this._onBeforeDrawObserver) {
  30415. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30416. }
  30417. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30418. },
  30419. enumerable: true,
  30420. configurable: true
  30421. });
  30422. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30423. get: function () {
  30424. return this._morphTargetManager;
  30425. },
  30426. set: function (value) {
  30427. if (this._morphTargetManager === value) {
  30428. return;
  30429. }
  30430. this._morphTargetManager = value;
  30431. this._syncGeometryWithMorphTargetManager();
  30432. },
  30433. enumerable: true,
  30434. configurable: true
  30435. });
  30436. Object.defineProperty(Mesh.prototype, "source", {
  30437. get: function () {
  30438. return this._source;
  30439. },
  30440. enumerable: true,
  30441. configurable: true
  30442. });
  30443. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30444. get: function () {
  30445. return this._unIndexed;
  30446. },
  30447. set: function (value) {
  30448. if (this._unIndexed !== value) {
  30449. this._unIndexed = value;
  30450. this._markSubMeshesAsAttributesDirty();
  30451. }
  30452. },
  30453. enumerable: true,
  30454. configurable: true
  30455. });
  30456. // Methods
  30457. /**
  30458. * Returns the string "Mesh".
  30459. */
  30460. Mesh.prototype.getClassName = function () {
  30461. return "Mesh";
  30462. };
  30463. /**
  30464. * Returns a string.
  30465. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30466. */
  30467. Mesh.prototype.toString = function (fullDetails) {
  30468. var ret = _super.prototype.toString.call(this, fullDetails);
  30469. ret += ", n vertices: " + this.getTotalVertices();
  30470. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30471. if (this.animations) {
  30472. for (var i = 0; i < this.animations.length; i++) {
  30473. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30474. }
  30475. }
  30476. if (fullDetails) {
  30477. if (this._geometry) {
  30478. var ib = this.getIndices();
  30479. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30480. if (vb && ib) {
  30481. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30482. }
  30483. }
  30484. else {
  30485. ret += ", flat shading: UNKNOWN";
  30486. }
  30487. }
  30488. return ret;
  30489. };
  30490. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30491. /**
  30492. * True if the mesh has some Levels Of Details (LOD).
  30493. * Returns a boolean.
  30494. */
  30495. get: function () {
  30496. return this._LODLevels.length > 0;
  30497. },
  30498. enumerable: true,
  30499. configurable: true
  30500. });
  30501. /**
  30502. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30503. * @returns an array of {BABYLON.MeshLODLevel}
  30504. */
  30505. Mesh.prototype.getLODLevels = function () {
  30506. return this._LODLevels;
  30507. };
  30508. Mesh.prototype._sortLODLevels = function () {
  30509. this._LODLevels.sort(function (a, b) {
  30510. if (a.distance < b.distance) {
  30511. return 1;
  30512. }
  30513. if (a.distance > b.distance) {
  30514. return -1;
  30515. }
  30516. return 0;
  30517. });
  30518. };
  30519. /**
  30520. * Add a mesh as LOD level triggered at the given distance.
  30521. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30522. * @param {number} distance The distance from the center of the object to show this level
  30523. * @param {Mesh} mesh The mesh to be added as LOD level
  30524. * @return {Mesh} This mesh (for chaining)
  30525. */
  30526. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30527. if (mesh && mesh._masterMesh) {
  30528. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30529. return this;
  30530. }
  30531. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30532. this._LODLevels.push(level);
  30533. if (mesh) {
  30534. mesh._masterMesh = this;
  30535. }
  30536. this._sortLODLevels();
  30537. return this;
  30538. };
  30539. /**
  30540. * Returns the LOD level mesh at the passed distance or null if not found.
  30541. * It is related to the method `addLODLevel(distance, mesh)`.
  30542. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30543. * Returns an object Mesh or `null`.
  30544. */
  30545. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30546. for (var index = 0; index < this._LODLevels.length; index++) {
  30547. var level = this._LODLevels[index];
  30548. if (level.distance === distance) {
  30549. return level.mesh;
  30550. }
  30551. }
  30552. return null;
  30553. };
  30554. /**
  30555. * Remove a mesh from the LOD array
  30556. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30557. * @param {Mesh} mesh The mesh to be removed.
  30558. * @return {Mesh} This mesh (for chaining)
  30559. */
  30560. Mesh.prototype.removeLODLevel = function (mesh) {
  30561. for (var index = 0; index < this._LODLevels.length; index++) {
  30562. if (this._LODLevels[index].mesh === mesh) {
  30563. this._LODLevels.splice(index, 1);
  30564. if (mesh) {
  30565. mesh._masterMesh = null;
  30566. }
  30567. }
  30568. }
  30569. this._sortLODLevels();
  30570. return this;
  30571. };
  30572. /**
  30573. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30574. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30575. */
  30576. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30577. if (!this._LODLevels || this._LODLevels.length === 0) {
  30578. return this;
  30579. }
  30580. var bSphere;
  30581. if (boundingSphere) {
  30582. bSphere = boundingSphere;
  30583. }
  30584. else {
  30585. var boundingInfo = this.getBoundingInfo();
  30586. bSphere = boundingInfo.boundingSphere;
  30587. }
  30588. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30589. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30590. if (this.onLODLevelSelection) {
  30591. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30592. }
  30593. return this;
  30594. }
  30595. for (var index = 0; index < this._LODLevels.length; index++) {
  30596. var level = this._LODLevels[index];
  30597. if (level.distance < distanceToCamera) {
  30598. if (level.mesh) {
  30599. level.mesh._preActivate();
  30600. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30601. }
  30602. if (this.onLODLevelSelection) {
  30603. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30604. }
  30605. return level.mesh;
  30606. }
  30607. }
  30608. if (this.onLODLevelSelection) {
  30609. this.onLODLevelSelection(distanceToCamera, this, this);
  30610. }
  30611. return this;
  30612. };
  30613. Object.defineProperty(Mesh.prototype, "geometry", {
  30614. /**
  30615. * Returns the mesh internal Geometry object.
  30616. */
  30617. get: function () {
  30618. return this._geometry;
  30619. },
  30620. enumerable: true,
  30621. configurable: true
  30622. });
  30623. /**
  30624. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30625. */
  30626. Mesh.prototype.getTotalVertices = function () {
  30627. if (this._geometry === null || this._geometry === undefined) {
  30628. return 0;
  30629. }
  30630. return this._geometry.getTotalVertices();
  30631. };
  30632. /**
  30633. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30634. * 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.
  30635. * You can force the copy with forceCopy === true
  30636. * Returns null if the mesh has no geometry or no vertex buffer.
  30637. * Possible `kind` values :
  30638. * - BABYLON.VertexBuffer.PositionKind
  30639. * - BABYLON.VertexBuffer.UVKind
  30640. * - BABYLON.VertexBuffer.UV2Kind
  30641. * - BABYLON.VertexBuffer.UV3Kind
  30642. * - BABYLON.VertexBuffer.UV4Kind
  30643. * - BABYLON.VertexBuffer.UV5Kind
  30644. * - BABYLON.VertexBuffer.UV6Kind
  30645. * - BABYLON.VertexBuffer.ColorKind
  30646. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30647. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30648. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30649. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30650. */
  30651. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30652. if (!this._geometry) {
  30653. return null;
  30654. }
  30655. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30656. };
  30657. /**
  30658. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30659. * Returns `null` if the mesh has no geometry.
  30660. * Possible `kind` values :
  30661. * - BABYLON.VertexBuffer.PositionKind
  30662. * - BABYLON.VertexBuffer.UVKind
  30663. * - BABYLON.VertexBuffer.UV2Kind
  30664. * - BABYLON.VertexBuffer.UV3Kind
  30665. * - BABYLON.VertexBuffer.UV4Kind
  30666. * - BABYLON.VertexBuffer.UV5Kind
  30667. * - BABYLON.VertexBuffer.UV6Kind
  30668. * - BABYLON.VertexBuffer.ColorKind
  30669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30673. */
  30674. Mesh.prototype.getVertexBuffer = function (kind) {
  30675. if (!this._geometry) {
  30676. return null;
  30677. }
  30678. return this._geometry.getVertexBuffer(kind);
  30679. };
  30680. /**
  30681. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30682. * Possible `kind` values :
  30683. * - BABYLON.VertexBuffer.PositionKind
  30684. * - BABYLON.VertexBuffer.UVKind
  30685. * - BABYLON.VertexBuffer.UV2Kind
  30686. * - BABYLON.VertexBuffer.UV3Kind
  30687. * - BABYLON.VertexBuffer.UV4Kind
  30688. * - BABYLON.VertexBuffer.UV5Kind
  30689. * - BABYLON.VertexBuffer.UV6Kind
  30690. * - BABYLON.VertexBuffer.ColorKind
  30691. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30692. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30693. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30694. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30695. */
  30696. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30697. if (!this._geometry) {
  30698. if (this._delayInfo) {
  30699. return this._delayInfo.indexOf(kind) !== -1;
  30700. }
  30701. return false;
  30702. }
  30703. return this._geometry.isVerticesDataPresent(kind);
  30704. };
  30705. /**
  30706. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30707. * Possible `kind` values :
  30708. * - BABYLON.VertexBuffer.PositionKind
  30709. * - BABYLON.VertexBuffer.UVKind
  30710. * - BABYLON.VertexBuffer.UV2Kind
  30711. * - BABYLON.VertexBuffer.UV3Kind
  30712. * - BABYLON.VertexBuffer.UV4Kind
  30713. * - BABYLON.VertexBuffer.UV5Kind
  30714. * - BABYLON.VertexBuffer.UV6Kind
  30715. * - BABYLON.VertexBuffer.ColorKind
  30716. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30717. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30718. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30719. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30720. */
  30721. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30722. if (!this._geometry) {
  30723. if (this._delayInfo) {
  30724. return this._delayInfo.indexOf(kind) !== -1;
  30725. }
  30726. return false;
  30727. }
  30728. return this._geometry.isVertexBufferUpdatable(kind);
  30729. };
  30730. /**
  30731. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30732. * Possible `kind` values :
  30733. * - BABYLON.VertexBuffer.PositionKind
  30734. * - BABYLON.VertexBuffer.UVKind
  30735. * - BABYLON.VertexBuffer.UV2Kind
  30736. * - BABYLON.VertexBuffer.UV3Kind
  30737. * - BABYLON.VertexBuffer.UV4Kind
  30738. * - BABYLON.VertexBuffer.UV5Kind
  30739. * - BABYLON.VertexBuffer.UV6Kind
  30740. * - BABYLON.VertexBuffer.ColorKind
  30741. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30742. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30743. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30744. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30745. */
  30746. Mesh.prototype.getVerticesDataKinds = function () {
  30747. if (!this._geometry) {
  30748. var result = new Array();
  30749. if (this._delayInfo) {
  30750. this._delayInfo.forEach(function (kind, index, array) {
  30751. result.push(kind);
  30752. });
  30753. }
  30754. return result;
  30755. }
  30756. return this._geometry.getVerticesDataKinds();
  30757. };
  30758. /**
  30759. * Returns a positive integer : the total number of indices in this mesh geometry.
  30760. * Returns zero if the mesh has no geometry.
  30761. */
  30762. Mesh.prototype.getTotalIndices = function () {
  30763. if (!this._geometry) {
  30764. return 0;
  30765. }
  30766. return this._geometry.getTotalIndices();
  30767. };
  30768. /**
  30769. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  30770. * 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.
  30771. * Returns an empty array if the mesh has no geometry.
  30772. */
  30773. Mesh.prototype.getIndices = function (copyWhenShared) {
  30774. if (!this._geometry) {
  30775. return [];
  30776. }
  30777. return this._geometry.getIndices(copyWhenShared);
  30778. };
  30779. Object.defineProperty(Mesh.prototype, "isBlocked", {
  30780. get: function () {
  30781. return this._masterMesh !== null && this._masterMesh !== undefined;
  30782. },
  30783. enumerable: true,
  30784. configurable: true
  30785. });
  30786. /**
  30787. * Determine if the current mesh is ready to be rendered
  30788. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  30789. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  30790. * @returns true if all associated assets are ready (material, textures, shaders)
  30791. */
  30792. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  30793. if (completeCheck === void 0) { completeCheck = false; }
  30794. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  30795. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30796. return false;
  30797. }
  30798. if (!_super.prototype.isReady.call(this, completeCheck)) {
  30799. return false;
  30800. }
  30801. if (!this.subMeshes || this.subMeshes.length === 0) {
  30802. return true;
  30803. }
  30804. if (!completeCheck) {
  30805. return true;
  30806. }
  30807. var engine = this.getEngine();
  30808. var scene = this.getScene();
  30809. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  30810. this.computeWorldMatrix();
  30811. var mat = this.material || scene.defaultMaterial;
  30812. if (mat) {
  30813. if (mat.storeEffectOnSubMeshes) {
  30814. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30815. var subMesh = _a[_i];
  30816. var effectiveMaterial = subMesh.getMaterial();
  30817. if (effectiveMaterial) {
  30818. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  30819. return false;
  30820. }
  30821. }
  30822. }
  30823. }
  30824. else {
  30825. if (!mat.isReady(this, hardwareInstancedRendering)) {
  30826. return false;
  30827. }
  30828. }
  30829. }
  30830. // Shadows
  30831. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  30832. var light = _c[_b];
  30833. var generator = light.getShadowGenerator();
  30834. if (generator) {
  30835. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  30836. var subMesh = _e[_d];
  30837. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  30838. return false;
  30839. }
  30840. }
  30841. }
  30842. }
  30843. // LOD
  30844. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  30845. var lod = _g[_f];
  30846. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  30847. return false;
  30848. }
  30849. }
  30850. return true;
  30851. };
  30852. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  30853. /**
  30854. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  30855. * This property is pertinent only for updatable parametric shapes.
  30856. */
  30857. get: function () {
  30858. return this._areNormalsFrozen;
  30859. },
  30860. enumerable: true,
  30861. configurable: true
  30862. });
  30863. /**
  30864. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30865. * It has no effect at all on other shapes.
  30866. * It prevents the mesh normals from being recomputed on next `positions` array update.
  30867. * Returns the Mesh.
  30868. */
  30869. Mesh.prototype.freezeNormals = function () {
  30870. this._areNormalsFrozen = true;
  30871. return this;
  30872. };
  30873. /**
  30874. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30875. * It has no effect at all on other shapes.
  30876. * It reactivates the mesh normals computation if it was previously frozen.
  30877. * Returns the Mesh.
  30878. */
  30879. Mesh.prototype.unfreezeNormals = function () {
  30880. this._areNormalsFrozen = false;
  30881. return this;
  30882. };
  30883. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  30884. /**
  30885. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  30886. */
  30887. set: function (count) {
  30888. this._overridenInstanceCount = count;
  30889. },
  30890. enumerable: true,
  30891. configurable: true
  30892. });
  30893. // Methods
  30894. Mesh.prototype._preActivate = function () {
  30895. var sceneRenderId = this.getScene().getRenderId();
  30896. if (this._preActivateId === sceneRenderId) {
  30897. return this;
  30898. }
  30899. this._preActivateId = sceneRenderId;
  30900. this._visibleInstances = null;
  30901. return this;
  30902. };
  30903. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  30904. if (this._visibleInstances) {
  30905. this._visibleInstances.intermediateDefaultRenderId = renderId;
  30906. }
  30907. return this;
  30908. };
  30909. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  30910. if (!this._visibleInstances) {
  30911. this._visibleInstances = {};
  30912. this._visibleInstances.defaultRenderId = renderId;
  30913. this._visibleInstances.selfDefaultRenderId = this._renderId;
  30914. }
  30915. if (!this._visibleInstances[renderId]) {
  30916. this._visibleInstances[renderId] = new Array();
  30917. }
  30918. this._visibleInstances[renderId].push(instance);
  30919. return this;
  30920. };
  30921. /**
  30922. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  30923. * This means the mesh underlying bounding box and sphere are recomputed.
  30924. * Returns the Mesh.
  30925. */
  30926. Mesh.prototype.refreshBoundingInfo = function () {
  30927. return this._refreshBoundingInfo(false);
  30928. };
  30929. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  30930. if (this._boundingInfo && this._boundingInfo.isLocked) {
  30931. return this;
  30932. }
  30933. var data = this._getPositionData(applySkeleton);
  30934. if (data) {
  30935. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  30936. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30937. }
  30938. if (this.subMeshes) {
  30939. for (var index = 0; index < this.subMeshes.length; index++) {
  30940. this.subMeshes[index].refreshBoundingInfo();
  30941. }
  30942. }
  30943. this._updateBoundingInfo();
  30944. return this;
  30945. };
  30946. Mesh.prototype._getPositionData = function (applySkeleton) {
  30947. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30948. if (data && applySkeleton && this.skeleton) {
  30949. data = BABYLON.Tools.Slice(data);
  30950. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30951. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30952. if (matricesWeightsData && matricesIndicesData) {
  30953. var needExtras = this.numBoneInfluencers > 4;
  30954. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30955. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30956. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  30957. var tempVector = BABYLON.Tmp.Vector3[0];
  30958. var finalMatrix = BABYLON.Tmp.Matrix[0];
  30959. var tempMatrix = BABYLON.Tmp.Matrix[1];
  30960. var matWeightIdx = 0;
  30961. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  30962. finalMatrix.reset();
  30963. var inf;
  30964. var weight;
  30965. for (inf = 0; inf < 4; inf++) {
  30966. weight = matricesWeightsData[matWeightIdx + inf];
  30967. if (weight <= 0)
  30968. break;
  30969. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30970. finalMatrix.addToSelf(tempMatrix);
  30971. }
  30972. if (needExtras) {
  30973. for (inf = 0; inf < 4; inf++) {
  30974. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30975. if (weight <= 0)
  30976. break;
  30977. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30978. finalMatrix.addToSelf(tempMatrix);
  30979. }
  30980. }
  30981. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  30982. tempVector.toArray(data, index);
  30983. }
  30984. }
  30985. }
  30986. return data;
  30987. };
  30988. Mesh.prototype._createGlobalSubMesh = function (force) {
  30989. var totalVertices = this.getTotalVertices();
  30990. if (!totalVertices || !this.getIndices()) {
  30991. return null;
  30992. }
  30993. // Check if we need to recreate the submeshes
  30994. if (this.subMeshes && this.subMeshes.length > 0) {
  30995. var ib = this.getIndices();
  30996. if (!ib) {
  30997. return null;
  30998. }
  30999. var totalIndices = ib.length;
  31000. var needToRecreate = false;
  31001. if (force) {
  31002. needToRecreate = true;
  31003. }
  31004. else {
  31005. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31006. var submesh = _a[_i];
  31007. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31008. needToRecreate = true;
  31009. break;
  31010. }
  31011. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31012. needToRecreate = true;
  31013. break;
  31014. }
  31015. }
  31016. }
  31017. if (!needToRecreate) {
  31018. return this.subMeshes[0];
  31019. }
  31020. }
  31021. this.releaseSubMeshes();
  31022. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31023. };
  31024. Mesh.prototype.subdivide = function (count) {
  31025. if (count < 1) {
  31026. return;
  31027. }
  31028. var totalIndices = this.getTotalIndices();
  31029. var subdivisionSize = (totalIndices / count) | 0;
  31030. var offset = 0;
  31031. // Ensure that subdivisionSize is a multiple of 3
  31032. while (subdivisionSize % 3 !== 0) {
  31033. subdivisionSize++;
  31034. }
  31035. this.releaseSubMeshes();
  31036. for (var index = 0; index < count; index++) {
  31037. if (offset >= totalIndices) {
  31038. break;
  31039. }
  31040. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31041. offset += subdivisionSize;
  31042. }
  31043. this.synchronizeInstances();
  31044. };
  31045. /**
  31046. * Sets the vertex data of the mesh geometry for the requested `kind`.
  31047. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  31048. * The `data` are either a numeric array either a Float32Array.
  31049. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  31050. * 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).
  31051. * Note that a new underlying VertexBuffer object is created each call.
  31052. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  31053. *
  31054. * Possible `kind` values :
  31055. * - BABYLON.VertexBuffer.PositionKind
  31056. * - BABYLON.VertexBuffer.UVKind
  31057. * - BABYLON.VertexBuffer.UV2Kind
  31058. * - BABYLON.VertexBuffer.UV3Kind
  31059. * - BABYLON.VertexBuffer.UV4Kind
  31060. * - BABYLON.VertexBuffer.UV5Kind
  31061. * - BABYLON.VertexBuffer.UV6Kind
  31062. * - BABYLON.VertexBuffer.ColorKind
  31063. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31064. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31065. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31066. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31067. *
  31068. * Returns the Mesh.
  31069. */
  31070. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31071. if (updatable === void 0) { updatable = false; }
  31072. if (!this._geometry) {
  31073. var vertexData = new BABYLON.VertexData();
  31074. vertexData.set(data, kind);
  31075. var scene = this.getScene();
  31076. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31077. }
  31078. else {
  31079. this._geometry.setVerticesData(kind, data, updatable, stride);
  31080. }
  31081. return this;
  31082. };
  31083. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31084. if (updatable === void 0) { updatable = true; }
  31085. var vb = this.getVertexBuffer(kind);
  31086. if (!vb || vb.isUpdatable() === updatable) {
  31087. return;
  31088. }
  31089. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31090. };
  31091. /**
  31092. * Sets the mesh VertexBuffer.
  31093. * Returns the Mesh.
  31094. */
  31095. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31096. if (!this._geometry) {
  31097. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31098. }
  31099. this._geometry.setVerticesBuffer(buffer);
  31100. return this;
  31101. };
  31102. /**
  31103. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  31104. * If the mesh has no geometry, it is simply returned as it is.
  31105. * The `data` are either a numeric array either a Float32Array.
  31106. * No new underlying VertexBuffer object is created.
  31107. * 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.
  31108. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  31109. *
  31110. * Possible `kind` values :
  31111. * - BABYLON.VertexBuffer.PositionKind
  31112. * - BABYLON.VertexBuffer.UVKind
  31113. * - BABYLON.VertexBuffer.UV2Kind
  31114. * - BABYLON.VertexBuffer.UV3Kind
  31115. * - BABYLON.VertexBuffer.UV4Kind
  31116. * - BABYLON.VertexBuffer.UV5Kind
  31117. * - BABYLON.VertexBuffer.UV6Kind
  31118. * - BABYLON.VertexBuffer.ColorKind
  31119. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31120. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31121. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31122. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31123. *
  31124. * Returns the Mesh.
  31125. */
  31126. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31127. if (!this._geometry) {
  31128. return this;
  31129. }
  31130. if (!makeItUnique) {
  31131. this._geometry.updateVerticesData(kind, data, updateExtends);
  31132. }
  31133. else {
  31134. this.makeGeometryUnique();
  31135. this.updateVerticesData(kind, data, updateExtends, false);
  31136. }
  31137. return this;
  31138. };
  31139. /**
  31140. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31141. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31142. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31143. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31144. * Returns the Mesh.
  31145. */
  31146. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31147. if (computeNormals === void 0) { computeNormals = true; }
  31148. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31149. if (!positions) {
  31150. return this;
  31151. }
  31152. positionFunction(positions);
  31153. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31154. if (computeNormals) {
  31155. var indices = this.getIndices();
  31156. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31157. if (!normals) {
  31158. return this;
  31159. }
  31160. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31161. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31162. }
  31163. return this;
  31164. };
  31165. /**
  31166. * Creates a un-shared specific occurence of the geometry for the mesh.
  31167. * Returns the Mesh.
  31168. */
  31169. Mesh.prototype.makeGeometryUnique = function () {
  31170. if (!this._geometry) {
  31171. return this;
  31172. }
  31173. var oldGeometry = this._geometry;
  31174. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31175. oldGeometry.releaseForMesh(this, true);
  31176. geometry.applyToMesh(this);
  31177. return this;
  31178. };
  31179. /**
  31180. * Sets the mesh indices.
  31181. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  31182. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  31183. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  31184. * This method creates a new index buffer each call.
  31185. * Returns the Mesh.
  31186. */
  31187. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31188. if (totalVertices === void 0) { totalVertices = null; }
  31189. if (updatable === void 0) { updatable = false; }
  31190. if (!this._geometry) {
  31191. var vertexData = new BABYLON.VertexData();
  31192. vertexData.indices = indices;
  31193. var scene = this.getScene();
  31194. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31195. }
  31196. else {
  31197. this._geometry.setIndices(indices, totalVertices, updatable);
  31198. }
  31199. return this;
  31200. };
  31201. /**
  31202. * Update the current index buffer
  31203. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31204. * Returns the Mesh.
  31205. */
  31206. Mesh.prototype.updateIndices = function (indices, offset) {
  31207. if (!this._geometry) {
  31208. return this;
  31209. }
  31210. this._geometry.updateIndices(indices, offset);
  31211. return this;
  31212. };
  31213. /**
  31214. * Invert the geometry to move from a right handed system to a left handed one.
  31215. * Returns the Mesh.
  31216. */
  31217. Mesh.prototype.toLeftHanded = function () {
  31218. if (!this._geometry) {
  31219. return this;
  31220. }
  31221. this._geometry.toLeftHanded();
  31222. return this;
  31223. };
  31224. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31225. if (!this._geometry) {
  31226. return this;
  31227. }
  31228. var engine = this.getScene().getEngine();
  31229. // Wireframe
  31230. var indexToBind;
  31231. if (this._unIndexed) {
  31232. indexToBind = null;
  31233. }
  31234. else {
  31235. switch (fillMode) {
  31236. case BABYLON.Material.PointFillMode:
  31237. indexToBind = null;
  31238. break;
  31239. case BABYLON.Material.WireFrameFillMode:
  31240. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31241. break;
  31242. default:
  31243. case BABYLON.Material.TriangleFillMode:
  31244. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31245. break;
  31246. }
  31247. }
  31248. // VBOs
  31249. this._geometry._bind(effect, indexToBind);
  31250. return this;
  31251. };
  31252. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31253. if (alternate === void 0) { alternate = false; }
  31254. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31255. return this;
  31256. }
  31257. this.onBeforeDrawObservable.notifyObservers(this);
  31258. var scene = this.getScene();
  31259. var engine = scene.getEngine();
  31260. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31261. // or triangles as points
  31262. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31263. }
  31264. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31265. // Triangles as wireframe
  31266. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31267. }
  31268. else {
  31269. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31270. }
  31271. if (scene._isAlternateRenderingEnabled && !alternate) {
  31272. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31273. if (!effect || !scene.activeCamera) {
  31274. return this;
  31275. }
  31276. scene._switchToAlternateCameraConfiguration(true);
  31277. this._effectiveMaterial.bindView(effect);
  31278. this._effectiveMaterial.bindViewProjection(effect);
  31279. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31280. this._draw(subMesh, fillMode, instancesCount, true);
  31281. engine.setViewport(scene.activeCamera.viewport);
  31282. scene._switchToAlternateCameraConfiguration(false);
  31283. this._effectiveMaterial.bindView(effect);
  31284. this._effectiveMaterial.bindViewProjection(effect);
  31285. }
  31286. return this;
  31287. };
  31288. /**
  31289. * Registers for this mesh a javascript function called just before the rendering process.
  31290. * This function is passed the current mesh.
  31291. * Return the Mesh.
  31292. */
  31293. Mesh.prototype.registerBeforeRender = function (func) {
  31294. this.onBeforeRenderObservable.add(func);
  31295. return this;
  31296. };
  31297. /**
  31298. * Disposes a previously registered javascript function called before the rendering.
  31299. * This function is passed the current mesh.
  31300. * Returns the Mesh.
  31301. */
  31302. Mesh.prototype.unregisterBeforeRender = function (func) {
  31303. this.onBeforeRenderObservable.removeCallback(func);
  31304. return this;
  31305. };
  31306. /**
  31307. * Registers for this mesh a javascript function called just after the rendering is complete.
  31308. * This function is passed the current mesh.
  31309. * Returns the Mesh.
  31310. */
  31311. Mesh.prototype.registerAfterRender = function (func) {
  31312. this.onAfterRenderObservable.add(func);
  31313. return this;
  31314. };
  31315. /**
  31316. * Disposes a previously registered javascript function called after the rendering.
  31317. * This function is passed the current mesh.
  31318. * Return the Mesh.
  31319. */
  31320. Mesh.prototype.unregisterAfterRender = function (func) {
  31321. this.onAfterRenderObservable.removeCallback(func);
  31322. return this;
  31323. };
  31324. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31325. var scene = this.getScene();
  31326. this._batchCache.mustReturn = false;
  31327. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31328. this._batchCache.visibleInstances[subMeshId] = null;
  31329. if (this._visibleInstances) {
  31330. var currentRenderId = scene.getRenderId();
  31331. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31332. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31333. var selfRenderId = this._renderId;
  31334. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31335. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31336. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31337. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31338. }
  31339. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31340. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31341. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31342. this._batchCache.mustReturn = true;
  31343. return this._batchCache;
  31344. }
  31345. if (currentRenderId !== selfRenderId) {
  31346. this._batchCache.renderSelf[subMeshId] = false;
  31347. }
  31348. }
  31349. this._renderIdForInstances[subMeshId] = currentRenderId;
  31350. }
  31351. return this._batchCache;
  31352. };
  31353. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31354. var visibleInstances = batch.visibleInstances[subMesh._id];
  31355. if (!visibleInstances) {
  31356. return this;
  31357. }
  31358. var matricesCount = visibleInstances.length + 1;
  31359. var bufferSize = matricesCount * 16 * 4;
  31360. var currentInstancesBufferSize = this._instancesBufferSize;
  31361. var instancesBuffer = this._instancesBuffer;
  31362. while (this._instancesBufferSize < bufferSize) {
  31363. this._instancesBufferSize *= 2;
  31364. }
  31365. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31366. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31367. }
  31368. var offset = 0;
  31369. var instancesCount = 0;
  31370. var world = this.getWorldMatrix();
  31371. if (batch.renderSelf[subMesh._id]) {
  31372. world.copyToArray(this._instancesData, offset);
  31373. offset += 16;
  31374. instancesCount++;
  31375. }
  31376. if (visibleInstances) {
  31377. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31378. var instance = visibleInstances[instanceIndex];
  31379. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31380. offset += 16;
  31381. instancesCount++;
  31382. }
  31383. }
  31384. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31385. if (instancesBuffer) {
  31386. instancesBuffer.dispose();
  31387. }
  31388. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31389. this._instancesBuffer = instancesBuffer;
  31390. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31391. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31392. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31393. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31394. }
  31395. else {
  31396. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31397. }
  31398. this._bind(subMesh, effect, fillMode);
  31399. this._draw(subMesh, fillMode, instancesCount);
  31400. engine.unbindInstanceAttributes();
  31401. return this;
  31402. };
  31403. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31404. var scene = this.getScene();
  31405. var engine = scene.getEngine();
  31406. if (hardwareInstancedRendering) {
  31407. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31408. }
  31409. else {
  31410. if (batch.renderSelf[subMesh._id]) {
  31411. // Draw
  31412. if (onBeforeDraw) {
  31413. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31414. }
  31415. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31416. }
  31417. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31418. if (visibleInstancesForSubMesh) {
  31419. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31420. var instance = visibleInstancesForSubMesh[instanceIndex];
  31421. // World
  31422. var world = instance.getWorldMatrix();
  31423. if (onBeforeDraw) {
  31424. onBeforeDraw(true, world, effectiveMaterial);
  31425. }
  31426. // Draw
  31427. this._draw(subMesh, fillMode);
  31428. }
  31429. }
  31430. }
  31431. return this;
  31432. };
  31433. /**
  31434. * Triggers the draw call for the mesh.
  31435. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31436. * Returns the Mesh.
  31437. */
  31438. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31439. this.checkOcclusionQuery();
  31440. if (this._isOccluded) {
  31441. return this;
  31442. }
  31443. var scene = this.getScene();
  31444. // Managing instances
  31445. var batch = this._getInstancesRenderList(subMesh._id);
  31446. if (batch.mustReturn) {
  31447. return this;
  31448. }
  31449. // Checking geometry state
  31450. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31451. return this;
  31452. }
  31453. this.onBeforeRenderObservable.notifyObservers(this);
  31454. var engine = scene.getEngine();
  31455. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31456. // Material
  31457. var material = subMesh.getMaterial();
  31458. if (!material) {
  31459. return this;
  31460. }
  31461. this._effectiveMaterial = material;
  31462. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31463. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31464. return this;
  31465. }
  31466. }
  31467. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31468. return this;
  31469. }
  31470. // Alpha mode
  31471. if (enableAlphaMode) {
  31472. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31473. }
  31474. // Outline - step 1
  31475. var savedDepthWrite = engine.getDepthWrite();
  31476. if (this.renderOutline) {
  31477. engine.setDepthWrite(false);
  31478. scene.getOutlineRenderer().render(subMesh, batch);
  31479. engine.setDepthWrite(savedDepthWrite);
  31480. }
  31481. var effect;
  31482. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31483. effect = subMesh.effect;
  31484. }
  31485. else {
  31486. effect = this._effectiveMaterial.getEffect();
  31487. }
  31488. if (!effect) {
  31489. return this;
  31490. }
  31491. var sideOrientation = this.overrideMaterialSideOrientation;
  31492. if (sideOrientation == null) {
  31493. sideOrientation = this._effectiveMaterial.sideOrientation;
  31494. if (this._getWorldMatrixDeterminant() < 0) {
  31495. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31496. }
  31497. }
  31498. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31499. if (this._effectiveMaterial.forceDepthWrite) {
  31500. engine.setDepthWrite(true);
  31501. }
  31502. // Bind
  31503. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31504. if (!hardwareInstancedRendering) {
  31505. this._bind(subMesh, effect, fillMode);
  31506. }
  31507. var world = this.getWorldMatrix();
  31508. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31509. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31510. }
  31511. else {
  31512. this._effectiveMaterial.bind(world, this);
  31513. }
  31514. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31515. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31516. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31517. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31518. }
  31519. // Draw
  31520. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31521. // Unbind
  31522. this._effectiveMaterial.unbind();
  31523. // Outline - step 2
  31524. if (this.renderOutline && savedDepthWrite) {
  31525. engine.setDepthWrite(true);
  31526. engine.setColorWrite(false);
  31527. scene.getOutlineRenderer().render(subMesh, batch);
  31528. engine.setColorWrite(true);
  31529. }
  31530. // Overlay
  31531. if (this.renderOverlay) {
  31532. var currentMode = engine.getAlphaMode();
  31533. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31534. scene.getOutlineRenderer().render(subMesh, batch, true);
  31535. engine.setAlphaMode(currentMode);
  31536. }
  31537. this.onAfterRenderObservable.notifyObservers(this);
  31538. return this;
  31539. };
  31540. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31541. if (isInstance && effectiveMaterial) {
  31542. effectiveMaterial.bindOnlyWorldMatrix(world);
  31543. }
  31544. };
  31545. /**
  31546. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31547. */
  31548. Mesh.prototype.getEmittedParticleSystems = function () {
  31549. var results = new Array();
  31550. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31551. var particleSystem = this.getScene().particleSystems[index];
  31552. if (particleSystem.emitter === this) {
  31553. results.push(particleSystem);
  31554. }
  31555. }
  31556. return results;
  31557. };
  31558. /**
  31559. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31560. */
  31561. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31562. var results = new Array();
  31563. var descendants = this.getDescendants();
  31564. descendants.push(this);
  31565. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31566. var particleSystem = this.getScene().particleSystems[index];
  31567. var emitter = particleSystem.emitter;
  31568. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31569. results.push(particleSystem);
  31570. }
  31571. }
  31572. return results;
  31573. };
  31574. Mesh.prototype._checkDelayState = function () {
  31575. var scene = this.getScene();
  31576. if (this._geometry) {
  31577. this._geometry.load(scene);
  31578. }
  31579. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31581. this._queueLoad(scene);
  31582. }
  31583. return this;
  31584. };
  31585. Mesh.prototype._queueLoad = function (scene) {
  31586. var _this = this;
  31587. scene._addPendingData(this);
  31588. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31589. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31590. if (data instanceof ArrayBuffer) {
  31591. _this._delayLoadingFunction(data, _this);
  31592. }
  31593. else {
  31594. _this._delayLoadingFunction(JSON.parse(data), _this);
  31595. }
  31596. _this.instances.forEach(function (instance) {
  31597. instance._syncSubMeshes();
  31598. });
  31599. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31600. scene._removePendingData(_this);
  31601. }, function () { }, scene.database, getBinaryData);
  31602. return this;
  31603. };
  31604. /**
  31605. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31606. */
  31607. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31608. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31609. return false;
  31610. }
  31611. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31612. return false;
  31613. }
  31614. this._checkDelayState();
  31615. return true;
  31616. };
  31617. /**
  31618. * Sets the mesh material by the material or multiMaterial `id` property.
  31619. * The material `id` is a string identifying the material or the multiMaterial.
  31620. * This method returns the Mesh.
  31621. */
  31622. Mesh.prototype.setMaterialByID = function (id) {
  31623. var materials = this.getScene().materials;
  31624. var index;
  31625. for (index = materials.length - 1; index > -1; index--) {
  31626. if (materials[index].id === id) {
  31627. this.material = materials[index];
  31628. return this;
  31629. }
  31630. }
  31631. // Multi
  31632. var multiMaterials = this.getScene().multiMaterials;
  31633. for (index = multiMaterials.length - 1; index > -1; index--) {
  31634. if (multiMaterials[index].id === id) {
  31635. this.material = multiMaterials[index];
  31636. return this;
  31637. }
  31638. }
  31639. return this;
  31640. };
  31641. /**
  31642. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31643. */
  31644. Mesh.prototype.getAnimatables = function () {
  31645. var results = new Array();
  31646. if (this.material) {
  31647. results.push(this.material);
  31648. }
  31649. if (this.skeleton) {
  31650. results.push(this.skeleton);
  31651. }
  31652. return results;
  31653. };
  31654. /**
  31655. * Modifies the mesh geometry according to the passed transformation matrix.
  31656. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31657. * The mesh normals are modified accordingly the same transformation.
  31658. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31659. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31660. * Returns the Mesh.
  31661. */
  31662. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31663. // Position
  31664. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31665. return this;
  31666. }
  31667. var submeshes = this.subMeshes.splice(0);
  31668. this._resetPointsArrayCache();
  31669. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31670. var temp = new Array();
  31671. var index;
  31672. for (index = 0; index < data.length; index += 3) {
  31673. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31674. }
  31675. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31676. // Normals
  31677. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31678. return this;
  31679. }
  31680. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31681. temp = [];
  31682. for (index = 0; index < data.length; index += 3) {
  31683. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31684. }
  31685. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31686. // flip faces?
  31687. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31688. this.flipFaces();
  31689. }
  31690. // Restore submeshes
  31691. this.releaseSubMeshes();
  31692. this.subMeshes = submeshes;
  31693. return this;
  31694. };
  31695. /**
  31696. * Modifies the mesh geometry according to its own current World Matrix.
  31697. * The mesh World Matrix is then reset.
  31698. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31699. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31700. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31701. * Returns the Mesh.
  31702. */
  31703. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31704. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31705. this.scaling.copyFromFloats(1, 1, 1);
  31706. this.position.copyFromFloats(0, 0, 0);
  31707. this.rotation.copyFromFloats(0, 0, 0);
  31708. //only if quaternion is already set
  31709. if (this.rotationQuaternion) {
  31710. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31711. }
  31712. this._worldMatrix = BABYLON.Matrix.Identity();
  31713. return this;
  31714. };
  31715. Object.defineProperty(Mesh.prototype, "_positions", {
  31716. // Cache
  31717. get: function () {
  31718. if (this._geometry) {
  31719. return this._geometry._positions;
  31720. }
  31721. return null;
  31722. },
  31723. enumerable: true,
  31724. configurable: true
  31725. });
  31726. Mesh.prototype._resetPointsArrayCache = function () {
  31727. if (this._geometry) {
  31728. this._geometry._resetPointsArrayCache();
  31729. }
  31730. return this;
  31731. };
  31732. Mesh.prototype._generatePointsArray = function () {
  31733. if (this._geometry) {
  31734. return this._geometry._generatePointsArray();
  31735. }
  31736. return false;
  31737. };
  31738. /**
  31739. * Returns a new Mesh object generated from the current mesh properties.
  31740. * This method must not get confused with createInstance().
  31741. * The parameter `name` is a string, the name given to the new mesh.
  31742. * The optional parameter `newParent` can be any Node object (default `null`).
  31743. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  31744. * 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.
  31745. */
  31746. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  31747. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31748. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  31749. };
  31750. /**
  31751. * Releases resources associated with this mesh.
  31752. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  31753. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  31754. */
  31755. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  31756. var _this = this;
  31757. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  31758. this.morphTargetManager = null;
  31759. if (this._geometry) {
  31760. this._geometry.releaseForMesh(this, true);
  31761. }
  31762. // Sources
  31763. var meshes = this.getScene().meshes;
  31764. meshes.forEach(function (abstractMesh) {
  31765. var mesh = abstractMesh;
  31766. if (mesh._source && mesh._source === _this) {
  31767. mesh._source = null;
  31768. }
  31769. });
  31770. this._source = null;
  31771. // Instances
  31772. if (this._instancesBuffer) {
  31773. this._instancesBuffer.dispose();
  31774. this._instancesBuffer = null;
  31775. }
  31776. while (this.instances.length) {
  31777. this.instances[0].dispose();
  31778. }
  31779. // Effect layers.
  31780. var effectLayers = this.getScene().effectLayers;
  31781. for (var i = 0; i < effectLayers.length; i++) {
  31782. var effectLayer = effectLayers[i];
  31783. if (effectLayer) {
  31784. effectLayer._disposeMesh(this);
  31785. }
  31786. }
  31787. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  31788. };
  31789. /**
  31790. * Modifies the mesh geometry according to a displacement map.
  31791. * 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.
  31792. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31793. * This method returns nothing.
  31794. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  31795. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31796. * 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.
  31797. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31798. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31799. *
  31800. * Returns the Mesh.
  31801. */
  31802. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  31803. var _this = this;
  31804. var scene = this.getScene();
  31805. var onload = function (img) {
  31806. // Getting height map data
  31807. var canvas = document.createElement("canvas");
  31808. var context = canvas.getContext("2d");
  31809. var heightMapWidth = img.width;
  31810. var heightMapHeight = img.height;
  31811. canvas.width = heightMapWidth;
  31812. canvas.height = heightMapHeight;
  31813. context.drawImage(img, 0, 0);
  31814. // Create VertexData from map data
  31815. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  31816. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  31817. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  31818. //execute success callback, if set
  31819. if (onSuccess) {
  31820. onSuccess(_this);
  31821. }
  31822. };
  31823. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  31824. return this;
  31825. };
  31826. /**
  31827. * Modifies the mesh geometry according to a displacementMap buffer.
  31828. * 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.
  31829. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31830. * This method returns nothing.
  31831. * 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.
  31832. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  31833. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31834. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31835. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31836. *
  31837. * Returns the Mesh.
  31838. */
  31839. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  31840. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  31841. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  31842. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31843. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  31844. return this;
  31845. }
  31846. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31847. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31848. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31849. var position = BABYLON.Vector3.Zero();
  31850. var normal = BABYLON.Vector3.Zero();
  31851. var uv = BABYLON.Vector2.Zero();
  31852. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  31853. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  31854. for (var index = 0; index < positions.length; index += 3) {
  31855. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  31856. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  31857. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  31858. // Compute height
  31859. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  31860. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  31861. var pos = (u + v * heightMapWidth) * 4;
  31862. var r = buffer[pos] / 255.0;
  31863. var g = buffer[pos + 1] / 255.0;
  31864. var b = buffer[pos + 2] / 255.0;
  31865. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31866. normal.normalize();
  31867. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  31868. position = position.add(normal);
  31869. position.toArray(positions, index);
  31870. }
  31871. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  31872. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  31873. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31874. return this;
  31875. };
  31876. /**
  31877. * Modify the mesh to get a flat shading rendering.
  31878. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  31879. * This method returns the Mesh.
  31880. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  31881. */
  31882. Mesh.prototype.convertToFlatShadedMesh = function () {
  31883. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  31884. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31885. var kinds = this.getVerticesDataKinds();
  31886. var vbs = {};
  31887. var data = {};
  31888. var newdata = {};
  31889. var updatableNormals = false;
  31890. var kindIndex;
  31891. var kind;
  31892. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31893. kind = kinds[kindIndex];
  31894. var vertexBuffer = this.getVertexBuffer(kind);
  31895. if (kind === BABYLON.VertexBuffer.NormalKind) {
  31896. updatableNormals = vertexBuffer.isUpdatable();
  31897. kinds.splice(kindIndex, 1);
  31898. kindIndex--;
  31899. continue;
  31900. }
  31901. vbs[kind] = vertexBuffer;
  31902. data[kind] = vbs[kind].getData();
  31903. newdata[kind] = [];
  31904. }
  31905. // Save previous submeshes
  31906. var previousSubmeshes = this.subMeshes.slice(0);
  31907. var indices = this.getIndices();
  31908. var totalIndices = this.getTotalIndices();
  31909. // Generating unique vertices per face
  31910. var index;
  31911. for (index = 0; index < totalIndices; index++) {
  31912. var vertexIndex = indices[index];
  31913. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31914. kind = kinds[kindIndex];
  31915. var stride = vbs[kind].getStrideSize();
  31916. for (var offset = 0; offset < stride; offset++) {
  31917. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31918. }
  31919. }
  31920. }
  31921. // Updating faces & normal
  31922. var normals = [];
  31923. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  31924. for (index = 0; index < totalIndices; index += 3) {
  31925. indices[index] = index;
  31926. indices[index + 1] = index + 1;
  31927. indices[index + 2] = index + 2;
  31928. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  31929. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  31930. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  31931. var p1p2 = p1.subtract(p2);
  31932. var p3p2 = p3.subtract(p2);
  31933. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  31934. // Store same normals for every vertex
  31935. for (var localIndex = 0; localIndex < 3; localIndex++) {
  31936. normals.push(normal.x);
  31937. normals.push(normal.y);
  31938. normals.push(normal.z);
  31939. }
  31940. }
  31941. this.setIndices(indices);
  31942. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  31943. // Updating vertex buffers
  31944. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31945. kind = kinds[kindIndex];
  31946. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31947. }
  31948. // Updating submeshes
  31949. this.releaseSubMeshes();
  31950. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31951. var previousOne = previousSubmeshes[submeshIndex];
  31952. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  31953. }
  31954. this.synchronizeInstances();
  31955. return this;
  31956. };
  31957. /**
  31958. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  31959. * In other words, more vertices, no more indices and a single bigger VBO.
  31960. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  31961. * Returns the Mesh.
  31962. */
  31963. Mesh.prototype.convertToUnIndexedMesh = function () {
  31964. /// <summary>Remove indices by unfolding faces into buffers</summary>
  31965. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31966. var kinds = this.getVerticesDataKinds();
  31967. var vbs = {};
  31968. var data = {};
  31969. var newdata = {};
  31970. var kindIndex;
  31971. var kind;
  31972. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31973. kind = kinds[kindIndex];
  31974. var vertexBuffer = this.getVertexBuffer(kind);
  31975. vbs[kind] = vertexBuffer;
  31976. data[kind] = vbs[kind].getData();
  31977. newdata[kind] = [];
  31978. }
  31979. // Save previous submeshes
  31980. var previousSubmeshes = this.subMeshes.slice(0);
  31981. var indices = this.getIndices();
  31982. var totalIndices = this.getTotalIndices();
  31983. // Generating unique vertices per face
  31984. var index;
  31985. for (index = 0; index < totalIndices; index++) {
  31986. var vertexIndex = indices[index];
  31987. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31988. kind = kinds[kindIndex];
  31989. var stride = vbs[kind].getStrideSize();
  31990. for (var offset = 0; offset < stride; offset++) {
  31991. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31992. }
  31993. }
  31994. }
  31995. // Updating indices
  31996. for (index = 0; index < totalIndices; index += 3) {
  31997. indices[index] = index;
  31998. indices[index + 1] = index + 1;
  31999. indices[index + 2] = index + 2;
  32000. }
  32001. this.setIndices(indices);
  32002. // Updating vertex buffers
  32003. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32004. kind = kinds[kindIndex];
  32005. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32006. }
  32007. // Updating submeshes
  32008. this.releaseSubMeshes();
  32009. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32010. var previousOne = previousSubmeshes[submeshIndex];
  32011. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32012. }
  32013. this._unIndexed = true;
  32014. this.synchronizeInstances();
  32015. return this;
  32016. };
  32017. /**
  32018. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32019. * This method returns the Mesh.
  32020. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32021. */
  32022. Mesh.prototype.flipFaces = function (flipNormals) {
  32023. if (flipNormals === void 0) { flipNormals = false; }
  32024. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32025. var i;
  32026. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32027. for (i = 0; i < vertex_data.normals.length; i++) {
  32028. vertex_data.normals[i] *= -1;
  32029. }
  32030. }
  32031. if (vertex_data.indices) {
  32032. var temp;
  32033. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32034. // reassign indices
  32035. temp = vertex_data.indices[i + 1];
  32036. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32037. vertex_data.indices[i + 2] = temp;
  32038. }
  32039. }
  32040. vertex_data.applyToMesh(this);
  32041. return this;
  32042. };
  32043. // Instances
  32044. /**
  32045. * Creates a new InstancedMesh object from the mesh model.
  32046. * An instance shares the same properties and the same material than its model.
  32047. * Only these properties of each instance can then be set individually :
  32048. * - position
  32049. * - rotation
  32050. * - rotationQuaternion
  32051. * - setPivotMatrix
  32052. * - scaling
  32053. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32054. * Warning : this method is not supported for Line mesh and LineSystem
  32055. */
  32056. Mesh.prototype.createInstance = function (name) {
  32057. return new BABYLON.InstancedMesh(name, this);
  32058. };
  32059. /**
  32060. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32061. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32062. * This method returns the Mesh.
  32063. */
  32064. Mesh.prototype.synchronizeInstances = function () {
  32065. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32066. var instance = this.instances[instanceIndex];
  32067. instance._syncSubMeshes();
  32068. }
  32069. return this;
  32070. };
  32071. /**
  32072. * Simplify the mesh according to the given array of settings.
  32073. * Function will return immediately and will simplify async. It returns the Mesh.
  32074. * @param settings a collection of simplification settings.
  32075. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32076. * @param type the type of simplification to run.
  32077. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32078. */
  32079. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32080. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32081. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32082. this.getScene().simplificationQueue.addTask({
  32083. settings: settings,
  32084. parallelProcessing: parallelProcessing,
  32085. mesh: this,
  32086. simplificationType: simplificationType,
  32087. successCallback: successCallback
  32088. });
  32089. return this;
  32090. };
  32091. /**
  32092. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32093. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32094. * This should be used together with the simplification to avoid disappearing triangles.
  32095. * Returns the Mesh.
  32096. * @param successCallback an optional success callback to be called after the optimization finished.
  32097. */
  32098. Mesh.prototype.optimizeIndices = function (successCallback) {
  32099. var _this = this;
  32100. var indices = this.getIndices();
  32101. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32102. if (!positions || !indices) {
  32103. return this;
  32104. }
  32105. var vectorPositions = new Array();
  32106. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32107. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32108. }
  32109. var dupes = new Array();
  32110. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32111. var realPos = vectorPositions.length - 1 - iteration;
  32112. var testedPosition = vectorPositions[realPos];
  32113. for (var j = 0; j < realPos; ++j) {
  32114. var againstPosition = vectorPositions[j];
  32115. if (testedPosition.equals(againstPosition)) {
  32116. dupes[realPos] = j;
  32117. break;
  32118. }
  32119. }
  32120. }, function () {
  32121. for (var i = 0; i < indices.length; ++i) {
  32122. indices[i] = dupes[indices[i]] || indices[i];
  32123. }
  32124. //indices are now reordered
  32125. var originalSubMeshes = _this.subMeshes.slice(0);
  32126. _this.setIndices(indices);
  32127. _this.subMeshes = originalSubMeshes;
  32128. if (successCallback) {
  32129. successCallback(_this);
  32130. }
  32131. });
  32132. return this;
  32133. };
  32134. Mesh.prototype.serialize = function (serializationObject) {
  32135. serializationObject.name = this.name;
  32136. serializationObject.id = this.id;
  32137. serializationObject.type = this.getClassName();
  32138. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32139. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32140. }
  32141. serializationObject.position = this.position.asArray();
  32142. if (this.rotationQuaternion) {
  32143. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32144. }
  32145. else if (this.rotation) {
  32146. serializationObject.rotation = this.rotation.asArray();
  32147. }
  32148. serializationObject.scaling = this.scaling.asArray();
  32149. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32150. serializationObject.isEnabled = this.isEnabled(false);
  32151. serializationObject.isVisible = this.isVisible;
  32152. serializationObject.infiniteDistance = this.infiniteDistance;
  32153. serializationObject.pickable = this.isPickable;
  32154. serializationObject.receiveShadows = this.receiveShadows;
  32155. serializationObject.billboardMode = this.billboardMode;
  32156. serializationObject.visibility = this.visibility;
  32157. serializationObject.checkCollisions = this.checkCollisions;
  32158. serializationObject.isBlocker = this.isBlocker;
  32159. // Parent
  32160. if (this.parent) {
  32161. serializationObject.parentId = this.parent.id;
  32162. }
  32163. // Geometry
  32164. serializationObject.isUnIndexed = this.isUnIndexed;
  32165. var geometry = this._geometry;
  32166. if (geometry) {
  32167. var geometryId = geometry.id;
  32168. serializationObject.geometryId = geometryId;
  32169. // SubMeshes
  32170. serializationObject.subMeshes = [];
  32171. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32172. var subMesh = this.subMeshes[subIndex];
  32173. serializationObject.subMeshes.push({
  32174. materialIndex: subMesh.materialIndex,
  32175. verticesStart: subMesh.verticesStart,
  32176. verticesCount: subMesh.verticesCount,
  32177. indexStart: subMesh.indexStart,
  32178. indexCount: subMesh.indexCount
  32179. });
  32180. }
  32181. }
  32182. // Material
  32183. if (this.material) {
  32184. serializationObject.materialId = this.material.id;
  32185. }
  32186. else {
  32187. this.material = null;
  32188. }
  32189. // Morph targets
  32190. if (this.morphTargetManager) {
  32191. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32192. }
  32193. // Skeleton
  32194. if (this.skeleton) {
  32195. serializationObject.skeletonId = this.skeleton.id;
  32196. }
  32197. // Physics
  32198. //TODO implement correct serialization for physics impostors.
  32199. var impostor = this.getPhysicsImpostor();
  32200. if (impostor) {
  32201. serializationObject.physicsMass = impostor.getParam("mass");
  32202. serializationObject.physicsFriction = impostor.getParam("friction");
  32203. serializationObject.physicsRestitution = impostor.getParam("mass");
  32204. serializationObject.physicsImpostor = impostor.type;
  32205. }
  32206. // Metadata
  32207. if (this.metadata) {
  32208. serializationObject.metadata = this.metadata;
  32209. }
  32210. // Instances
  32211. serializationObject.instances = [];
  32212. for (var index = 0; index < this.instances.length; index++) {
  32213. var instance = this.instances[index];
  32214. var serializationInstance = {
  32215. name: instance.name,
  32216. id: instance.id,
  32217. position: instance.position.asArray(),
  32218. scaling: instance.scaling.asArray()
  32219. };
  32220. if (instance.rotationQuaternion) {
  32221. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32222. }
  32223. else if (instance.rotation) {
  32224. serializationInstance.rotation = instance.rotation.asArray();
  32225. }
  32226. serializationObject.instances.push(serializationInstance);
  32227. // Animations
  32228. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32229. serializationInstance.ranges = instance.serializeAnimationRanges();
  32230. }
  32231. //
  32232. // Animations
  32233. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32234. serializationObject.ranges = this.serializeAnimationRanges();
  32235. // Layer mask
  32236. serializationObject.layerMask = this.layerMask;
  32237. // Alpha
  32238. serializationObject.alphaIndex = this.alphaIndex;
  32239. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32240. // Overlay
  32241. serializationObject.overlayAlpha = this.overlayAlpha;
  32242. serializationObject.overlayColor = this.overlayColor.asArray();
  32243. serializationObject.renderOverlay = this.renderOverlay;
  32244. // Fog
  32245. serializationObject.applyFog = this.applyFog;
  32246. // Action Manager
  32247. if (this.actionManager) {
  32248. serializationObject.actions = this.actionManager.serialize(this.name);
  32249. }
  32250. };
  32251. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32252. if (!this.geometry) {
  32253. return;
  32254. }
  32255. this._markSubMeshesAsAttributesDirty();
  32256. var morphTargetManager = this._morphTargetManager;
  32257. if (morphTargetManager && morphTargetManager.vertexCount) {
  32258. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32259. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32260. this.morphTargetManager = null;
  32261. return;
  32262. }
  32263. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32264. var morphTarget = morphTargetManager.getActiveTarget(index);
  32265. var positions = morphTarget.getPositions();
  32266. if (!positions) {
  32267. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32268. return;
  32269. }
  32270. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32271. var normals = morphTarget.getNormals();
  32272. if (normals) {
  32273. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32274. }
  32275. var tangents = morphTarget.getTangents();
  32276. if (tangents) {
  32277. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32278. }
  32279. }
  32280. }
  32281. else {
  32282. var index = 0;
  32283. // Positions
  32284. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32285. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32286. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32287. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32288. }
  32289. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32290. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32291. }
  32292. index++;
  32293. }
  32294. }
  32295. };
  32296. // Statics
  32297. /**
  32298. * Returns a new Mesh object parsed from the source provided.
  32299. * The parameter `parsedMesh` is the source.
  32300. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32301. */
  32302. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32303. var mesh;
  32304. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32305. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32306. }
  32307. else {
  32308. mesh = new Mesh(parsedMesh.name, scene);
  32309. }
  32310. mesh.id = parsedMesh.id;
  32311. if (BABYLON.Tags) {
  32312. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32313. }
  32314. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32315. if (parsedMesh.metadata !== undefined) {
  32316. mesh.metadata = parsedMesh.metadata;
  32317. }
  32318. if (parsedMesh.rotationQuaternion) {
  32319. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32320. }
  32321. else if (parsedMesh.rotation) {
  32322. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32323. }
  32324. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32325. if (parsedMesh.localMatrix) {
  32326. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32327. }
  32328. else if (parsedMesh.pivotMatrix) {
  32329. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32330. }
  32331. mesh.setEnabled(parsedMesh.isEnabled);
  32332. mesh.isVisible = parsedMesh.isVisible;
  32333. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32334. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32335. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32336. if (parsedMesh.applyFog !== undefined) {
  32337. mesh.applyFog = parsedMesh.applyFog;
  32338. }
  32339. if (parsedMesh.pickable !== undefined) {
  32340. mesh.isPickable = parsedMesh.pickable;
  32341. }
  32342. if (parsedMesh.alphaIndex !== undefined) {
  32343. mesh.alphaIndex = parsedMesh.alphaIndex;
  32344. }
  32345. mesh.receiveShadows = parsedMesh.receiveShadows;
  32346. mesh.billboardMode = parsedMesh.billboardMode;
  32347. if (parsedMesh.visibility !== undefined) {
  32348. mesh.visibility = parsedMesh.visibility;
  32349. }
  32350. mesh.checkCollisions = parsedMesh.checkCollisions;
  32351. if (parsedMesh.isBlocker !== undefined) {
  32352. mesh.isBlocker = parsedMesh.isBlocker;
  32353. }
  32354. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32355. // freezeWorldMatrix
  32356. if (parsedMesh.freezeWorldMatrix) {
  32357. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32358. }
  32359. // Parent
  32360. if (parsedMesh.parentId) {
  32361. mesh._waitingParentId = parsedMesh.parentId;
  32362. }
  32363. // Actions
  32364. if (parsedMesh.actions !== undefined) {
  32365. mesh._waitingActions = parsedMesh.actions;
  32366. }
  32367. // Overlay
  32368. if (parsedMesh.overlayAlpha !== undefined) {
  32369. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32370. }
  32371. if (parsedMesh.overlayColor !== undefined) {
  32372. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32373. }
  32374. if (parsedMesh.renderOverlay !== undefined) {
  32375. mesh.renderOverlay = parsedMesh.renderOverlay;
  32376. }
  32377. // Geometry
  32378. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32379. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32380. if (parsedMesh.delayLoadingFile) {
  32381. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32382. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32383. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32384. if (parsedMesh._binaryInfo) {
  32385. mesh._binaryInfo = parsedMesh._binaryInfo;
  32386. }
  32387. mesh._delayInfo = [];
  32388. if (parsedMesh.hasUVs) {
  32389. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32390. }
  32391. if (parsedMesh.hasUVs2) {
  32392. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32393. }
  32394. if (parsedMesh.hasUVs3) {
  32395. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32396. }
  32397. if (parsedMesh.hasUVs4) {
  32398. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32399. }
  32400. if (parsedMesh.hasUVs5) {
  32401. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32402. }
  32403. if (parsedMesh.hasUVs6) {
  32404. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32405. }
  32406. if (parsedMesh.hasColors) {
  32407. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32408. }
  32409. if (parsedMesh.hasMatricesIndices) {
  32410. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32411. }
  32412. if (parsedMesh.hasMatricesWeights) {
  32413. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32414. }
  32415. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32416. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32417. mesh._checkDelayState();
  32418. }
  32419. }
  32420. else {
  32421. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32422. }
  32423. // Material
  32424. if (parsedMesh.materialId) {
  32425. mesh.setMaterialByID(parsedMesh.materialId);
  32426. }
  32427. else {
  32428. mesh.material = null;
  32429. }
  32430. // Morph targets
  32431. if (parsedMesh.morphTargetManagerId > -1) {
  32432. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32433. }
  32434. // Skeleton
  32435. if (parsedMesh.skeletonId > -1) {
  32436. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32437. if (parsedMesh.numBoneInfluencers) {
  32438. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32439. }
  32440. }
  32441. // Animations
  32442. if (parsedMesh.animations) {
  32443. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32444. var parsedAnimation = parsedMesh.animations[animationIndex];
  32445. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32446. }
  32447. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32448. }
  32449. if (parsedMesh.autoAnimate) {
  32450. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32451. }
  32452. // Layer Mask
  32453. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32454. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32455. }
  32456. else {
  32457. mesh.layerMask = 0x0FFFFFFF;
  32458. }
  32459. // Physics
  32460. if (parsedMesh.physicsImpostor) {
  32461. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32462. mass: parsedMesh.physicsMass,
  32463. friction: parsedMesh.physicsFriction,
  32464. restitution: parsedMesh.physicsRestitution
  32465. }, scene);
  32466. }
  32467. // Instances
  32468. if (parsedMesh.instances) {
  32469. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32470. var parsedInstance = parsedMesh.instances[index];
  32471. var instance = mesh.createInstance(parsedInstance.name);
  32472. if (parsedInstance.id) {
  32473. instance.id = parsedInstance.id;
  32474. }
  32475. if (BABYLON.Tags) {
  32476. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32477. }
  32478. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32479. if (parsedInstance.parentId) {
  32480. instance._waitingParentId = parsedInstance.parentId;
  32481. }
  32482. if (parsedInstance.rotationQuaternion) {
  32483. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32484. }
  32485. else if (parsedInstance.rotation) {
  32486. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32487. }
  32488. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32489. instance.checkCollisions = mesh.checkCollisions;
  32490. if (parsedMesh.animations) {
  32491. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32492. parsedAnimation = parsedMesh.animations[animationIndex];
  32493. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32494. }
  32495. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32496. }
  32497. }
  32498. }
  32499. return mesh;
  32500. };
  32501. /**
  32502. * Creates a ribbon mesh.
  32503. * Please consider using the same method from the MeshBuilder class instead.
  32504. * 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.
  32505. *
  32506. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32507. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32508. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32509. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32510. * 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.
  32511. * 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.
  32512. * 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
  32513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32514. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32516. */
  32517. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32518. if (closeArray === void 0) { closeArray = false; }
  32519. if (updatable === void 0) { updatable = false; }
  32520. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32521. pathArray: pathArray,
  32522. closeArray: closeArray,
  32523. closePath: closePath,
  32524. offset: offset,
  32525. updatable: updatable,
  32526. sideOrientation: sideOrientation,
  32527. instance: instance
  32528. }, scene);
  32529. };
  32530. /**
  32531. * Creates a plane polygonal mesh. By default, this is a disc.
  32532. * Please consider using the same method from the MeshBuilder class instead.
  32533. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32534. * 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.
  32535. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32536. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32538. */
  32539. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32540. if (scene === void 0) { scene = null; }
  32541. var options = {
  32542. radius: radius,
  32543. tessellation: tessellation,
  32544. sideOrientation: sideOrientation,
  32545. updatable: updatable
  32546. };
  32547. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32548. };
  32549. /**
  32550. * Creates a box mesh.
  32551. * Please consider using the same method from the MeshBuilder class instead.
  32552. * The parameter `size` sets the size (float) of each box side (default 1).
  32553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32556. */
  32557. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32558. if (scene === void 0) { scene = null; }
  32559. var options = {
  32560. size: size,
  32561. sideOrientation: sideOrientation,
  32562. updatable: updatable
  32563. };
  32564. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32565. };
  32566. /**
  32567. * Creates a sphere mesh.
  32568. * Please consider using the same method from the MeshBuilder class instead.
  32569. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32570. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32571. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32572. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32574. */
  32575. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32576. var options = {
  32577. segments: segments,
  32578. diameterX: diameter,
  32579. diameterY: diameter,
  32580. diameterZ: diameter,
  32581. sideOrientation: sideOrientation,
  32582. updatable: updatable
  32583. };
  32584. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32585. };
  32586. /**
  32587. * Creates a cylinder or a cone mesh.
  32588. * Please consider using the same method from the MeshBuilder class instead.
  32589. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32590. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32591. * 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.
  32592. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32593. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32595. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32597. */
  32598. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32599. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32600. if (scene !== undefined) {
  32601. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32602. updatable = scene;
  32603. }
  32604. scene = subdivisions;
  32605. subdivisions = 1;
  32606. }
  32607. var options = {
  32608. height: height,
  32609. diameterTop: diameterTop,
  32610. diameterBottom: diameterBottom,
  32611. tessellation: tessellation,
  32612. subdivisions: subdivisions,
  32613. sideOrientation: sideOrientation,
  32614. updatable: updatable
  32615. };
  32616. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32617. };
  32618. // Torus (Code from SharpDX.org)
  32619. /**
  32620. * Creates a torus mesh.
  32621. * Please consider using the same method from the MeshBuilder class instead.
  32622. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32623. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32624. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32626. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32628. */
  32629. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32630. var options = {
  32631. diameter: diameter,
  32632. thickness: thickness,
  32633. tessellation: tessellation,
  32634. sideOrientation: sideOrientation,
  32635. updatable: updatable
  32636. };
  32637. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32638. };
  32639. /**
  32640. * Creates a torus knot mesh.
  32641. * Please consider using the same method from the MeshBuilder class instead.
  32642. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32643. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32644. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32645. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32647. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32649. */
  32650. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32651. var options = {
  32652. radius: radius,
  32653. tube: tube,
  32654. radialSegments: radialSegments,
  32655. tubularSegments: tubularSegments,
  32656. p: p,
  32657. q: q,
  32658. sideOrientation: sideOrientation,
  32659. updatable: updatable
  32660. };
  32661. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32662. };
  32663. /**
  32664. * Creates a line mesh.
  32665. * Please consider using the same method from the MeshBuilder class instead.
  32666. * 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.
  32667. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32668. * The parameter `points` is an array successive Vector3.
  32669. * 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
  32670. * When updating an instance, remember that only point positions can change, not the number of points.
  32671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32672. */
  32673. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32674. if (scene === void 0) { scene = null; }
  32675. if (updatable === void 0) { updatable = false; }
  32676. if (instance === void 0) { instance = null; }
  32677. var options = {
  32678. points: points,
  32679. updatable: updatable,
  32680. instance: instance
  32681. };
  32682. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32683. };
  32684. /**
  32685. * Creates a dashed line mesh.
  32686. * Please consider using the same method from the MeshBuilder class instead.
  32687. * 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.
  32688. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32689. * The parameter `points` is an array successive Vector3.
  32690. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32691. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32692. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32693. * 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
  32694. * When updating an instance, remember that only point positions can change, not the number of points.
  32695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32696. */
  32697. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32698. if (scene === void 0) { scene = null; }
  32699. var options = {
  32700. points: points,
  32701. dashSize: dashSize,
  32702. gapSize: gapSize,
  32703. dashNb: dashNb,
  32704. updatable: updatable,
  32705. instance: instance
  32706. };
  32707. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32708. };
  32709. /**
  32710. * Creates a polygon mesh.
  32711. * Please consider using the same method from the MeshBuilder class instead.
  32712. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32713. * 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.
  32714. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32716. * Remember you can only change the shape positions, not their number when updating a polygon.
  32717. */
  32718. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32719. var options = {
  32720. shape: shape,
  32721. holes: holes,
  32722. updatable: updatable,
  32723. sideOrientation: sideOrientation
  32724. };
  32725. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32726. };
  32727. /**
  32728. * Creates an extruded polygon mesh, with depth in the Y direction.
  32729. * Please consider using the same method from the MeshBuilder class instead.
  32730. */
  32731. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32732. var options = {
  32733. shape: shape,
  32734. holes: holes,
  32735. depth: depth,
  32736. updatable: updatable,
  32737. sideOrientation: sideOrientation
  32738. };
  32739. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  32740. };
  32741. /**
  32742. * Creates an extruded shape mesh.
  32743. * 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.
  32744. * Please consider using the same method from the MeshBuilder class instead.
  32745. *
  32746. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32747. * 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
  32748. * extruded along the Z axis.
  32749. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32750. * 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.
  32751. * The parameter `scale` (float, default 1) is the value to scale the shape.
  32752. * 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
  32753. * 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
  32754. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32755. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32756. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32758. */
  32759. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  32760. if (scene === void 0) { scene = null; }
  32761. var options = {
  32762. shape: shape,
  32763. path: path,
  32764. scale: scale,
  32765. rotation: rotation,
  32766. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32767. sideOrientation: sideOrientation,
  32768. instance: instance,
  32769. updatable: updatable
  32770. };
  32771. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  32772. };
  32773. /**
  32774. * Creates an custom extruded shape mesh.
  32775. * 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.
  32776. * Please consider using the same method from the MeshBuilder class instead.
  32777. *
  32778. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32779. * 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
  32780. * extruded along the Z axis.
  32781. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32782. * 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
  32783. * and the distance of this point from the begining of the path :
  32784. * ```javascript
  32785. * var rotationFunction = function(i, distance) {
  32786. * // do things
  32787. * return rotationValue; }
  32788. * ```
  32789. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  32790. * 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
  32791. * and the distance of this point from the begining of the path :
  32792. * ```javascript
  32793. * var scaleFunction = function(i, distance) {
  32794. * // do things
  32795. * return scaleValue;}
  32796. * ```
  32797. * It must returns a float value that will be the scale value applied to the shape on each path point.
  32798. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  32799. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  32800. * 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
  32801. * 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
  32802. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32806. */
  32807. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  32808. var options = {
  32809. shape: shape,
  32810. path: path,
  32811. scaleFunction: scaleFunction,
  32812. rotationFunction: rotationFunction,
  32813. ribbonCloseArray: ribbonCloseArray,
  32814. ribbonClosePath: ribbonClosePath,
  32815. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32816. sideOrientation: sideOrientation,
  32817. instance: instance,
  32818. updatable: updatable
  32819. };
  32820. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  32821. };
  32822. /**
  32823. * Creates lathe mesh.
  32824. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  32825. * Please consider using the same method from the MeshBuilder class instead.
  32826. * 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
  32827. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  32828. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  32829. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  32830. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32831. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32833. */
  32834. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  32835. var options = {
  32836. shape: shape,
  32837. radius: radius,
  32838. tessellation: tessellation,
  32839. sideOrientation: sideOrientation,
  32840. updatable: updatable
  32841. };
  32842. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  32843. };
  32844. /**
  32845. * Creates a plane mesh.
  32846. * Please consider using the same method from the MeshBuilder class instead.
  32847. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  32848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32851. */
  32852. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  32853. var options = {
  32854. size: size,
  32855. width: size,
  32856. height: size,
  32857. sideOrientation: sideOrientation,
  32858. updatable: updatable
  32859. };
  32860. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  32861. };
  32862. /**
  32863. * Creates a ground mesh.
  32864. * Please consider using the same method from the MeshBuilder class instead.
  32865. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  32866. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  32867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32868. */
  32869. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  32870. var options = {
  32871. width: width,
  32872. height: height,
  32873. subdivisions: subdivisions,
  32874. updatable: updatable
  32875. };
  32876. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  32877. };
  32878. /**
  32879. * Creates a tiled ground mesh.
  32880. * Please consider using the same method from the MeshBuilder class instead.
  32881. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  32882. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  32883. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  32884. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  32885. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  32886. * numbers of subdivisions on the ground width and height of each tile.
  32887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32888. */
  32889. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  32890. var options = {
  32891. xmin: xmin,
  32892. zmin: zmin,
  32893. xmax: xmax,
  32894. zmax: zmax,
  32895. subdivisions: subdivisions,
  32896. precision: precision,
  32897. updatable: updatable
  32898. };
  32899. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  32900. };
  32901. /**
  32902. * Creates a ground mesh from a height map.
  32903. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  32904. * Please consider using the same method from the MeshBuilder class instead.
  32905. * The parameter `url` sets the URL of the height map image resource.
  32906. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  32907. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  32908. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  32909. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  32910. * 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).
  32911. * This function is passed the newly built mesh :
  32912. * ```javascript
  32913. * function(mesh) { // do things
  32914. * return; }
  32915. * ```
  32916. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32917. */
  32918. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  32919. var options = {
  32920. width: width,
  32921. height: height,
  32922. subdivisions: subdivisions,
  32923. minHeight: minHeight,
  32924. maxHeight: maxHeight,
  32925. updatable: updatable,
  32926. onReady: onReady
  32927. };
  32928. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  32929. };
  32930. /**
  32931. * Creates a tube mesh.
  32932. * 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.
  32933. * Please consider using the same method from the MeshBuilder class instead.
  32934. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  32935. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  32936. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  32937. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  32938. * 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.
  32939. * It must return a radius value (positive float) :
  32940. * ```javascript
  32941. * var radiusFunction = function(i, distance) {
  32942. * // do things
  32943. * return radius; }
  32944. * ```
  32945. * 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
  32946. * 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
  32947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32948. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32950. */
  32951. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  32952. var options = {
  32953. path: path,
  32954. radius: radius,
  32955. tessellation: tessellation,
  32956. radiusFunction: radiusFunction,
  32957. arc: 1,
  32958. cap: cap,
  32959. updatable: updatable,
  32960. sideOrientation: sideOrientation,
  32961. instance: instance
  32962. };
  32963. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  32964. };
  32965. /**
  32966. * Creates a polyhedron mesh.
  32967. * Please consider using the same method from the MeshBuilder class instead.
  32968. * 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
  32969. * to choose the wanted type.
  32970. * The parameter `size` (positive float, default 1) sets the polygon size.
  32971. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  32972. * 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`.
  32973. * 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
  32974. * 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)`).
  32975. * 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
  32976. * 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.
  32977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32980. */
  32981. Mesh.CreatePolyhedron = function (name, options, scene) {
  32982. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  32983. };
  32984. /**
  32985. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  32986. * Please consider using the same method from the MeshBuilder class instead.
  32987. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  32988. * 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`).
  32989. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  32990. * 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.
  32991. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32992. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32993. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32994. */
  32995. Mesh.CreateIcoSphere = function (name, options, scene) {
  32996. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  32997. };
  32998. /**
  32999. * Creates a decal mesh.
  33000. * Please consider using the same method from the MeshBuilder class instead.
  33001. * 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.
  33002. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33003. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33004. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33005. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33006. */
  33007. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33008. var options = {
  33009. position: position,
  33010. normal: normal,
  33011. size: size,
  33012. angle: angle
  33013. };
  33014. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33015. };
  33016. // Skeletons
  33017. /**
  33018. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33019. */
  33020. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33021. if (!this._sourcePositions) {
  33022. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33023. if (!source) {
  33024. return this._sourcePositions;
  33025. }
  33026. this._sourcePositions = new Float32Array(source);
  33027. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33028. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33029. }
  33030. }
  33031. return this._sourcePositions;
  33032. };
  33033. /**
  33034. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33035. */
  33036. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33037. if (!this._sourceNormals) {
  33038. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33039. if (!source) {
  33040. return this._sourceNormals;
  33041. }
  33042. this._sourceNormals = new Float32Array(source);
  33043. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33044. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33045. }
  33046. }
  33047. return this._sourceNormals;
  33048. };
  33049. /**
  33050. * Updates the vertex buffer by applying transformation from the bones.
  33051. * Returns the Mesh.
  33052. *
  33053. * @param {skeleton} skeleton to apply
  33054. */
  33055. Mesh.prototype.applySkeleton = function (skeleton) {
  33056. if (!this.geometry) {
  33057. return this;
  33058. }
  33059. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33060. return this;
  33061. }
  33062. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33063. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33064. return this;
  33065. }
  33066. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33067. return this;
  33068. }
  33069. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33070. return this;
  33071. }
  33072. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33073. return this;
  33074. }
  33075. if (!this._sourcePositions) {
  33076. var submeshes = this.subMeshes.slice();
  33077. this.setPositionsForCPUSkinning();
  33078. this.subMeshes = submeshes;
  33079. }
  33080. if (!this._sourceNormals) {
  33081. this.setNormalsForCPUSkinning();
  33082. }
  33083. // positionsData checks for not being Float32Array will only pass at most once
  33084. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33085. if (!positionsData) {
  33086. return this;
  33087. }
  33088. if (!(positionsData instanceof Float32Array)) {
  33089. positionsData = new Float32Array(positionsData);
  33090. }
  33091. // normalsData checks for not being Float32Array will only pass at most once
  33092. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33093. if (!normalsData) {
  33094. return this;
  33095. }
  33096. if (!(normalsData instanceof Float32Array)) {
  33097. normalsData = new Float32Array(normalsData);
  33098. }
  33099. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33100. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33101. if (!matricesWeightsData || !matricesIndicesData) {
  33102. return this;
  33103. }
  33104. var needExtras = this.numBoneInfluencers > 4;
  33105. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33106. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33107. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33108. var tempVector3 = BABYLON.Vector3.Zero();
  33109. var finalMatrix = new BABYLON.Matrix();
  33110. var tempMatrix = new BABYLON.Matrix();
  33111. var matWeightIdx = 0;
  33112. var inf;
  33113. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33114. var weight;
  33115. for (inf = 0; inf < 4; inf++) {
  33116. weight = matricesWeightsData[matWeightIdx + inf];
  33117. if (weight > 0) {
  33118. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33119. finalMatrix.addToSelf(tempMatrix);
  33120. }
  33121. else
  33122. break;
  33123. }
  33124. if (needExtras) {
  33125. for (inf = 0; inf < 4; inf++) {
  33126. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33127. if (weight > 0) {
  33128. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33129. finalMatrix.addToSelf(tempMatrix);
  33130. }
  33131. else
  33132. break;
  33133. }
  33134. }
  33135. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33136. tempVector3.toArray(positionsData, index);
  33137. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33138. tempVector3.toArray(normalsData, index);
  33139. finalMatrix.reset();
  33140. }
  33141. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33142. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33143. return this;
  33144. };
  33145. // Tools
  33146. /**
  33147. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33148. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33149. */
  33150. Mesh.MinMax = function (meshes) {
  33151. var minVector = null;
  33152. var maxVector = null;
  33153. meshes.forEach(function (mesh, index, array) {
  33154. var boundingInfo = mesh.getBoundingInfo();
  33155. var boundingBox = boundingInfo.boundingBox;
  33156. if (!minVector || !maxVector) {
  33157. minVector = boundingBox.minimumWorld;
  33158. maxVector = boundingBox.maximumWorld;
  33159. }
  33160. else {
  33161. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33162. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33163. }
  33164. });
  33165. if (!minVector || !maxVector) {
  33166. return {
  33167. min: BABYLON.Vector3.Zero(),
  33168. max: BABYLON.Vector3.Zero()
  33169. };
  33170. }
  33171. return {
  33172. min: minVector,
  33173. max: maxVector
  33174. };
  33175. };
  33176. /**
  33177. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33178. */
  33179. Mesh.Center = function (meshesOrMinMaxVector) {
  33180. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33181. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33182. };
  33183. /**
  33184. * Merge the array of meshes into a single mesh for performance reasons.
  33185. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33186. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33187. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33188. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33189. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33190. */
  33191. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33192. if (disposeSource === void 0) { disposeSource = true; }
  33193. var index;
  33194. if (!allow32BitsIndices) {
  33195. var totalVertices = 0;
  33196. // Counting vertices
  33197. for (index = 0; index < meshes.length; index++) {
  33198. if (meshes[index]) {
  33199. totalVertices += meshes[index].getTotalVertices();
  33200. if (totalVertices > 65536) {
  33201. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33202. return null;
  33203. }
  33204. }
  33205. }
  33206. }
  33207. // Merge
  33208. var vertexData = null;
  33209. var otherVertexData;
  33210. var indiceArray = new Array();
  33211. var source = null;
  33212. for (index = 0; index < meshes.length; index++) {
  33213. if (meshes[index]) {
  33214. meshes[index].computeWorldMatrix(true);
  33215. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33216. otherVertexData.transform(meshes[index].getWorldMatrix());
  33217. if (vertexData) {
  33218. vertexData.merge(otherVertexData);
  33219. }
  33220. else {
  33221. vertexData = otherVertexData;
  33222. source = meshes[index];
  33223. }
  33224. if (subdivideWithSubMeshes) {
  33225. indiceArray.push(meshes[index].getTotalIndices());
  33226. }
  33227. }
  33228. }
  33229. source = source;
  33230. if (!meshSubclass) {
  33231. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33232. }
  33233. vertexData.applyToMesh(meshSubclass);
  33234. // Setting properties
  33235. meshSubclass.material = source.material;
  33236. meshSubclass.checkCollisions = source.checkCollisions;
  33237. // Cleaning
  33238. if (disposeSource) {
  33239. for (index = 0; index < meshes.length; index++) {
  33240. if (meshes[index]) {
  33241. meshes[index].dispose();
  33242. }
  33243. }
  33244. }
  33245. // Subdivide
  33246. if (subdivideWithSubMeshes) {
  33247. //-- Suppresions du submesh global
  33248. meshSubclass.releaseSubMeshes();
  33249. index = 0;
  33250. var offset = 0;
  33251. //-- aplique la subdivision en fonction du tableau d'indices
  33252. while (index < indiceArray.length) {
  33253. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33254. offset += indiceArray[index];
  33255. index++;
  33256. }
  33257. }
  33258. return meshSubclass;
  33259. };
  33260. // Consts
  33261. Mesh._FRONTSIDE = 0;
  33262. Mesh._BACKSIDE = 1;
  33263. Mesh._DOUBLESIDE = 2;
  33264. Mesh._DEFAULTSIDE = 0;
  33265. Mesh._NO_CAP = 0;
  33266. Mesh._CAP_START = 1;
  33267. Mesh._CAP_END = 2;
  33268. Mesh._CAP_ALL = 3;
  33269. return Mesh;
  33270. }(BABYLON.AbstractMesh));
  33271. BABYLON.Mesh = Mesh;
  33272. })(BABYLON || (BABYLON = {}));
  33273. //# sourceMappingURL=babylon.mesh.js.map
  33274. "use strict";
  33275. var BABYLON;
  33276. (function (BABYLON) {
  33277. var BaseSubMesh = /** @class */ (function () {
  33278. function BaseSubMesh() {
  33279. }
  33280. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33281. get: function () {
  33282. return this._materialEffect;
  33283. },
  33284. enumerable: true,
  33285. configurable: true
  33286. });
  33287. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33288. if (defines === void 0) { defines = null; }
  33289. if (this._materialEffect === effect) {
  33290. if (!effect) {
  33291. this._materialDefines = null;
  33292. }
  33293. return;
  33294. }
  33295. this._materialDefines = defines;
  33296. this._materialEffect = effect;
  33297. };
  33298. return BaseSubMesh;
  33299. }());
  33300. BABYLON.BaseSubMesh = BaseSubMesh;
  33301. var SubMesh = /** @class */ (function (_super) {
  33302. __extends(SubMesh, _super);
  33303. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33304. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33305. var _this = _super.call(this) || this;
  33306. _this.materialIndex = materialIndex;
  33307. _this.verticesStart = verticesStart;
  33308. _this.verticesCount = verticesCount;
  33309. _this.indexStart = indexStart;
  33310. _this.indexCount = indexCount;
  33311. _this._renderId = 0;
  33312. _this._mesh = mesh;
  33313. _this._renderingMesh = renderingMesh || mesh;
  33314. mesh.subMeshes.push(_this);
  33315. _this._trianglePlanes = [];
  33316. _this._id = mesh.subMeshes.length - 1;
  33317. if (createBoundingBox) {
  33318. _this.refreshBoundingInfo();
  33319. mesh.computeWorldMatrix(true);
  33320. }
  33321. return _this;
  33322. }
  33323. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33324. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33325. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33326. };
  33327. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33328. get: function () {
  33329. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33330. },
  33331. enumerable: true,
  33332. configurable: true
  33333. });
  33334. /**
  33335. * Returns the submesh BoudingInfo object.
  33336. */
  33337. SubMesh.prototype.getBoundingInfo = function () {
  33338. if (this.IsGlobal) {
  33339. return this._mesh.getBoundingInfo();
  33340. }
  33341. return this._boundingInfo;
  33342. };
  33343. /**
  33344. * Sets the submesh BoundingInfo.
  33345. * Return the SubMesh.
  33346. */
  33347. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33348. this._boundingInfo = boundingInfo;
  33349. return this;
  33350. };
  33351. /**
  33352. * Returns the mesh of the current submesh.
  33353. */
  33354. SubMesh.prototype.getMesh = function () {
  33355. return this._mesh;
  33356. };
  33357. /**
  33358. * Returns the rendering mesh of the submesh.
  33359. */
  33360. SubMesh.prototype.getRenderingMesh = function () {
  33361. return this._renderingMesh;
  33362. };
  33363. /**
  33364. * Returns the submesh material.
  33365. */
  33366. SubMesh.prototype.getMaterial = function () {
  33367. var rootMaterial = this._renderingMesh.material;
  33368. if (rootMaterial === null || rootMaterial === undefined) {
  33369. return this._mesh.getScene().defaultMaterial;
  33370. }
  33371. else if (rootMaterial.getSubMaterial) {
  33372. var multiMaterial = rootMaterial;
  33373. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33374. if (this._currentMaterial !== effectiveMaterial) {
  33375. this._currentMaterial = effectiveMaterial;
  33376. this._materialDefines = null;
  33377. }
  33378. return effectiveMaterial;
  33379. }
  33380. return rootMaterial;
  33381. };
  33382. // Methods
  33383. /**
  33384. * Sets a new updated BoundingInfo object to the submesh.
  33385. * Returns the SubMesh.
  33386. */
  33387. SubMesh.prototype.refreshBoundingInfo = function () {
  33388. this._lastColliderWorldVertices = null;
  33389. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33390. return this;
  33391. }
  33392. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33393. if (!data) {
  33394. this._boundingInfo = this._mesh.getBoundingInfo();
  33395. return this;
  33396. }
  33397. var indices = this._renderingMesh.getIndices();
  33398. var extend;
  33399. //is this the only submesh?
  33400. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33401. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33402. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33403. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33404. }
  33405. else {
  33406. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33407. }
  33408. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33409. return this;
  33410. };
  33411. SubMesh.prototype._checkCollision = function (collider) {
  33412. var boundingInfo = this.getBoundingInfo();
  33413. return boundingInfo._checkCollision(collider);
  33414. };
  33415. /**
  33416. * Updates the submesh BoundingInfo.
  33417. * Returns the Submesh.
  33418. */
  33419. SubMesh.prototype.updateBoundingInfo = function (world) {
  33420. var boundingInfo = this.getBoundingInfo();
  33421. if (!boundingInfo) {
  33422. this.refreshBoundingInfo();
  33423. boundingInfo = this.getBoundingInfo();
  33424. }
  33425. boundingInfo.update(world);
  33426. return this;
  33427. };
  33428. /**
  33429. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33430. * Boolean returned.
  33431. */
  33432. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33433. var boundingInfo = this.getBoundingInfo();
  33434. if (!boundingInfo) {
  33435. return false;
  33436. }
  33437. return boundingInfo.isInFrustum(frustumPlanes);
  33438. };
  33439. /**
  33440. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33441. * Boolean returned.
  33442. */
  33443. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33444. var boundingInfo = this.getBoundingInfo();
  33445. if (!boundingInfo) {
  33446. return false;
  33447. }
  33448. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33449. };
  33450. /**
  33451. * Renders the submesh.
  33452. * Returns it.
  33453. */
  33454. SubMesh.prototype.render = function (enableAlphaMode) {
  33455. this._renderingMesh.render(this, enableAlphaMode);
  33456. return this;
  33457. };
  33458. /**
  33459. * Returns a new Index Buffer.
  33460. * Type returned : WebGLBuffer.
  33461. */
  33462. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33463. if (!this._linesIndexBuffer) {
  33464. var linesIndices = [];
  33465. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33466. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33467. }
  33468. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33469. this.linesIndexCount = linesIndices.length;
  33470. }
  33471. return this._linesIndexBuffer;
  33472. };
  33473. /**
  33474. * True is the passed Ray intersects the submesh bounding box.
  33475. * Boolean returned.
  33476. */
  33477. SubMesh.prototype.canIntersects = function (ray) {
  33478. var boundingInfo = this.getBoundingInfo();
  33479. if (!boundingInfo) {
  33480. return false;
  33481. }
  33482. return ray.intersectsBox(boundingInfo.boundingBox);
  33483. };
  33484. /**
  33485. * Returns an object IntersectionInfo.
  33486. */
  33487. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33488. var intersectInfo = null;
  33489. var material = this.getMaterial();
  33490. if (!material) {
  33491. return null;
  33492. }
  33493. switch (material.fillMode) {
  33494. case BABYLON.Material.PointListDrawMode:
  33495. case BABYLON.Material.LineListDrawMode:
  33496. case BABYLON.Material.LineLoopDrawMode:
  33497. case BABYLON.Material.LineStripDrawMode:
  33498. case BABYLON.Material.TriangleFanDrawMode:
  33499. case BABYLON.Material.TriangleStripDrawMode:
  33500. return null;
  33501. }
  33502. // LineMesh first as it's also a Mesh...
  33503. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33504. var lineMesh = this._mesh;
  33505. // Line test
  33506. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33507. var p0 = positions[indices[index]];
  33508. var p1 = positions[indices[index + 1]];
  33509. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33510. if (length < 0) {
  33511. continue;
  33512. }
  33513. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33514. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33515. if (fastCheck) {
  33516. break;
  33517. }
  33518. }
  33519. }
  33520. }
  33521. else {
  33522. // Triangles test
  33523. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33524. var p0 = positions[indices[index]];
  33525. var p1 = positions[indices[index + 1]];
  33526. var p2 = positions[indices[index + 2]];
  33527. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33528. if (currentIntersectInfo) {
  33529. if (currentIntersectInfo.distance < 0) {
  33530. continue;
  33531. }
  33532. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33533. intersectInfo = currentIntersectInfo;
  33534. intersectInfo.faceId = index / 3;
  33535. if (fastCheck) {
  33536. break;
  33537. }
  33538. }
  33539. }
  33540. }
  33541. }
  33542. return intersectInfo;
  33543. };
  33544. SubMesh.prototype._rebuild = function () {
  33545. if (this._linesIndexBuffer) {
  33546. this._linesIndexBuffer = null;
  33547. }
  33548. };
  33549. // Clone
  33550. /**
  33551. * Creates a new Submesh from the passed Mesh.
  33552. */
  33553. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33554. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33555. if (!this.IsGlobal) {
  33556. var boundingInfo = this.getBoundingInfo();
  33557. if (!boundingInfo) {
  33558. return result;
  33559. }
  33560. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33561. }
  33562. return result;
  33563. };
  33564. // Dispose
  33565. /**
  33566. * Disposes the Submesh.
  33567. * Returns nothing.
  33568. */
  33569. SubMesh.prototype.dispose = function () {
  33570. if (this._linesIndexBuffer) {
  33571. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33572. this._linesIndexBuffer = null;
  33573. }
  33574. // Remove from mesh
  33575. var index = this._mesh.subMeshes.indexOf(this);
  33576. this._mesh.subMeshes.splice(index, 1);
  33577. };
  33578. // Statics
  33579. /**
  33580. * Creates a new Submesh from the passed parameters :
  33581. * - materialIndex (integer) : the index of the main mesh material.
  33582. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33583. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33584. * - mesh (Mesh) : the main mesh to create the submesh from.
  33585. * - renderingMesh (optional Mesh) : rendering mesh.
  33586. */
  33587. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33588. var minVertexIndex = Number.MAX_VALUE;
  33589. var maxVertexIndex = -Number.MAX_VALUE;
  33590. renderingMesh = (renderingMesh || mesh);
  33591. var indices = renderingMesh.getIndices();
  33592. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33593. var vertexIndex = indices[index];
  33594. if (vertexIndex < minVertexIndex)
  33595. minVertexIndex = vertexIndex;
  33596. if (vertexIndex > maxVertexIndex)
  33597. maxVertexIndex = vertexIndex;
  33598. }
  33599. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33600. };
  33601. return SubMesh;
  33602. }(BaseSubMesh));
  33603. BABYLON.SubMesh = SubMesh;
  33604. })(BABYLON || (BABYLON = {}));
  33605. //# sourceMappingURL=babylon.subMesh.js.map
  33606. "use strict";
  33607. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33608. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33609. s = arguments[i];
  33610. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33611. t[p] = s[p];
  33612. }
  33613. return t;
  33614. };
  33615. var BABYLON;
  33616. (function (BABYLON) {
  33617. /**
  33618. * Manages the defines for the Material
  33619. */
  33620. var MaterialDefines = /** @class */ (function () {
  33621. function MaterialDefines() {
  33622. this._isDirty = true;
  33623. /** @ignore */
  33624. this._areLightsDirty = true;
  33625. /** @ignore */
  33626. this._areAttributesDirty = true;
  33627. /** @ignore */
  33628. this._areTexturesDirty = true;
  33629. /** @ignore */
  33630. this._areFresnelDirty = true;
  33631. /** @ignore */
  33632. this._areMiscDirty = true;
  33633. /** @ignore */
  33634. this._areImageProcessingDirty = true;
  33635. /** @ignore */
  33636. this._normals = false;
  33637. /** @ignore */
  33638. this._uvs = false;
  33639. /** @ignore */
  33640. this._needNormals = false;
  33641. /** @ignore */
  33642. this._needUVs = false;
  33643. }
  33644. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33645. /**
  33646. * Specifies if the material needs to be re-calculated
  33647. */
  33648. get: function () {
  33649. return this._isDirty;
  33650. },
  33651. enumerable: true,
  33652. configurable: true
  33653. });
  33654. /**
  33655. * Marks the material to indicate that it has been re-calculated
  33656. */
  33657. MaterialDefines.prototype.markAsProcessed = function () {
  33658. this._isDirty = false;
  33659. this._areAttributesDirty = false;
  33660. this._areTexturesDirty = false;
  33661. this._areFresnelDirty = false;
  33662. this._areLightsDirty = false;
  33663. this._areMiscDirty = false;
  33664. this._areImageProcessingDirty = false;
  33665. };
  33666. /**
  33667. * Marks the material to indicate that it needs to be re-calculated
  33668. */
  33669. MaterialDefines.prototype.markAsUnprocessed = function () {
  33670. this._isDirty = true;
  33671. };
  33672. /**
  33673. * Marks the material to indicate all of its defines need to be re-calculated
  33674. */
  33675. MaterialDefines.prototype.markAllAsDirty = function () {
  33676. this._areTexturesDirty = true;
  33677. this._areAttributesDirty = true;
  33678. this._areLightsDirty = true;
  33679. this._areFresnelDirty = true;
  33680. this._areMiscDirty = true;
  33681. this._areImageProcessingDirty = true;
  33682. this._isDirty = true;
  33683. };
  33684. /**
  33685. * Marks the material to indicate that image processing needs to be re-calculated
  33686. */
  33687. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33688. this._areImageProcessingDirty = true;
  33689. this._isDirty = true;
  33690. };
  33691. /**
  33692. * Marks the material to indicate the lights need to be re-calculated
  33693. */
  33694. MaterialDefines.prototype.markAsLightDirty = function () {
  33695. this._areLightsDirty = true;
  33696. this._isDirty = true;
  33697. };
  33698. /**
  33699. * Marks the attribute state as changed
  33700. */
  33701. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33702. this._areAttributesDirty = true;
  33703. this._isDirty = true;
  33704. };
  33705. /**
  33706. * Marks the texture state as changed
  33707. */
  33708. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33709. this._areTexturesDirty = true;
  33710. this._isDirty = true;
  33711. };
  33712. /**
  33713. * Marks the fresnel state as changed
  33714. */
  33715. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33716. this._areFresnelDirty = true;
  33717. this._isDirty = true;
  33718. };
  33719. /**
  33720. * Marks the misc state as changed
  33721. */
  33722. MaterialDefines.prototype.markAsMiscDirty = function () {
  33723. this._areMiscDirty = true;
  33724. this._isDirty = true;
  33725. };
  33726. /**
  33727. * Rebuilds the material defines
  33728. */
  33729. MaterialDefines.prototype.rebuild = function () {
  33730. if (this._keys) {
  33731. delete this._keys;
  33732. }
  33733. this._keys = [];
  33734. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  33735. var key = _a[_i];
  33736. if (key[0] === "_") {
  33737. continue;
  33738. }
  33739. this._keys.push(key);
  33740. }
  33741. };
  33742. /**
  33743. * Specifies if two material defines are equal
  33744. * @param other - A material define instance to compare to
  33745. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  33746. */
  33747. MaterialDefines.prototype.isEqual = function (other) {
  33748. if (this._keys.length !== other._keys.length) {
  33749. return false;
  33750. }
  33751. for (var index = 0; index < this._keys.length; index++) {
  33752. var prop = this._keys[index];
  33753. if (this[prop] !== other[prop]) {
  33754. return false;
  33755. }
  33756. }
  33757. return true;
  33758. };
  33759. /**
  33760. * Clones this instance's defines to another instance
  33761. * @param other - material defines to clone values to
  33762. */
  33763. MaterialDefines.prototype.cloneTo = function (other) {
  33764. if (this._keys.length !== other._keys.length) {
  33765. other._keys = this._keys.slice(0);
  33766. }
  33767. for (var index = 0; index < this._keys.length; index++) {
  33768. var prop = this._keys[index];
  33769. other[prop] = this[prop];
  33770. }
  33771. };
  33772. /**
  33773. * Resets the material define values
  33774. */
  33775. MaterialDefines.prototype.reset = function () {
  33776. for (var index = 0; index < this._keys.length; index++) {
  33777. var prop = this._keys[index];
  33778. var type = typeof this[prop];
  33779. switch (type) {
  33780. case "number":
  33781. this[prop] = 0;
  33782. break;
  33783. case "string":
  33784. this[prop] = "";
  33785. break;
  33786. default:
  33787. this[prop] = false;
  33788. break;
  33789. }
  33790. }
  33791. };
  33792. /**
  33793. * Converts the material define values to a string
  33794. * @returns - String of material define information
  33795. */
  33796. MaterialDefines.prototype.toString = function () {
  33797. var result = "";
  33798. for (var index = 0; index < this._keys.length; index++) {
  33799. var prop = this._keys[index];
  33800. var value = this[prop];
  33801. var type = typeof value;
  33802. switch (type) {
  33803. case "number":
  33804. case "string":
  33805. result += "#define " + prop + " " + value + "\n";
  33806. break;
  33807. default:
  33808. if (value) {
  33809. result += "#define " + prop + "\n";
  33810. }
  33811. break;
  33812. }
  33813. }
  33814. return result;
  33815. };
  33816. return MaterialDefines;
  33817. }());
  33818. BABYLON.MaterialDefines = MaterialDefines;
  33819. /**
  33820. * Base class for the main features of a material in Babylon.js
  33821. */
  33822. var Material = /** @class */ (function () {
  33823. /**
  33824. * Creates a material instance
  33825. * @param name defines the name of the material
  33826. * @param scene defines the scene to reference
  33827. * @param doNotAdd specifies if the material should be added to the scene
  33828. */
  33829. function Material(name, scene, doNotAdd) {
  33830. /**
  33831. * Specifies if the ready state should be checked on each call
  33832. */
  33833. this.checkReadyOnEveryCall = false;
  33834. /**
  33835. * Specifies if the ready state should be checked once
  33836. */
  33837. this.checkReadyOnlyOnce = false;
  33838. /**
  33839. * The state of the material
  33840. */
  33841. this.state = "";
  33842. /**
  33843. * The alpha value of the material
  33844. */
  33845. this._alpha = 1.0;
  33846. /**
  33847. * Specifies if back face culling is enabled
  33848. */
  33849. this._backFaceCulling = true;
  33850. /**
  33851. * Specifies if the material should be serialized
  33852. */
  33853. this.doNotSerialize = false;
  33854. /**
  33855. * Specifies if the effect should be stored on sub meshes
  33856. */
  33857. this.storeEffectOnSubMeshes = false;
  33858. /**
  33859. * An event triggered when the material is disposed
  33860. */
  33861. this.onDisposeObservable = new BABYLON.Observable();
  33862. /**
  33863. * An event triggered when the material is bound
  33864. */
  33865. this.onBindObservable = new BABYLON.Observable();
  33866. /**
  33867. * An event triggered when the material is unbound
  33868. */
  33869. this.onUnBindObservable = new BABYLON.Observable();
  33870. /**
  33871. * Stores the value of the alpha mode
  33872. */
  33873. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  33874. /**
  33875. * Stores the state of the need depth pre-pass value
  33876. */
  33877. this._needDepthPrePass = false;
  33878. /**
  33879. * Specifies if depth writing should be disabled
  33880. */
  33881. this.disableDepthWrite = false;
  33882. /**
  33883. * Specifies if depth writing should be forced
  33884. */
  33885. this.forceDepthWrite = false;
  33886. /**
  33887. * Specifies if there should be a separate pass for culling
  33888. */
  33889. this.separateCullingPass = false;
  33890. /**
  33891. * Stores the state specifing if fog should be enabled
  33892. */
  33893. this._fogEnabled = true;
  33894. /**
  33895. * Stores the size of points
  33896. */
  33897. this.pointSize = 1.0;
  33898. /**
  33899. * Stores the z offset value
  33900. */
  33901. this.zOffset = 0;
  33902. /**
  33903. * Specifies if the material was previously ready
  33904. */
  33905. this._wasPreviouslyReady = false;
  33906. /**
  33907. * Stores the fill mode state
  33908. */
  33909. this._fillMode = Material.TriangleFillMode;
  33910. this.name = name;
  33911. this.id = name || BABYLON.Tools.RandomId();
  33912. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33913. if (this._scene.useRightHandedSystem) {
  33914. this.sideOrientation = Material.ClockWiseSideOrientation;
  33915. }
  33916. else {
  33917. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  33918. }
  33919. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  33920. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  33921. if (!doNotAdd) {
  33922. this._scene.materials.push(this);
  33923. }
  33924. }
  33925. Object.defineProperty(Material, "TriangleFillMode", {
  33926. /**
  33927. * Returns the triangle fill mode
  33928. */
  33929. get: function () {
  33930. return Material._TriangleFillMode;
  33931. },
  33932. enumerable: true,
  33933. configurable: true
  33934. });
  33935. Object.defineProperty(Material, "WireFrameFillMode", {
  33936. /**
  33937. * Returns the wireframe mode
  33938. */
  33939. get: function () {
  33940. return Material._WireFrameFillMode;
  33941. },
  33942. enumerable: true,
  33943. configurable: true
  33944. });
  33945. Object.defineProperty(Material, "PointFillMode", {
  33946. /**
  33947. * Returns the point fill mode
  33948. */
  33949. get: function () {
  33950. return Material._PointFillMode;
  33951. },
  33952. enumerable: true,
  33953. configurable: true
  33954. });
  33955. Object.defineProperty(Material, "PointListDrawMode", {
  33956. /**
  33957. * Returns the point list draw mode
  33958. */
  33959. get: function () {
  33960. return Material._PointListDrawMode;
  33961. },
  33962. enumerable: true,
  33963. configurable: true
  33964. });
  33965. Object.defineProperty(Material, "LineListDrawMode", {
  33966. /**
  33967. * Returns the line list draw mode
  33968. */
  33969. get: function () {
  33970. return Material._LineListDrawMode;
  33971. },
  33972. enumerable: true,
  33973. configurable: true
  33974. });
  33975. Object.defineProperty(Material, "LineLoopDrawMode", {
  33976. /**
  33977. * Returns the line loop draw mode
  33978. */
  33979. get: function () {
  33980. return Material._LineLoopDrawMode;
  33981. },
  33982. enumerable: true,
  33983. configurable: true
  33984. });
  33985. Object.defineProperty(Material, "LineStripDrawMode", {
  33986. /**
  33987. * Returns the line strip draw mode
  33988. */
  33989. get: function () {
  33990. return Material._LineStripDrawMode;
  33991. },
  33992. enumerable: true,
  33993. configurable: true
  33994. });
  33995. Object.defineProperty(Material, "TriangleStripDrawMode", {
  33996. /**
  33997. * Returns the triangle strip draw mode
  33998. */
  33999. get: function () {
  34000. return Material._TriangleStripDrawMode;
  34001. },
  34002. enumerable: true,
  34003. configurable: true
  34004. });
  34005. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34006. /**
  34007. * Returns the triangle fan draw mode
  34008. */
  34009. get: function () {
  34010. return Material._TriangleFanDrawMode;
  34011. },
  34012. enumerable: true,
  34013. configurable: true
  34014. });
  34015. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34016. /**
  34017. * Returns the clock-wise side orientation
  34018. */
  34019. get: function () {
  34020. return Material._ClockWiseSideOrientation;
  34021. },
  34022. enumerable: true,
  34023. configurable: true
  34024. });
  34025. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34026. /**
  34027. * Returns the counter clock-wise side orientation
  34028. */
  34029. get: function () {
  34030. return Material._CounterClockWiseSideOrientation;
  34031. },
  34032. enumerable: true,
  34033. configurable: true
  34034. });
  34035. Object.defineProperty(Material, "TextureDirtyFlag", {
  34036. /**
  34037. * Returns the dirty texture flag value
  34038. */
  34039. get: function () {
  34040. return Material._TextureDirtyFlag;
  34041. },
  34042. enumerable: true,
  34043. configurable: true
  34044. });
  34045. Object.defineProperty(Material, "LightDirtyFlag", {
  34046. /**
  34047. * Returns the dirty light flag value
  34048. */
  34049. get: function () {
  34050. return Material._LightDirtyFlag;
  34051. },
  34052. enumerable: true,
  34053. configurable: true
  34054. });
  34055. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34056. /**
  34057. * Returns the dirty fresnel flag value
  34058. */
  34059. get: function () {
  34060. return Material._FresnelDirtyFlag;
  34061. },
  34062. enumerable: true,
  34063. configurable: true
  34064. });
  34065. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34066. /**
  34067. * Returns the dirty attributes flag value
  34068. */
  34069. get: function () {
  34070. return Material._AttributesDirtyFlag;
  34071. },
  34072. enumerable: true,
  34073. configurable: true
  34074. });
  34075. Object.defineProperty(Material, "MiscDirtyFlag", {
  34076. /**
  34077. * Returns the dirty misc flag value
  34078. */
  34079. get: function () {
  34080. return Material._MiscDirtyFlag;
  34081. },
  34082. enumerable: true,
  34083. configurable: true
  34084. });
  34085. Object.defineProperty(Material.prototype, "alpha", {
  34086. /**
  34087. * Gets the alpha value of the material
  34088. */
  34089. get: function () {
  34090. return this._alpha;
  34091. },
  34092. /**
  34093. * Sets the alpha value of the material
  34094. */
  34095. set: function (value) {
  34096. if (this._alpha === value) {
  34097. return;
  34098. }
  34099. this._alpha = value;
  34100. this.markAsDirty(Material.MiscDirtyFlag);
  34101. },
  34102. enumerable: true,
  34103. configurable: true
  34104. });
  34105. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34106. /**
  34107. * Gets the back-face culling state
  34108. */
  34109. get: function () {
  34110. return this._backFaceCulling;
  34111. },
  34112. /**
  34113. * Sets the back-face culling state
  34114. */
  34115. set: function (value) {
  34116. if (this._backFaceCulling === value) {
  34117. return;
  34118. }
  34119. this._backFaceCulling = value;
  34120. this.markAsDirty(Material.TextureDirtyFlag);
  34121. },
  34122. enumerable: true,
  34123. configurable: true
  34124. });
  34125. Object.defineProperty(Material.prototype, "onDispose", {
  34126. /**
  34127. * Called during a dispose event
  34128. */
  34129. set: function (callback) {
  34130. if (this._onDisposeObserver) {
  34131. this.onDisposeObservable.remove(this._onDisposeObserver);
  34132. }
  34133. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34134. },
  34135. enumerable: true,
  34136. configurable: true
  34137. });
  34138. Object.defineProperty(Material.prototype, "onBind", {
  34139. /**
  34140. * Called during a bind event
  34141. */
  34142. set: function (callback) {
  34143. if (this._onBindObserver) {
  34144. this.onBindObservable.remove(this._onBindObserver);
  34145. }
  34146. this._onBindObserver = this.onBindObservable.add(callback);
  34147. },
  34148. enumerable: true,
  34149. configurable: true
  34150. });
  34151. Object.defineProperty(Material.prototype, "alphaMode", {
  34152. /**
  34153. * Gets the value of the alpha mode
  34154. */
  34155. get: function () {
  34156. return this._alphaMode;
  34157. },
  34158. /**
  34159. * Sets the value of the alpha mode.
  34160. *
  34161. * | Value | Type | Description |
  34162. * | --- | --- | --- |
  34163. * | 0 | ALPHA_DISABLE | |
  34164. * | 1 | ALPHA_ADD | |
  34165. * | 2 | ALPHA_COMBINE | |
  34166. * | 3 | ALPHA_SUBTRACT | |
  34167. * | 4 | ALPHA_MULTIPLY | |
  34168. * | 5 | ALPHA_MAXIMIZED | |
  34169. * | 6 | ALPHA_ONEONE | |
  34170. * | 7 | ALPHA_PREMULTIPLIED | |
  34171. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34172. * | 9 | ALPHA_INTERPOLATE | |
  34173. * | 10 | ALPHA_SCREENMODE | |
  34174. *
  34175. */
  34176. set: function (value) {
  34177. if (this._alphaMode === value) {
  34178. return;
  34179. }
  34180. this._alphaMode = value;
  34181. this.markAsDirty(Material.TextureDirtyFlag);
  34182. },
  34183. enumerable: true,
  34184. configurable: true
  34185. });
  34186. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34187. /**
  34188. * Gets the depth pre-pass value
  34189. */
  34190. get: function () {
  34191. return this._needDepthPrePass;
  34192. },
  34193. /**
  34194. * Sets the need depth pre-pass value
  34195. */
  34196. set: function (value) {
  34197. if (this._needDepthPrePass === value) {
  34198. return;
  34199. }
  34200. this._needDepthPrePass = value;
  34201. if (this._needDepthPrePass) {
  34202. this.checkReadyOnEveryCall = true;
  34203. }
  34204. },
  34205. enumerable: true,
  34206. configurable: true
  34207. });
  34208. Object.defineProperty(Material.prototype, "fogEnabled", {
  34209. /**
  34210. * Gets the value of the fog enabled state
  34211. */
  34212. get: function () {
  34213. return this._fogEnabled;
  34214. },
  34215. /**
  34216. * Sets the state for enabling fog
  34217. */
  34218. set: function (value) {
  34219. if (this._fogEnabled === value) {
  34220. return;
  34221. }
  34222. this._fogEnabled = value;
  34223. this.markAsDirty(Material.MiscDirtyFlag);
  34224. },
  34225. enumerable: true,
  34226. configurable: true
  34227. });
  34228. Object.defineProperty(Material.prototype, "wireframe", {
  34229. /**
  34230. * Gets a value specifying if wireframe mode is enabled
  34231. */
  34232. get: function () {
  34233. switch (this._fillMode) {
  34234. case Material.WireFrameFillMode:
  34235. case Material.LineListDrawMode:
  34236. case Material.LineLoopDrawMode:
  34237. case Material.LineStripDrawMode:
  34238. return true;
  34239. }
  34240. return this._scene.forceWireframe;
  34241. },
  34242. /**
  34243. * Sets the state of wireframe mode
  34244. */
  34245. set: function (value) {
  34246. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34247. },
  34248. enumerable: true,
  34249. configurable: true
  34250. });
  34251. Object.defineProperty(Material.prototype, "pointsCloud", {
  34252. /**
  34253. * Gets the value specifying if point clouds are enabled
  34254. */
  34255. get: function () {
  34256. switch (this._fillMode) {
  34257. case Material.PointFillMode:
  34258. case Material.PointListDrawMode:
  34259. return true;
  34260. }
  34261. return this._scene.forcePointsCloud;
  34262. },
  34263. /**
  34264. * Sets the state of point cloud mode
  34265. */
  34266. set: function (value) {
  34267. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34268. },
  34269. enumerable: true,
  34270. configurable: true
  34271. });
  34272. Object.defineProperty(Material.prototype, "fillMode", {
  34273. /**
  34274. * Gets the material fill mode
  34275. */
  34276. get: function () {
  34277. return this._fillMode;
  34278. },
  34279. /**
  34280. * Sets the material fill mode
  34281. */
  34282. set: function (value) {
  34283. if (this._fillMode === value) {
  34284. return;
  34285. }
  34286. this._fillMode = value;
  34287. this.markAsDirty(Material.MiscDirtyFlag);
  34288. },
  34289. enumerable: true,
  34290. configurable: true
  34291. });
  34292. /**
  34293. * Returns a string representation of the current material
  34294. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34295. * @returns a string with material information
  34296. */
  34297. Material.prototype.toString = function (fullDetails) {
  34298. var ret = "Name: " + this.name;
  34299. if (fullDetails) {
  34300. }
  34301. return ret;
  34302. };
  34303. /**
  34304. * Gets the class name of the material
  34305. * @returns a string with the class name of the material
  34306. */
  34307. Material.prototype.getClassName = function () {
  34308. return "Material";
  34309. };
  34310. Object.defineProperty(Material.prototype, "isFrozen", {
  34311. /**
  34312. * Specifies if updates for the material been locked
  34313. */
  34314. get: function () {
  34315. return this.checkReadyOnlyOnce;
  34316. },
  34317. enumerable: true,
  34318. configurable: true
  34319. });
  34320. /**
  34321. * Locks updates for the material
  34322. */
  34323. Material.prototype.freeze = function () {
  34324. this.checkReadyOnlyOnce = true;
  34325. };
  34326. /**
  34327. * Unlocks updates for the material
  34328. */
  34329. Material.prototype.unfreeze = function () {
  34330. this.checkReadyOnlyOnce = false;
  34331. };
  34332. /**
  34333. * Specifies if the material is ready to be used
  34334. * @param mesh defines the mesh to check
  34335. * @param useInstances specifies if instances should be used
  34336. * @returns a boolean indicating if the material is ready to be used
  34337. */
  34338. Material.prototype.isReady = function (mesh, useInstances) {
  34339. return true;
  34340. };
  34341. /**
  34342. * Specifies that the submesh is ready to be used
  34343. * @param mesh defines the mesh to check
  34344. * @param subMesh defines which submesh to check
  34345. * @param useInstances specifies that instances should be used
  34346. * @returns a boolean indicating that the submesh is ready or not
  34347. */
  34348. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34349. return false;
  34350. };
  34351. /**
  34352. * Returns the material effect
  34353. * @returns the effect associated with the material
  34354. */
  34355. Material.prototype.getEffect = function () {
  34356. return this._effect;
  34357. };
  34358. /**
  34359. * Returns the current scene
  34360. * @returns a Scene
  34361. */
  34362. Material.prototype.getScene = function () {
  34363. return this._scene;
  34364. };
  34365. /**
  34366. * Specifies if the material will require alpha blending
  34367. * @returns a boolean specifying if alpha blending is needed
  34368. */
  34369. Material.prototype.needAlphaBlending = function () {
  34370. return (this.alpha < 1.0);
  34371. };
  34372. /**
  34373. * Specifies if the mesh will require alpha blending
  34374. * @param mesh defines the mesh to check
  34375. * @returns a boolean specifying if alpha blending is needed for the mesh
  34376. */
  34377. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34378. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34379. };
  34380. /**
  34381. * Specifies if this material should be rendered in alpha test mode
  34382. * @returns a boolean specifying if an alpha test is needed.
  34383. */
  34384. Material.prototype.needAlphaTesting = function () {
  34385. return false;
  34386. };
  34387. /**
  34388. * Gets the texture used for the alpha test
  34389. * @returns the texture to use for alpha testing
  34390. */
  34391. Material.prototype.getAlphaTestTexture = function () {
  34392. return null;
  34393. };
  34394. /**
  34395. * Marks the material to indicate that it needs to be re-calculated
  34396. */
  34397. Material.prototype.markDirty = function () {
  34398. this._wasPreviouslyReady = false;
  34399. };
  34400. /** @ignore */
  34401. Material.prototype._preBind = function (effect, overrideOrientation) {
  34402. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34403. var engine = this._scene.getEngine();
  34404. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34405. var reverse = orientation === Material.ClockWiseSideOrientation;
  34406. engine.enableEffect(effect ? effect : this._effect);
  34407. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34408. return reverse;
  34409. };
  34410. /**
  34411. * Binds the material to the mesh
  34412. * @param world defines the world transformation matrix
  34413. * @param mesh defines the mesh to bind the material to
  34414. */
  34415. Material.prototype.bind = function (world, mesh) {
  34416. };
  34417. /**
  34418. * Binds the submesh to the material
  34419. * @param world defines the world transformation matrix
  34420. * @param mesh defines the mesh containing the submesh
  34421. * @param subMesh defines the submesh to bind the material to
  34422. */
  34423. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34424. };
  34425. /**
  34426. * Binds the world matrix to the material
  34427. * @param world defines the world transformation matrix
  34428. */
  34429. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34430. };
  34431. /**
  34432. * Binds the scene's uniform buffer to the effect.
  34433. * @param effect defines the effect to bind to the scene uniform buffer
  34434. * @param sceneUbo defines the uniform buffer storing scene data
  34435. */
  34436. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34437. sceneUbo.bindToEffect(effect, "Scene");
  34438. };
  34439. /**
  34440. * Binds the view matrix to the effect
  34441. * @param effect defines the effect to bind the view matrix to
  34442. */
  34443. Material.prototype.bindView = function (effect) {
  34444. if (!this._useUBO) {
  34445. effect.setMatrix("view", this.getScene().getViewMatrix());
  34446. }
  34447. else {
  34448. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34449. }
  34450. };
  34451. /**
  34452. * Binds the view projection matrix to the effect
  34453. * @param effect defines the effect to bind the view projection matrix to
  34454. */
  34455. Material.prototype.bindViewProjection = function (effect) {
  34456. if (!this._useUBO) {
  34457. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34458. }
  34459. else {
  34460. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34461. }
  34462. };
  34463. /**
  34464. * Specifies if material alpha testing should be turned on for the mesh
  34465. * @param mesh defines the mesh to check
  34466. */
  34467. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34468. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34469. };
  34470. /**
  34471. * Processes to execute after binding the material to a mesh
  34472. * @param mesh defines the rendered mesh
  34473. */
  34474. Material.prototype._afterBind = function (mesh) {
  34475. this._scene._cachedMaterial = this;
  34476. if (mesh) {
  34477. this._scene._cachedVisibility = mesh.visibility;
  34478. }
  34479. else {
  34480. this._scene._cachedVisibility = 1;
  34481. }
  34482. if (mesh) {
  34483. this.onBindObservable.notifyObservers(mesh);
  34484. }
  34485. if (this.disableDepthWrite) {
  34486. var engine = this._scene.getEngine();
  34487. this._cachedDepthWriteState = engine.getDepthWrite();
  34488. engine.setDepthWrite(false);
  34489. }
  34490. };
  34491. /**
  34492. * Unbinds the material from the mesh
  34493. */
  34494. Material.prototype.unbind = function () {
  34495. this.onUnBindObservable.notifyObservers(this);
  34496. if (this.disableDepthWrite) {
  34497. var engine = this._scene.getEngine();
  34498. engine.setDepthWrite(this._cachedDepthWriteState);
  34499. }
  34500. };
  34501. /**
  34502. * Gets the active textures from the material
  34503. * @returns an array of textures
  34504. */
  34505. Material.prototype.getActiveTextures = function () {
  34506. return [];
  34507. };
  34508. /**
  34509. * Specifies if the material uses a texture
  34510. * @param texture defines the texture to check against the material
  34511. * @returns a boolean specifying if the material uses the texture
  34512. */
  34513. Material.prototype.hasTexture = function (texture) {
  34514. return false;
  34515. };
  34516. /**
  34517. * Makes a duplicate of the material, and gives it a new name
  34518. * @param name defines the new name for the duplicated material
  34519. * @returns the cloned material
  34520. */
  34521. Material.prototype.clone = function (name) {
  34522. return null;
  34523. };
  34524. /**
  34525. * Gets the meshes bound to the material
  34526. * @returns an array of meshes bound to the material
  34527. */
  34528. Material.prototype.getBindedMeshes = function () {
  34529. var result = new Array();
  34530. for (var index = 0; index < this._scene.meshes.length; index++) {
  34531. var mesh = this._scene.meshes[index];
  34532. if (mesh.material === this) {
  34533. result.push(mesh);
  34534. }
  34535. }
  34536. return result;
  34537. };
  34538. /**
  34539. * Force shader compilation
  34540. * @param mesh defines the mesh associated with this material
  34541. * @param onCompiled defines a function to execute once the material is compiled
  34542. * @param options defines the options to configure the compilation
  34543. */
  34544. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34545. var _this = this;
  34546. var localOptions = __assign({ clipPlane: false }, options);
  34547. var subMesh = new BABYLON.BaseSubMesh();
  34548. var scene = this.getScene();
  34549. var checkReady = function () {
  34550. if (!_this._scene || !_this._scene.getEngine()) {
  34551. return;
  34552. }
  34553. if (subMesh._materialDefines) {
  34554. subMesh._materialDefines._renderId = -1;
  34555. }
  34556. var clipPlaneState = scene.clipPlane;
  34557. if (localOptions.clipPlane) {
  34558. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34559. }
  34560. if (_this.storeEffectOnSubMeshes) {
  34561. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34562. if (onCompiled) {
  34563. onCompiled(_this);
  34564. }
  34565. }
  34566. else {
  34567. setTimeout(checkReady, 16);
  34568. }
  34569. }
  34570. else {
  34571. if (_this.isReady(mesh)) {
  34572. if (onCompiled) {
  34573. onCompiled(_this);
  34574. }
  34575. }
  34576. else {
  34577. setTimeout(checkReady, 16);
  34578. }
  34579. }
  34580. if (localOptions.clipPlane) {
  34581. scene.clipPlane = clipPlaneState;
  34582. }
  34583. };
  34584. checkReady();
  34585. };
  34586. /**
  34587. * Force shader compilation
  34588. * @param mesh defines the mesh that will use this material
  34589. * @param options defines additional options for compiling the shaders
  34590. * @returns a promise that resolves when the compilation completes
  34591. */
  34592. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34593. var _this = this;
  34594. return new Promise(function (resolve) {
  34595. _this.forceCompilation(mesh, function () {
  34596. resolve();
  34597. }, options);
  34598. });
  34599. };
  34600. /**
  34601. * Marks a define in the material to indicate that it needs to be re-computed
  34602. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34603. */
  34604. Material.prototype.markAsDirty = function (flag) {
  34605. if (flag & Material.TextureDirtyFlag) {
  34606. this._markAllSubMeshesAsTexturesDirty();
  34607. }
  34608. if (flag & Material.LightDirtyFlag) {
  34609. this._markAllSubMeshesAsLightsDirty();
  34610. }
  34611. if (flag & Material.FresnelDirtyFlag) {
  34612. this._markAllSubMeshesAsFresnelDirty();
  34613. }
  34614. if (flag & Material.AttributesDirtyFlag) {
  34615. this._markAllSubMeshesAsAttributesDirty();
  34616. }
  34617. if (flag & Material.MiscDirtyFlag) {
  34618. this._markAllSubMeshesAsMiscDirty();
  34619. }
  34620. this.getScene().resetCachedMaterial();
  34621. };
  34622. /**
  34623. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34624. * @param func defines a function which checks material defines against the submeshes
  34625. */
  34626. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34627. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34628. var mesh = _a[_i];
  34629. if (!mesh.subMeshes) {
  34630. continue;
  34631. }
  34632. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34633. var subMesh = _c[_b];
  34634. if (subMesh.getMaterial() !== this) {
  34635. continue;
  34636. }
  34637. if (!subMesh._materialDefines) {
  34638. continue;
  34639. }
  34640. func(subMesh._materialDefines);
  34641. }
  34642. }
  34643. };
  34644. /**
  34645. * Indicates that image processing needs to be re-calculated for all submeshes
  34646. */
  34647. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34648. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34649. };
  34650. /**
  34651. * Indicates that textures need to be re-calculated for all submeshes
  34652. */
  34653. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34654. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34655. };
  34656. /**
  34657. * Indicates that fresnel needs to be re-calculated for all submeshes
  34658. */
  34659. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34660. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34661. };
  34662. /**
  34663. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34664. */
  34665. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34666. this._markAllSubMeshesAsDirty(function (defines) {
  34667. defines.markAsFresnelDirty();
  34668. defines.markAsMiscDirty();
  34669. });
  34670. };
  34671. /**
  34672. * Indicates that lights need to be re-calculated for all submeshes
  34673. */
  34674. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34675. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34676. };
  34677. /**
  34678. * Indicates that attributes need to be re-calculated for all submeshes
  34679. */
  34680. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34681. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34682. };
  34683. /**
  34684. * Indicates that misc needs to be re-calculated for all submeshes
  34685. */
  34686. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34687. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34688. };
  34689. /**
  34690. * Indicates that textures and misc need to be re-calculated for all submeshes
  34691. */
  34692. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34693. this._markAllSubMeshesAsDirty(function (defines) {
  34694. defines.markAsTexturesDirty();
  34695. defines.markAsMiscDirty();
  34696. });
  34697. };
  34698. /**
  34699. * Disposes the material
  34700. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34701. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34702. */
  34703. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34704. // Animations
  34705. this.getScene().stopAnimation(this);
  34706. this.getScene().freeProcessedMaterials();
  34707. // Remove from scene
  34708. var index = this._scene.materials.indexOf(this);
  34709. if (index >= 0) {
  34710. this._scene.materials.splice(index, 1);
  34711. }
  34712. // Remove from meshes
  34713. for (index = 0; index < this._scene.meshes.length; index++) {
  34714. var mesh = this._scene.meshes[index];
  34715. if (mesh.material === this) {
  34716. mesh.material = null;
  34717. if (mesh.geometry) {
  34718. var geometry = (mesh.geometry);
  34719. if (this.storeEffectOnSubMeshes) {
  34720. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34721. var subMesh = _a[_i];
  34722. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34723. if (forceDisposeEffect && subMesh._materialEffect) {
  34724. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34725. }
  34726. }
  34727. }
  34728. else {
  34729. geometry._releaseVertexArrayObject(this._effect);
  34730. }
  34731. }
  34732. }
  34733. }
  34734. this._uniformBuffer.dispose();
  34735. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  34736. if (forceDisposeEffect && this._effect) {
  34737. if (!this.storeEffectOnSubMeshes) {
  34738. this._scene.getEngine()._releaseEffect(this._effect);
  34739. }
  34740. this._effect = null;
  34741. }
  34742. // Callback
  34743. this.onDisposeObservable.notifyObservers(this);
  34744. this.onDisposeObservable.clear();
  34745. this.onBindObservable.clear();
  34746. this.onUnBindObservable.clear();
  34747. };
  34748. /**
  34749. * Serializes this material
  34750. * @returns the serialized material object
  34751. */
  34752. Material.prototype.serialize = function () {
  34753. return BABYLON.SerializationHelper.Serialize(this);
  34754. };
  34755. /**
  34756. * Creates a MultiMaterial from parsed MultiMaterial data.
  34757. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  34758. * @param scene defines the hosting scene
  34759. * @returns a new MultiMaterial
  34760. */
  34761. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  34762. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  34763. multiMaterial.id = parsedMultiMaterial.id;
  34764. if (BABYLON.Tags) {
  34765. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  34766. }
  34767. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  34768. var subMatId = parsedMultiMaterial.materials[matIndex];
  34769. if (subMatId) {
  34770. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  34771. }
  34772. else {
  34773. multiMaterial.subMaterials.push(null);
  34774. }
  34775. }
  34776. return multiMaterial;
  34777. };
  34778. /**
  34779. * Creates a material from parsed material data
  34780. * @param parsedMaterial defines parsed material data
  34781. * @param scene defines the hosting scene
  34782. * @param rootUrl defines the root URL to use to load textures
  34783. * @returns a new material
  34784. */
  34785. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  34786. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  34787. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  34788. }
  34789. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  34790. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  34791. if (!BABYLON.LegacyPBRMaterial) {
  34792. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  34793. return;
  34794. }
  34795. }
  34796. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  34797. return materialType.Parse(parsedMaterial, scene, rootUrl);
  34798. ;
  34799. };
  34800. // Triangle views
  34801. Material._TriangleFillMode = 0;
  34802. Material._WireFrameFillMode = 1;
  34803. Material._PointFillMode = 2;
  34804. // Draw modes
  34805. Material._PointListDrawMode = 3;
  34806. Material._LineListDrawMode = 4;
  34807. Material._LineLoopDrawMode = 5;
  34808. Material._LineStripDrawMode = 6;
  34809. Material._TriangleStripDrawMode = 7;
  34810. Material._TriangleFanDrawMode = 8;
  34811. /**
  34812. * Stores the clock-wise side orientation
  34813. */
  34814. Material._ClockWiseSideOrientation = 0;
  34815. /**
  34816. * Stores the counter clock-wise side orientation
  34817. */
  34818. Material._CounterClockWiseSideOrientation = 1;
  34819. /**
  34820. * The dirty texture flag value
  34821. */
  34822. Material._TextureDirtyFlag = 1;
  34823. /**
  34824. * The dirty light flag value
  34825. */
  34826. Material._LightDirtyFlag = 2;
  34827. /**
  34828. * The dirty fresnel flag value
  34829. */
  34830. Material._FresnelDirtyFlag = 4;
  34831. /**
  34832. * The dirty attribute flag value
  34833. */
  34834. Material._AttributesDirtyFlag = 8;
  34835. /**
  34836. * The dirty misc flag value
  34837. */
  34838. Material._MiscDirtyFlag = 16;
  34839. __decorate([
  34840. BABYLON.serialize()
  34841. ], Material.prototype, "id", void 0);
  34842. __decorate([
  34843. BABYLON.serialize()
  34844. ], Material.prototype, "name", void 0);
  34845. __decorate([
  34846. BABYLON.serialize()
  34847. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  34848. __decorate([
  34849. BABYLON.serialize()
  34850. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  34851. __decorate([
  34852. BABYLON.serialize()
  34853. ], Material.prototype, "state", void 0);
  34854. __decorate([
  34855. BABYLON.serialize("alpha")
  34856. ], Material.prototype, "_alpha", void 0);
  34857. __decorate([
  34858. BABYLON.serialize("backFaceCulling")
  34859. ], Material.prototype, "_backFaceCulling", void 0);
  34860. __decorate([
  34861. BABYLON.serialize()
  34862. ], Material.prototype, "sideOrientation", void 0);
  34863. __decorate([
  34864. BABYLON.serialize("alphaMode")
  34865. ], Material.prototype, "_alphaMode", void 0);
  34866. __decorate([
  34867. BABYLON.serialize()
  34868. ], Material.prototype, "_needDepthPrePass", void 0);
  34869. __decorate([
  34870. BABYLON.serialize()
  34871. ], Material.prototype, "disableDepthWrite", void 0);
  34872. __decorate([
  34873. BABYLON.serialize()
  34874. ], Material.prototype, "forceDepthWrite", void 0);
  34875. __decorate([
  34876. BABYLON.serialize()
  34877. ], Material.prototype, "separateCullingPass", void 0);
  34878. __decorate([
  34879. BABYLON.serialize("fogEnabled")
  34880. ], Material.prototype, "_fogEnabled", void 0);
  34881. __decorate([
  34882. BABYLON.serialize()
  34883. ], Material.prototype, "pointSize", void 0);
  34884. __decorate([
  34885. BABYLON.serialize()
  34886. ], Material.prototype, "zOffset", void 0);
  34887. __decorate([
  34888. BABYLON.serialize()
  34889. ], Material.prototype, "wireframe", null);
  34890. __decorate([
  34891. BABYLON.serialize()
  34892. ], Material.prototype, "pointsCloud", null);
  34893. __decorate([
  34894. BABYLON.serialize()
  34895. ], Material.prototype, "fillMode", null);
  34896. return Material;
  34897. }());
  34898. BABYLON.Material = Material;
  34899. })(BABYLON || (BABYLON = {}));
  34900. //# sourceMappingURL=babylon.material.js.map
  34901. "use strict";
  34902. var BABYLON;
  34903. (function (BABYLON) {
  34904. var UniformBuffer = /** @class */ (function () {
  34905. /**
  34906. * Uniform buffer objects.
  34907. *
  34908. * Handles blocks of uniform on the GPU.
  34909. *
  34910. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  34911. *
  34912. * For more information, please refer to :
  34913. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  34914. */
  34915. function UniformBuffer(engine, data, dynamic) {
  34916. this._engine = engine;
  34917. this._noUBO = !engine.supportsUniformBuffers;
  34918. this._dynamic = dynamic;
  34919. this._data = data || [];
  34920. this._uniformLocations = {};
  34921. this._uniformSizes = {};
  34922. this._uniformLocationPointer = 0;
  34923. this._needSync = false;
  34924. if (this._noUBO) {
  34925. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  34926. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  34927. this.updateFloat = this._updateFloatForEffect;
  34928. this.updateFloat2 = this._updateFloat2ForEffect;
  34929. this.updateFloat3 = this._updateFloat3ForEffect;
  34930. this.updateFloat4 = this._updateFloat4ForEffect;
  34931. this.updateMatrix = this._updateMatrixForEffect;
  34932. this.updateVector3 = this._updateVector3ForEffect;
  34933. this.updateVector4 = this._updateVector4ForEffect;
  34934. this.updateColor3 = this._updateColor3ForEffect;
  34935. this.updateColor4 = this._updateColor4ForEffect;
  34936. }
  34937. else {
  34938. this._engine._uniformBuffers.push(this);
  34939. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  34940. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  34941. this.updateFloat = this._updateFloatForUniform;
  34942. this.updateFloat2 = this._updateFloat2ForUniform;
  34943. this.updateFloat3 = this._updateFloat3ForUniform;
  34944. this.updateFloat4 = this._updateFloat4ForUniform;
  34945. this.updateMatrix = this._updateMatrixForUniform;
  34946. this.updateVector3 = this._updateVector3ForUniform;
  34947. this.updateVector4 = this._updateVector4ForUniform;
  34948. this.updateColor3 = this._updateColor3ForUniform;
  34949. this.updateColor4 = this._updateColor4ForUniform;
  34950. }
  34951. }
  34952. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  34953. // Properties
  34954. /**
  34955. * Indicates if the buffer is using the WebGL2 UBO implementation,
  34956. * or just falling back on setUniformXXX calls.
  34957. */
  34958. get: function () {
  34959. return !this._noUBO;
  34960. },
  34961. enumerable: true,
  34962. configurable: true
  34963. });
  34964. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  34965. /**
  34966. * Indicates if the WebGL underlying uniform buffer is in sync
  34967. * with the javascript cache data.
  34968. */
  34969. get: function () {
  34970. return !this._needSync;
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. /**
  34976. * Indicates if the WebGL underlying uniform buffer is dynamic.
  34977. * Also, a dynamic UniformBuffer will disable cache verification and always
  34978. * update the underlying WebGL uniform buffer to the GPU.
  34979. */
  34980. UniformBuffer.prototype.isDynamic = function () {
  34981. return this._dynamic !== undefined;
  34982. };
  34983. /**
  34984. * The data cache on JS side.
  34985. */
  34986. UniformBuffer.prototype.getData = function () {
  34987. return this._bufferData;
  34988. };
  34989. /**
  34990. * The underlying WebGL Uniform buffer.
  34991. */
  34992. UniformBuffer.prototype.getBuffer = function () {
  34993. return this._buffer;
  34994. };
  34995. /**
  34996. * std140 layout specifies how to align data within an UBO structure.
  34997. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  34998. * for specs.
  34999. */
  35000. UniformBuffer.prototype._fillAlignment = function (size) {
  35001. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35002. // and 4x4 matrices
  35003. // TODO : change if other types are used
  35004. var alignment;
  35005. if (size <= 2) {
  35006. alignment = size;
  35007. }
  35008. else {
  35009. alignment = 4;
  35010. }
  35011. if ((this._uniformLocationPointer % alignment) !== 0) {
  35012. var oldPointer = this._uniformLocationPointer;
  35013. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35014. var diff = this._uniformLocationPointer - oldPointer;
  35015. for (var i = 0; i < diff; i++) {
  35016. this._data.push(0);
  35017. }
  35018. }
  35019. };
  35020. /**
  35021. * Adds an uniform in the buffer.
  35022. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35023. * for the layout to be correct !
  35024. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35025. * @param {number|number[]} size Data size, or data directly.
  35026. */
  35027. UniformBuffer.prototype.addUniform = function (name, size) {
  35028. if (this._noUBO) {
  35029. return;
  35030. }
  35031. if (this._uniformLocations[name] !== undefined) {
  35032. // Already existing uniform
  35033. return;
  35034. }
  35035. // This function must be called in the order of the shader layout !
  35036. // size can be the size of the uniform, or data directly
  35037. var data;
  35038. if (size instanceof Array) {
  35039. data = size;
  35040. size = data.length;
  35041. }
  35042. else {
  35043. size = size;
  35044. data = [];
  35045. // Fill with zeros
  35046. for (var i = 0; i < size; i++) {
  35047. data.push(0);
  35048. }
  35049. }
  35050. this._fillAlignment(size);
  35051. this._uniformSizes[name] = size;
  35052. this._uniformLocations[name] = this._uniformLocationPointer;
  35053. this._uniformLocationPointer += size;
  35054. for (var i = 0; i < size; i++) {
  35055. this._data.push(data[i]);
  35056. }
  35057. this._needSync = true;
  35058. };
  35059. /**
  35060. * Wrapper for addUniform.
  35061. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35062. * @param {Matrix} mat A 4x4 matrix.
  35063. */
  35064. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35065. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35066. };
  35067. /**
  35068. * Wrapper for addUniform.
  35069. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35070. * @param {number} x
  35071. * @param {number} y
  35072. */
  35073. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35074. var temp = [x, y];
  35075. this.addUniform(name, temp);
  35076. };
  35077. /**
  35078. * Wrapper for addUniform.
  35079. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35080. * @param {number} x
  35081. * @param {number} y
  35082. * @param {number} z
  35083. */
  35084. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35085. var temp = [x, y, z];
  35086. this.addUniform(name, temp);
  35087. };
  35088. /**
  35089. * Wrapper for addUniform.
  35090. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35091. * @param {Color3} color
  35092. */
  35093. UniformBuffer.prototype.addColor3 = function (name, color) {
  35094. var temp = new Array();
  35095. color.toArray(temp);
  35096. this.addUniform(name, temp);
  35097. };
  35098. /**
  35099. * Wrapper for addUniform.
  35100. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35101. * @param {Color3} color
  35102. * @param {number} alpha
  35103. */
  35104. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35105. var temp = new Array();
  35106. color.toArray(temp);
  35107. temp.push(alpha);
  35108. this.addUniform(name, temp);
  35109. };
  35110. /**
  35111. * Wrapper for addUniform.
  35112. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35113. * @param {Vector3} vector
  35114. */
  35115. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35116. var temp = new Array();
  35117. vector.toArray(temp);
  35118. this.addUniform(name, temp);
  35119. };
  35120. /**
  35121. * Wrapper for addUniform.
  35122. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35123. */
  35124. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35125. this.addUniform(name, 12);
  35126. };
  35127. /**
  35128. * Wrapper for addUniform.
  35129. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35130. */
  35131. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35132. this.addUniform(name, 8);
  35133. };
  35134. /**
  35135. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35136. */
  35137. UniformBuffer.prototype.create = function () {
  35138. if (this._noUBO) {
  35139. return;
  35140. }
  35141. if (this._buffer) {
  35142. return; // nothing to do
  35143. }
  35144. // See spec, alignment must be filled as a vec4
  35145. this._fillAlignment(4);
  35146. this._bufferData = new Float32Array(this._data);
  35147. this._rebuild();
  35148. this._needSync = true;
  35149. };
  35150. UniformBuffer.prototype._rebuild = function () {
  35151. if (this._noUBO) {
  35152. return;
  35153. }
  35154. if (this._dynamic) {
  35155. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35156. }
  35157. else {
  35158. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35159. }
  35160. };
  35161. /**
  35162. * Updates the WebGL Uniform Buffer on the GPU.
  35163. * If the `dynamic` flag is set to true, no cache comparison is done.
  35164. * Otherwise, the buffer will be updated only if the cache differs.
  35165. */
  35166. UniformBuffer.prototype.update = function () {
  35167. if (!this._buffer) {
  35168. this.create();
  35169. return;
  35170. }
  35171. if (!this._dynamic && !this._needSync) {
  35172. return;
  35173. }
  35174. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35175. this._needSync = false;
  35176. };
  35177. /**
  35178. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35179. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35180. * @param {number[]|Float32Array} data Flattened data
  35181. * @param {number} size Size of the data.
  35182. */
  35183. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35184. var location = this._uniformLocations[uniformName];
  35185. if (location === undefined) {
  35186. if (this._buffer) {
  35187. // Cannot add an uniform if the buffer is already created
  35188. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35189. return;
  35190. }
  35191. this.addUniform(uniformName, size);
  35192. location = this._uniformLocations[uniformName];
  35193. }
  35194. if (!this._buffer) {
  35195. this.create();
  35196. }
  35197. if (!this._dynamic) {
  35198. // Cache for static uniform buffers
  35199. var changed = false;
  35200. for (var i = 0; i < size; i++) {
  35201. if (this._bufferData[location + i] !== data[i]) {
  35202. changed = true;
  35203. this._bufferData[location + i] = data[i];
  35204. }
  35205. }
  35206. this._needSync = this._needSync || changed;
  35207. }
  35208. else {
  35209. // No cache for dynamic
  35210. for (var i = 0; i < size; i++) {
  35211. this._bufferData[location + i] = data[i];
  35212. }
  35213. }
  35214. };
  35215. // Update methods
  35216. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35217. // To match std140, matrix must be realigned
  35218. for (var i = 0; i < 3; i++) {
  35219. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35220. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35221. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35222. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35223. }
  35224. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35225. };
  35226. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35227. this._currentEffect.setMatrix3x3(name, matrix);
  35228. };
  35229. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35230. this._currentEffect.setMatrix2x2(name, matrix);
  35231. };
  35232. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35233. // To match std140, matrix must be realigned
  35234. for (var i = 0; i < 2; i++) {
  35235. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35236. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35237. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35238. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35239. }
  35240. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35241. };
  35242. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35243. this._currentEffect.setFloat(name, x);
  35244. };
  35245. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35246. UniformBuffer._tempBuffer[0] = x;
  35247. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35248. };
  35249. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35250. if (suffix === void 0) { suffix = ""; }
  35251. this._currentEffect.setFloat2(name + suffix, x, y);
  35252. };
  35253. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35254. if (suffix === void 0) { suffix = ""; }
  35255. UniformBuffer._tempBuffer[0] = x;
  35256. UniformBuffer._tempBuffer[1] = y;
  35257. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35258. };
  35259. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35260. if (suffix === void 0) { suffix = ""; }
  35261. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35262. };
  35263. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35264. if (suffix === void 0) { suffix = ""; }
  35265. UniformBuffer._tempBuffer[0] = x;
  35266. UniformBuffer._tempBuffer[1] = y;
  35267. UniformBuffer._tempBuffer[2] = z;
  35268. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35269. };
  35270. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35271. if (suffix === void 0) { suffix = ""; }
  35272. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35273. };
  35274. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35275. if (suffix === void 0) { suffix = ""; }
  35276. UniformBuffer._tempBuffer[0] = x;
  35277. UniformBuffer._tempBuffer[1] = y;
  35278. UniformBuffer._tempBuffer[2] = z;
  35279. UniformBuffer._tempBuffer[3] = w;
  35280. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35281. };
  35282. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35283. this._currentEffect.setMatrix(name, mat);
  35284. };
  35285. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35286. this.updateUniform(name, mat.toArray(), 16);
  35287. };
  35288. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35289. this._currentEffect.setVector3(name, vector);
  35290. };
  35291. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35292. vector.toArray(UniformBuffer._tempBuffer);
  35293. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35294. };
  35295. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35296. this._currentEffect.setVector4(name, vector);
  35297. };
  35298. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35299. vector.toArray(UniformBuffer._tempBuffer);
  35300. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35301. };
  35302. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35303. if (suffix === void 0) { suffix = ""; }
  35304. this._currentEffect.setColor3(name + suffix, color);
  35305. };
  35306. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35307. if (suffix === void 0) { suffix = ""; }
  35308. color.toArray(UniformBuffer._tempBuffer);
  35309. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35310. };
  35311. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35312. if (suffix === void 0) { suffix = ""; }
  35313. this._currentEffect.setColor4(name + suffix, color, alpha);
  35314. };
  35315. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35316. if (suffix === void 0) { suffix = ""; }
  35317. color.toArray(UniformBuffer._tempBuffer);
  35318. UniformBuffer._tempBuffer[3] = alpha;
  35319. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35320. };
  35321. /**
  35322. * Sets a sampler uniform on the effect.
  35323. * @param {string} name Name of the sampler.
  35324. * @param {Texture} texture
  35325. */
  35326. UniformBuffer.prototype.setTexture = function (name, texture) {
  35327. this._currentEffect.setTexture(name, texture);
  35328. };
  35329. /**
  35330. * Directly updates the value of the uniform in the cache AND on the GPU.
  35331. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35332. * @param {number[]|Float32Array} data Flattened data
  35333. */
  35334. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35335. this.updateUniform(uniformName, data, data.length);
  35336. this.update();
  35337. };
  35338. /**
  35339. * Binds this uniform buffer to an effect.
  35340. * @param {Effect} effect
  35341. * @param {string} name Name of the uniform block in the shader.
  35342. */
  35343. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35344. this._currentEffect = effect;
  35345. if (this._noUBO || !this._buffer) {
  35346. return;
  35347. }
  35348. effect.bindUniformBuffer(this._buffer, name);
  35349. };
  35350. /**
  35351. * Disposes the uniform buffer.
  35352. */
  35353. UniformBuffer.prototype.dispose = function () {
  35354. if (this._noUBO) {
  35355. return;
  35356. }
  35357. var index = this._engine._uniformBuffers.indexOf(this);
  35358. if (index !== -1) {
  35359. this._engine._uniformBuffers.splice(index, 1);
  35360. }
  35361. if (!this._buffer) {
  35362. return;
  35363. }
  35364. if (this._engine._releaseBuffer(this._buffer)) {
  35365. this._buffer = null;
  35366. }
  35367. };
  35368. // Pool for avoiding memory leaks
  35369. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35370. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35371. return UniformBuffer;
  35372. }());
  35373. BABYLON.UniformBuffer = UniformBuffer;
  35374. })(BABYLON || (BABYLON = {}));
  35375. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35376. "use strict";
  35377. var BABYLON;
  35378. (function (BABYLON) {
  35379. /**
  35380. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35381. */
  35382. var VertexData = /** @class */ (function () {
  35383. function VertexData() {
  35384. }
  35385. /**
  35386. * Uses the passed data array to set the set the values for the specified kind of data
  35387. * @param data a linear array of floating numbers
  35388. * @param kind the type of data that is being set, eg positions, colors etc
  35389. */
  35390. VertexData.prototype.set = function (data, kind) {
  35391. switch (kind) {
  35392. case BABYLON.VertexBuffer.PositionKind:
  35393. this.positions = data;
  35394. break;
  35395. case BABYLON.VertexBuffer.NormalKind:
  35396. this.normals = data;
  35397. break;
  35398. case BABYLON.VertexBuffer.TangentKind:
  35399. this.tangents = data;
  35400. break;
  35401. case BABYLON.VertexBuffer.UVKind:
  35402. this.uvs = data;
  35403. break;
  35404. case BABYLON.VertexBuffer.UV2Kind:
  35405. this.uvs2 = data;
  35406. break;
  35407. case BABYLON.VertexBuffer.UV3Kind:
  35408. this.uvs3 = data;
  35409. break;
  35410. case BABYLON.VertexBuffer.UV4Kind:
  35411. this.uvs4 = data;
  35412. break;
  35413. case BABYLON.VertexBuffer.UV5Kind:
  35414. this.uvs5 = data;
  35415. break;
  35416. case BABYLON.VertexBuffer.UV6Kind:
  35417. this.uvs6 = data;
  35418. break;
  35419. case BABYLON.VertexBuffer.ColorKind:
  35420. this.colors = data;
  35421. break;
  35422. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35423. this.matricesIndices = data;
  35424. break;
  35425. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35426. this.matricesWeights = data;
  35427. break;
  35428. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35429. this.matricesIndicesExtra = data;
  35430. break;
  35431. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35432. this.matricesWeightsExtra = data;
  35433. break;
  35434. }
  35435. };
  35436. /**
  35437. * Associates the vertexData to the passed Mesh.
  35438. * Sets it as updatable or not (default `false`)
  35439. * @param mesh the mesh the vertexData is applied to
  35440. * @param updatable when used and having the value true allows new data to update the vertexData
  35441. * @returns the VertexData
  35442. */
  35443. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35444. this._applyTo(mesh, updatable);
  35445. return this;
  35446. };
  35447. /**
  35448. * Associates the vertexData to the passed Geometry.
  35449. * Sets it as updatable or not (default `false`)
  35450. * @param geometry the geometry the vertexData is applied to
  35451. * @param updatable when used and having the value true allows new data to update the vertexData
  35452. * @returns VertexData
  35453. */
  35454. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35455. this._applyTo(geometry, updatable);
  35456. return this;
  35457. };
  35458. /**
  35459. * Updates the associated mesh
  35460. * @param mesh the mesh to be updated
  35461. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35462. * @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
  35463. * @returns VertexData
  35464. */
  35465. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35466. this._update(mesh);
  35467. return this;
  35468. };
  35469. /**
  35470. * Updates the associated geometry
  35471. * @param geometry the geometry to be updated
  35472. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35473. * @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
  35474. * @returns VertexData.
  35475. */
  35476. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35477. this._update(geometry);
  35478. return this;
  35479. };
  35480. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35481. if (updatable === void 0) { updatable = false; }
  35482. if (this.positions) {
  35483. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35484. }
  35485. if (this.normals) {
  35486. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35487. }
  35488. if (this.tangents) {
  35489. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35490. }
  35491. if (this.uvs) {
  35492. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35493. }
  35494. if (this.uvs2) {
  35495. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35496. }
  35497. if (this.uvs3) {
  35498. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35499. }
  35500. if (this.uvs4) {
  35501. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35502. }
  35503. if (this.uvs5) {
  35504. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35505. }
  35506. if (this.uvs6) {
  35507. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35508. }
  35509. if (this.colors) {
  35510. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35511. }
  35512. if (this.matricesIndices) {
  35513. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35514. }
  35515. if (this.matricesWeights) {
  35516. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35517. }
  35518. if (this.matricesIndicesExtra) {
  35519. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35520. }
  35521. if (this.matricesWeightsExtra) {
  35522. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35523. }
  35524. if (this.indices) {
  35525. meshOrGeometry.setIndices(this.indices, null, updatable);
  35526. }
  35527. return this;
  35528. };
  35529. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35530. if (this.positions) {
  35531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35532. }
  35533. if (this.normals) {
  35534. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35535. }
  35536. if (this.tangents) {
  35537. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35538. }
  35539. if (this.uvs) {
  35540. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35541. }
  35542. if (this.uvs2) {
  35543. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35544. }
  35545. if (this.uvs3) {
  35546. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35547. }
  35548. if (this.uvs4) {
  35549. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35550. }
  35551. if (this.uvs5) {
  35552. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35553. }
  35554. if (this.uvs6) {
  35555. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35556. }
  35557. if (this.colors) {
  35558. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35559. }
  35560. if (this.matricesIndices) {
  35561. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35562. }
  35563. if (this.matricesWeights) {
  35564. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35565. }
  35566. if (this.matricesIndicesExtra) {
  35567. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35568. }
  35569. if (this.matricesWeightsExtra) {
  35570. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35571. }
  35572. if (this.indices) {
  35573. meshOrGeometry.setIndices(this.indices, null);
  35574. }
  35575. return this;
  35576. };
  35577. /**
  35578. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35579. * @param matrix the transforming matrix
  35580. * @returns the VertexData
  35581. */
  35582. VertexData.prototype.transform = function (matrix) {
  35583. var transformed = BABYLON.Vector3.Zero();
  35584. var index;
  35585. if (this.positions) {
  35586. var position = BABYLON.Vector3.Zero();
  35587. for (index = 0; index < this.positions.length; index += 3) {
  35588. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35589. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35590. this.positions[index] = transformed.x;
  35591. this.positions[index + 1] = transformed.y;
  35592. this.positions[index + 2] = transformed.z;
  35593. }
  35594. }
  35595. if (this.normals) {
  35596. var normal = BABYLON.Vector3.Zero();
  35597. for (index = 0; index < this.normals.length; index += 3) {
  35598. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35599. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35600. this.normals[index] = transformed.x;
  35601. this.normals[index + 1] = transformed.y;
  35602. this.normals[index + 2] = transformed.z;
  35603. }
  35604. }
  35605. if (this.tangents) {
  35606. var tangent = BABYLON.Vector4.Zero();
  35607. var tangentTransformed = BABYLON.Vector4.Zero();
  35608. for (index = 0; index < this.tangents.length; index += 4) {
  35609. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35610. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35611. this.tangents[index] = tangentTransformed.x;
  35612. this.tangents[index + 1] = tangentTransformed.y;
  35613. this.tangents[index + 2] = tangentTransformed.z;
  35614. this.tangents[index + 3] = tangentTransformed.w;
  35615. }
  35616. }
  35617. return this;
  35618. };
  35619. /**
  35620. * Merges the passed VertexData into the current one
  35621. * @param other the VertexData to be merged into the current one
  35622. * @returns the modified VertexData
  35623. */
  35624. VertexData.prototype.merge = function (other) {
  35625. this._validate();
  35626. other._validate();
  35627. if (!this.normals !== !other.normals ||
  35628. !this.tangents !== !other.tangents ||
  35629. !this.uvs !== !other.uvs ||
  35630. !this.uvs2 !== !other.uvs2 ||
  35631. !this.uvs3 !== !other.uvs3 ||
  35632. !this.uvs4 !== !other.uvs4 ||
  35633. !this.uvs5 !== !other.uvs5 ||
  35634. !this.uvs6 !== !other.uvs6 ||
  35635. !this.colors !== !other.colors ||
  35636. !this.matricesIndices !== !other.matricesIndices ||
  35637. !this.matricesWeights !== !other.matricesWeights ||
  35638. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35639. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35640. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35641. }
  35642. if (other.indices) {
  35643. if (!this.indices) {
  35644. this.indices = [];
  35645. }
  35646. var offset = this.positions ? this.positions.length / 3 : 0;
  35647. for (var index = 0; index < other.indices.length; index++) {
  35648. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35649. this.indices.push(other.indices[index] + offset);
  35650. }
  35651. }
  35652. this.positions = this._mergeElement(this.positions, other.positions);
  35653. this.normals = this._mergeElement(this.normals, other.normals);
  35654. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35655. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35656. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35657. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35658. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35659. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35660. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35661. this.colors = this._mergeElement(this.colors, other.colors);
  35662. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35663. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35664. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35665. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35666. return this;
  35667. };
  35668. VertexData.prototype._mergeElement = function (source, other) {
  35669. if (!source) {
  35670. return other;
  35671. }
  35672. if (!other) {
  35673. return source;
  35674. }
  35675. var len = other.length + source.length;
  35676. var isSrcTypedArray = source instanceof Float32Array;
  35677. var isOthTypedArray = other instanceof Float32Array;
  35678. // use non-loop method when the source is Float32Array
  35679. if (isSrcTypedArray) {
  35680. var ret32 = new Float32Array(len);
  35681. ret32.set(source);
  35682. ret32.set(other, source.length);
  35683. return ret32;
  35684. // source is number[], when other is also use concat
  35685. }
  35686. else if (!isOthTypedArray) {
  35687. return source.concat(other);
  35688. // source is a number[], but other is a Float32Array, loop required
  35689. }
  35690. else {
  35691. var ret = source.slice(0); // copy source to a separate array
  35692. for (var i = 0, len = other.length; i < len; i++) {
  35693. ret.push(other[i]);
  35694. }
  35695. return ret;
  35696. }
  35697. };
  35698. VertexData.prototype._validate = function () {
  35699. if (!this.positions) {
  35700. throw new Error("Positions are required");
  35701. }
  35702. var getElementCount = function (kind, values) {
  35703. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35704. if ((values.length % stride) !== 0) {
  35705. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35706. }
  35707. return values.length / stride;
  35708. };
  35709. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35710. var validateElementCount = function (kind, values) {
  35711. var elementCount = getElementCount(kind, values);
  35712. if (elementCount !== positionsElementCount) {
  35713. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35714. }
  35715. };
  35716. if (this.normals)
  35717. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35718. if (this.tangents)
  35719. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35720. if (this.uvs)
  35721. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35722. if (this.uvs2)
  35723. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35724. if (this.uvs3)
  35725. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35726. if (this.uvs4)
  35727. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35728. if (this.uvs5)
  35729. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35730. if (this.uvs6)
  35731. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35732. if (this.colors)
  35733. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  35734. if (this.matricesIndices)
  35735. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  35736. if (this.matricesWeights)
  35737. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  35738. if (this.matricesIndicesExtra)
  35739. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  35740. if (this.matricesWeightsExtra)
  35741. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  35742. };
  35743. /**
  35744. * Serializes the VertexData
  35745. * @returns a serialized object
  35746. */
  35747. VertexData.prototype.serialize = function () {
  35748. var serializationObject = this.serialize();
  35749. if (this.positions) {
  35750. serializationObject.positions = this.positions;
  35751. }
  35752. if (this.normals) {
  35753. serializationObject.normals = this.normals;
  35754. }
  35755. if (this.tangents) {
  35756. serializationObject.tangents = this.tangents;
  35757. }
  35758. if (this.uvs) {
  35759. serializationObject.uvs = this.uvs;
  35760. }
  35761. if (this.uvs2) {
  35762. serializationObject.uvs2 = this.uvs2;
  35763. }
  35764. if (this.uvs3) {
  35765. serializationObject.uvs3 = this.uvs3;
  35766. }
  35767. if (this.uvs4) {
  35768. serializationObject.uvs4 = this.uvs4;
  35769. }
  35770. if (this.uvs5) {
  35771. serializationObject.uvs5 = this.uvs5;
  35772. }
  35773. if (this.uvs6) {
  35774. serializationObject.uvs6 = this.uvs6;
  35775. }
  35776. if (this.colors) {
  35777. serializationObject.colors = this.colors;
  35778. }
  35779. if (this.matricesIndices) {
  35780. serializationObject.matricesIndices = this.matricesIndices;
  35781. serializationObject.matricesIndices._isExpanded = true;
  35782. }
  35783. if (this.matricesWeights) {
  35784. serializationObject.matricesWeights = this.matricesWeights;
  35785. }
  35786. if (this.matricesIndicesExtra) {
  35787. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35788. serializationObject.matricesIndicesExtra._isExpanded = true;
  35789. }
  35790. if (this.matricesWeightsExtra) {
  35791. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35792. }
  35793. serializationObject.indices = this.indices;
  35794. return serializationObject;
  35795. };
  35796. // Statics
  35797. /**
  35798. * Extracts the vertexData from a mesh
  35799. * @param mesh the mesh from which to extract the VertexData
  35800. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  35801. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  35802. * @returns the object VertexData associated to the passed mesh
  35803. */
  35804. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  35805. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  35806. };
  35807. /**
  35808. * Extracts the vertexData from the geometry
  35809. * @param geometry the geometry from which to extract the VertexData
  35810. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  35811. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  35812. * @returns the object VertexData associated to the passed mesh
  35813. */
  35814. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  35815. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  35816. };
  35817. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  35818. var result = new VertexData();
  35819. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35820. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  35821. }
  35822. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35823. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  35824. }
  35825. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35826. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  35827. }
  35828. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35829. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  35830. }
  35831. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35832. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  35833. }
  35834. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35835. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  35836. }
  35837. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35838. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  35839. }
  35840. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35841. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  35842. }
  35843. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35844. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  35845. }
  35846. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35847. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  35848. }
  35849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35850. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  35851. }
  35852. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35853. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  35854. }
  35855. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35856. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  35857. }
  35858. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35859. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  35860. }
  35861. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35862. return result;
  35863. };
  35864. /**
  35865. * Creates the VertexData for a Ribbon
  35866. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  35867. * * pathArray array of paths, each of which an array of successive Vector3
  35868. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  35869. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  35870. * * 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
  35871. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35872. * * 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)
  35873. * * 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)
  35874. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  35875. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  35876. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  35877. * @returns the VertexData of the ribbon
  35878. */
  35879. VertexData.CreateRibbon = function (options) {
  35880. var pathArray = options.pathArray;
  35881. var closeArray = options.closeArray || false;
  35882. var closePath = options.closePath || false;
  35883. var invertUV = options.invertUV || false;
  35884. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35885. var offset = options.offset || defaultOffset;
  35886. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35887. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35888. var customUV = options.uvs;
  35889. var customColors = options.colors;
  35890. var positions = [];
  35891. var indices = [];
  35892. var normals = [];
  35893. var uvs = [];
  35894. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35895. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35896. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35897. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35898. var minlg; // minimal length among all paths from pathArray
  35899. var lg = []; // array of path lengths : nb of vertex per path
  35900. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35901. var p; // path iterator
  35902. var i; // point iterator
  35903. var j; // point iterator
  35904. // if single path in pathArray
  35905. if (pathArray.length < 2) {
  35906. var ar1 = [];
  35907. var ar2 = [];
  35908. for (i = 0; i < pathArray[0].length - offset; i++) {
  35909. ar1.push(pathArray[0][i]);
  35910. ar2.push(pathArray[0][i + offset]);
  35911. }
  35912. pathArray = [ar1, ar2];
  35913. }
  35914. // positions and horizontal distances (u)
  35915. var idc = 0;
  35916. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  35917. var path;
  35918. var l;
  35919. minlg = pathArray[0].length;
  35920. var vectlg;
  35921. var dist;
  35922. for (p = 0; p < pathArray.length; p++) {
  35923. uTotalDistance[p] = 0;
  35924. us[p] = [0];
  35925. path = pathArray[p];
  35926. l = path.length;
  35927. minlg = (minlg < l) ? minlg : l;
  35928. j = 0;
  35929. while (j < l) {
  35930. positions.push(path[j].x, path[j].y, path[j].z);
  35931. if (j > 0) {
  35932. vectlg = path[j].subtract(path[j - 1]).length();
  35933. dist = vectlg + uTotalDistance[p];
  35934. us[p].push(dist);
  35935. uTotalDistance[p] = dist;
  35936. }
  35937. j++;
  35938. }
  35939. if (closePath) {
  35940. j--;
  35941. positions.push(path[0].x, path[0].y, path[0].z);
  35942. vectlg = path[j].subtract(path[0]).length();
  35943. dist = vectlg + uTotalDistance[p];
  35944. us[p].push(dist);
  35945. uTotalDistance[p] = dist;
  35946. }
  35947. lg[p] = l + closePathCorr;
  35948. idx[p] = idc;
  35949. idc += (l + closePathCorr);
  35950. }
  35951. // vertical distances (v)
  35952. var path1;
  35953. var path2;
  35954. var vertex1 = null;
  35955. var vertex2 = null;
  35956. for (i = 0; i < minlg + closePathCorr; i++) {
  35957. vTotalDistance[i] = 0;
  35958. vs[i] = [0];
  35959. for (p = 0; p < pathArray.length - 1; p++) {
  35960. path1 = pathArray[p];
  35961. path2 = pathArray[p + 1];
  35962. if (i === minlg) {
  35963. vertex1 = path1[0];
  35964. vertex2 = path2[0];
  35965. }
  35966. else {
  35967. vertex1 = path1[i];
  35968. vertex2 = path2[i];
  35969. }
  35970. vectlg = vertex2.subtract(vertex1).length();
  35971. dist = vectlg + vTotalDistance[i];
  35972. vs[i].push(dist);
  35973. vTotalDistance[i] = dist;
  35974. }
  35975. if (closeArray && vertex2 && vertex1) {
  35976. path1 = pathArray[p];
  35977. path2 = pathArray[0];
  35978. if (i === minlg) {
  35979. vertex2 = path2[0];
  35980. }
  35981. vectlg = vertex2.subtract(vertex1).length();
  35982. dist = vectlg + vTotalDistance[i];
  35983. vTotalDistance[i] = dist;
  35984. }
  35985. }
  35986. // uvs
  35987. var u;
  35988. var v;
  35989. if (customUV) {
  35990. for (p = 0; p < customUV.length; p++) {
  35991. uvs.push(customUV[p].x, customUV[p].y);
  35992. }
  35993. }
  35994. else {
  35995. for (p = 0; p < pathArray.length; p++) {
  35996. for (i = 0; i < minlg + closePathCorr; i++) {
  35997. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  35998. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  35999. if (invertUV) {
  36000. uvs.push(v, u);
  36001. }
  36002. else {
  36003. uvs.push(u, v);
  36004. }
  36005. }
  36006. }
  36007. }
  36008. // indices
  36009. p = 0; // path index
  36010. var pi = 0; // positions array index
  36011. var l1 = lg[p] - 1; // path1 length
  36012. var l2 = lg[p + 1] - 1; // path2 length
  36013. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36014. var shft = idx[1] - idx[0]; // shift
  36015. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36016. while (pi <= min && p < path1nb) {
  36017. // 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
  36018. indices.push(pi, pi + shft, pi + 1);
  36019. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36020. pi += 1;
  36021. if (pi === min) {
  36022. p++;
  36023. if (p === lg.length - 1) {
  36024. shft = idx[0] - idx[p];
  36025. l1 = lg[p] - 1;
  36026. l2 = lg[0] - 1;
  36027. }
  36028. else {
  36029. shft = idx[p + 1] - idx[p];
  36030. l1 = lg[p] - 1;
  36031. l2 = lg[p + 1] - 1;
  36032. }
  36033. pi = idx[p];
  36034. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36035. }
  36036. }
  36037. // normals
  36038. VertexData.ComputeNormals(positions, indices, normals);
  36039. if (closePath) {
  36040. var indexFirst = 0;
  36041. var indexLast = 0;
  36042. for (p = 0; p < pathArray.length; p++) {
  36043. indexFirst = idx[p] * 3;
  36044. if (p + 1 < pathArray.length) {
  36045. indexLast = (idx[p + 1] - 1) * 3;
  36046. }
  36047. else {
  36048. indexLast = normals.length - 3;
  36049. }
  36050. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36051. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36052. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36053. normals[indexLast] = normals[indexFirst];
  36054. normals[indexLast + 1] = normals[indexFirst + 1];
  36055. normals[indexLast + 2] = normals[indexFirst + 2];
  36056. }
  36057. }
  36058. // sides
  36059. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36060. // Colors
  36061. var colors = null;
  36062. if (customColors) {
  36063. colors = new Float32Array(customColors.length * 4);
  36064. for (var c = 0; c < customColors.length; c++) {
  36065. colors[c * 4] = customColors[c].r;
  36066. colors[c * 4 + 1] = customColors[c].g;
  36067. colors[c * 4 + 2] = customColors[c].b;
  36068. colors[c * 4 + 3] = customColors[c].a;
  36069. }
  36070. }
  36071. // Result
  36072. var vertexData = new VertexData();
  36073. var positions32 = new Float32Array(positions);
  36074. var normals32 = new Float32Array(normals);
  36075. var uvs32 = new Float32Array(uvs);
  36076. vertexData.indices = indices;
  36077. vertexData.positions = positions32;
  36078. vertexData.normals = normals32;
  36079. vertexData.uvs = uvs32;
  36080. if (colors) {
  36081. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36082. }
  36083. if (closePath) {
  36084. vertexData._idx = idx;
  36085. }
  36086. return vertexData;
  36087. };
  36088. /**
  36089. * Creates the VertexData for a box
  36090. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36091. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36092. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36093. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36094. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36095. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36096. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36097. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36098. * * 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)
  36099. * * 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)
  36100. * @returns the VertexData of the box
  36101. */
  36102. VertexData.CreateBox = function (options) {
  36103. var normalsSource = [
  36104. new BABYLON.Vector3(0, 0, 1),
  36105. new BABYLON.Vector3(0, 0, -1),
  36106. new BABYLON.Vector3(1, 0, 0),
  36107. new BABYLON.Vector3(-1, 0, 0),
  36108. new BABYLON.Vector3(0, 1, 0),
  36109. new BABYLON.Vector3(0, -1, 0)
  36110. ];
  36111. var indices = [];
  36112. var positions = [];
  36113. var normals = [];
  36114. var uvs = [];
  36115. var width = options.width || options.size || 1;
  36116. var height = options.height || options.size || 1;
  36117. var depth = options.depth || options.size || 1;
  36118. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36119. var faceUV = options.faceUV || new Array(6);
  36120. var faceColors = options.faceColors;
  36121. var colors = [];
  36122. // default face colors and UV if undefined
  36123. for (var f = 0; f < 6; f++) {
  36124. if (faceUV[f] === undefined) {
  36125. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36126. }
  36127. if (faceColors && faceColors[f] === undefined) {
  36128. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36129. }
  36130. }
  36131. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36132. // Create each face in turn.
  36133. for (var index = 0; index < normalsSource.length; index++) {
  36134. var normal = normalsSource[index];
  36135. // Get two vectors perpendicular to the face normal and to each other.
  36136. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36137. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36138. // Six indices (two triangles) per face.
  36139. var verticesLength = positions.length / 3;
  36140. indices.push(verticesLength);
  36141. indices.push(verticesLength + 1);
  36142. indices.push(verticesLength + 2);
  36143. indices.push(verticesLength);
  36144. indices.push(verticesLength + 2);
  36145. indices.push(verticesLength + 3);
  36146. // Four vertices per face.
  36147. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36148. positions.push(vertex.x, vertex.y, vertex.z);
  36149. normals.push(normal.x, normal.y, normal.z);
  36150. uvs.push(faceUV[index].z, faceUV[index].w);
  36151. if (faceColors) {
  36152. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36153. }
  36154. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36155. positions.push(vertex.x, vertex.y, vertex.z);
  36156. normals.push(normal.x, normal.y, normal.z);
  36157. uvs.push(faceUV[index].x, faceUV[index].w);
  36158. if (faceColors) {
  36159. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36160. }
  36161. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36162. positions.push(vertex.x, vertex.y, vertex.z);
  36163. normals.push(normal.x, normal.y, normal.z);
  36164. uvs.push(faceUV[index].x, faceUV[index].y);
  36165. if (faceColors) {
  36166. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36167. }
  36168. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36169. positions.push(vertex.x, vertex.y, vertex.z);
  36170. normals.push(normal.x, normal.y, normal.z);
  36171. uvs.push(faceUV[index].z, faceUV[index].y);
  36172. if (faceColors) {
  36173. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36174. }
  36175. }
  36176. // sides
  36177. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36178. // Result
  36179. var vertexData = new VertexData();
  36180. vertexData.indices = indices;
  36181. vertexData.positions = positions;
  36182. vertexData.normals = normals;
  36183. vertexData.uvs = uvs;
  36184. if (faceColors) {
  36185. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36186. vertexData.colors = totalColors;
  36187. }
  36188. return vertexData;
  36189. };
  36190. /**
  36191. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36192. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36193. * * segments sets the number of horizontal strips optional, default 32
  36194. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36195. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36196. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36197. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36198. * * 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
  36199. * * 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
  36200. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36201. * * 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)
  36202. * * 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)
  36203. * @returns the VertexData of the ellipsoid
  36204. */
  36205. VertexData.CreateSphere = function (options) {
  36206. var segments = options.segments || 32;
  36207. var diameterX = options.diameterX || options.diameter || 1;
  36208. var diameterY = options.diameterY || options.diameter || 1;
  36209. var diameterZ = options.diameterZ || options.diameter || 1;
  36210. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36211. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36212. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36213. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36214. var totalZRotationSteps = 2 + segments;
  36215. var totalYRotationSteps = 2 * totalZRotationSteps;
  36216. var indices = [];
  36217. var positions = [];
  36218. var normals = [];
  36219. var uvs = [];
  36220. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36221. var normalizedZ = zRotationStep / totalZRotationSteps;
  36222. var angleZ = normalizedZ * Math.PI * slice;
  36223. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36224. var normalizedY = yRotationStep / totalYRotationSteps;
  36225. var angleY = normalizedY * Math.PI * 2 * arc;
  36226. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36227. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36228. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36229. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36230. var vertex = complete.multiply(radius);
  36231. var normal = complete.divide(radius).normalize();
  36232. positions.push(vertex.x, vertex.y, vertex.z);
  36233. normals.push(normal.x, normal.y, normal.z);
  36234. uvs.push(normalizedY, normalizedZ);
  36235. }
  36236. if (zRotationStep > 0) {
  36237. var verticesCount = positions.length / 3;
  36238. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36239. indices.push((firstIndex));
  36240. indices.push((firstIndex + 1));
  36241. indices.push(firstIndex + totalYRotationSteps + 1);
  36242. indices.push((firstIndex + totalYRotationSteps + 1));
  36243. indices.push((firstIndex + 1));
  36244. indices.push((firstIndex + totalYRotationSteps + 2));
  36245. }
  36246. }
  36247. }
  36248. // Sides
  36249. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36250. // Result
  36251. var vertexData = new VertexData();
  36252. vertexData.indices = indices;
  36253. vertexData.positions = positions;
  36254. vertexData.normals = normals;
  36255. vertexData.uvs = uvs;
  36256. return vertexData;
  36257. };
  36258. /**
  36259. * Creates the VertexData for a cylinder, cone or prism
  36260. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36261. * * height sets the height (y direction) of the cylinder, optional, default 2
  36262. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36263. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36264. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36265. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36266. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36267. * * 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
  36268. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36269. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36270. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36271. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36272. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36273. * * 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)
  36274. * * 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)
  36275. * @returns the VertexData of the cylinder, cone or prism
  36276. */
  36277. VertexData.CreateCylinder = function (options) {
  36278. var height = options.height || 2;
  36279. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36280. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36281. var tessellation = options.tessellation || 24;
  36282. var subdivisions = options.subdivisions || 1;
  36283. var hasRings = options.hasRings ? true : false;
  36284. var enclose = options.enclose ? true : false;
  36285. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36286. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36287. var faceUV = options.faceUV || new Array(3);
  36288. var faceColors = options.faceColors;
  36289. // default face colors and UV if undefined
  36290. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36291. var ringNb = (hasRings) ? subdivisions : 1;
  36292. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36293. var f;
  36294. for (f = 0; f < surfaceNb; f++) {
  36295. if (faceColors && faceColors[f] === undefined) {
  36296. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36297. }
  36298. }
  36299. for (f = 0; f < surfaceNb; f++) {
  36300. if (faceUV && faceUV[f] === undefined) {
  36301. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36302. }
  36303. }
  36304. var indices = new Array();
  36305. var positions = new Array();
  36306. var normals = new Array();
  36307. var uvs = new Array();
  36308. var colors = new Array();
  36309. var angle_step = Math.PI * 2 * arc / tessellation;
  36310. var angle;
  36311. var h;
  36312. var radius;
  36313. var tan = (diameterBottom - diameterTop) / 2 / height;
  36314. var ringVertex = BABYLON.Vector3.Zero();
  36315. var ringNormal = BABYLON.Vector3.Zero();
  36316. var ringFirstVertex = BABYLON.Vector3.Zero();
  36317. var ringFirstNormal = BABYLON.Vector3.Zero();
  36318. var quadNormal = BABYLON.Vector3.Zero();
  36319. var Y = BABYLON.Axis.Y;
  36320. // positions, normals, uvs
  36321. var i;
  36322. var j;
  36323. var r;
  36324. var ringIdx = 1;
  36325. var s = 1; // surface index
  36326. var cs = 0;
  36327. var v = 0;
  36328. for (i = 0; i <= subdivisions; i++) {
  36329. h = i / subdivisions;
  36330. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36331. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36332. for (r = 0; r < ringIdx; r++) {
  36333. if (hasRings) {
  36334. s += r;
  36335. }
  36336. if (enclose) {
  36337. s += 2 * r;
  36338. }
  36339. for (j = 0; j <= tessellation; j++) {
  36340. angle = j * angle_step;
  36341. // position
  36342. ringVertex.x = Math.cos(-angle) * radius;
  36343. ringVertex.y = -height / 2 + h * height;
  36344. ringVertex.z = Math.sin(-angle) * radius;
  36345. // normal
  36346. if (diameterTop === 0 && i === subdivisions) {
  36347. // if no top cap, reuse former normals
  36348. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36349. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36350. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36351. }
  36352. else {
  36353. ringNormal.x = ringVertex.x;
  36354. ringNormal.z = ringVertex.z;
  36355. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36356. ringNormal.normalize();
  36357. }
  36358. // keep first ring vertex values for enclose
  36359. if (j === 0) {
  36360. ringFirstVertex.copyFrom(ringVertex);
  36361. ringFirstNormal.copyFrom(ringNormal);
  36362. }
  36363. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36364. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36365. if (hasRings) {
  36366. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36367. }
  36368. else {
  36369. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36370. }
  36371. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36372. if (faceColors) {
  36373. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36374. }
  36375. }
  36376. // if enclose, add four vertices and their dedicated normals
  36377. if (arc !== 1 && enclose) {
  36378. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36379. positions.push(0, ringVertex.y, 0);
  36380. positions.push(0, ringVertex.y, 0);
  36381. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36382. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36383. quadNormal.normalize();
  36384. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36385. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36386. quadNormal.normalize();
  36387. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36388. if (hasRings) {
  36389. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36390. }
  36391. else {
  36392. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36393. }
  36394. uvs.push(faceUV[s + 1].x, v);
  36395. uvs.push(faceUV[s + 1].z, v);
  36396. if (hasRings) {
  36397. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36398. }
  36399. else {
  36400. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36401. }
  36402. uvs.push(faceUV[s + 2].x, v);
  36403. uvs.push(faceUV[s + 2].z, v);
  36404. if (faceColors) {
  36405. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36406. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36407. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36408. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36409. }
  36410. }
  36411. if (cs !== s) {
  36412. cs = s;
  36413. }
  36414. }
  36415. }
  36416. // indices
  36417. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36418. var s;
  36419. i = 0;
  36420. for (s = 0; s < subdivisions; s++) {
  36421. var i0 = 0;
  36422. var i1 = 0;
  36423. var i2 = 0;
  36424. var i3 = 0;
  36425. for (j = 0; j < tessellation; j++) {
  36426. i0 = i * (e + 1) + j;
  36427. i1 = (i + 1) * (e + 1) + j;
  36428. i2 = i * (e + 1) + (j + 1);
  36429. i3 = (i + 1) * (e + 1) + (j + 1);
  36430. indices.push(i0, i1, i2);
  36431. indices.push(i3, i2, i1);
  36432. }
  36433. if (arc !== 1 && enclose) {
  36434. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36435. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36436. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36437. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36438. }
  36439. i = (hasRings) ? (i + 2) : (i + 1);
  36440. }
  36441. // Caps
  36442. var createCylinderCap = function (isTop) {
  36443. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36444. if (radius === 0) {
  36445. return;
  36446. }
  36447. // Cap positions, normals & uvs
  36448. var angle;
  36449. var circleVector;
  36450. var i;
  36451. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36452. var c = null;
  36453. if (faceColors) {
  36454. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36455. }
  36456. // cap center
  36457. var vbase = positions.length / 3;
  36458. var offset = isTop ? height / 2 : -height / 2;
  36459. var center = new BABYLON.Vector3(0, offset, 0);
  36460. positions.push(center.x, center.y, center.z);
  36461. normals.push(0, isTop ? 1 : -1, 0);
  36462. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36463. if (c) {
  36464. colors.push(c.r, c.g, c.b, c.a);
  36465. }
  36466. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36467. for (i = 0; i <= tessellation; i++) {
  36468. angle = Math.PI * 2 * i * arc / tessellation;
  36469. var cos = Math.cos(-angle);
  36470. var sin = Math.sin(-angle);
  36471. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36472. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36473. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36474. normals.push(0, isTop ? 1 : -1, 0);
  36475. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36476. if (c) {
  36477. colors.push(c.r, c.g, c.b, c.a);
  36478. }
  36479. }
  36480. // Cap indices
  36481. for (i = 0; i < tessellation; i++) {
  36482. if (!isTop) {
  36483. indices.push(vbase);
  36484. indices.push(vbase + (i + 1));
  36485. indices.push(vbase + (i + 2));
  36486. }
  36487. else {
  36488. indices.push(vbase);
  36489. indices.push(vbase + (i + 2));
  36490. indices.push(vbase + (i + 1));
  36491. }
  36492. }
  36493. };
  36494. // add caps to geometry
  36495. createCylinderCap(false);
  36496. createCylinderCap(true);
  36497. // Sides
  36498. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36499. var vertexData = new VertexData();
  36500. vertexData.indices = indices;
  36501. vertexData.positions = positions;
  36502. vertexData.normals = normals;
  36503. vertexData.uvs = uvs;
  36504. if (faceColors) {
  36505. vertexData.colors = colors;
  36506. }
  36507. return vertexData;
  36508. };
  36509. /**
  36510. * Creates the VertexData for a torus
  36511. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36512. * * diameter the diameter of the torus, optional default 1
  36513. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36514. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36515. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36516. * * 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)
  36517. * * 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)
  36518. * @returns the VertexData of the torus
  36519. */
  36520. VertexData.CreateTorus = function (options) {
  36521. var indices = [];
  36522. var positions = [];
  36523. var normals = [];
  36524. var uvs = [];
  36525. var diameter = options.diameter || 1;
  36526. var thickness = options.thickness || 0.5;
  36527. var tessellation = options.tessellation || 16;
  36528. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36529. var stride = tessellation + 1;
  36530. for (var i = 0; i <= tessellation; i++) {
  36531. var u = i / tessellation;
  36532. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36533. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36534. for (var j = 0; j <= tessellation; j++) {
  36535. var v = 1 - j / tessellation;
  36536. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36537. var dx = Math.cos(innerAngle);
  36538. var dy = Math.sin(innerAngle);
  36539. // Create a vertex.
  36540. var normal = new BABYLON.Vector3(dx, dy, 0);
  36541. var position = normal.scale(thickness / 2);
  36542. var textureCoordinate = new BABYLON.Vector2(u, v);
  36543. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36544. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36545. positions.push(position.x, position.y, position.z);
  36546. normals.push(normal.x, normal.y, normal.z);
  36547. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36548. // And create indices for two triangles.
  36549. var nextI = (i + 1) % stride;
  36550. var nextJ = (j + 1) % stride;
  36551. indices.push(i * stride + j);
  36552. indices.push(i * stride + nextJ);
  36553. indices.push(nextI * stride + j);
  36554. indices.push(i * stride + nextJ);
  36555. indices.push(nextI * stride + nextJ);
  36556. indices.push(nextI * stride + j);
  36557. }
  36558. }
  36559. // Sides
  36560. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36561. // Result
  36562. var vertexData = new VertexData();
  36563. vertexData.indices = indices;
  36564. vertexData.positions = positions;
  36565. vertexData.normals = normals;
  36566. vertexData.uvs = uvs;
  36567. return vertexData;
  36568. };
  36569. /**
  36570. * Creates the VertexData of the LineSystem
  36571. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36572. * - lines an array of lines, each line being an array of successive Vector3
  36573. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36574. * @returns the VertexData of the LineSystem
  36575. */
  36576. VertexData.CreateLineSystem = function (options) {
  36577. var indices = [];
  36578. var positions = [];
  36579. var lines = options.lines;
  36580. var colors = options.colors;
  36581. var vertexColors = [];
  36582. var idx = 0;
  36583. for (var l = 0; l < lines.length; l++) {
  36584. var points = lines[l];
  36585. for (var index = 0; index < points.length; index++) {
  36586. positions.push(points[index].x, points[index].y, points[index].z);
  36587. if (colors) {
  36588. var color = colors[l];
  36589. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36590. }
  36591. if (index > 0) {
  36592. indices.push(idx - 1);
  36593. indices.push(idx);
  36594. }
  36595. idx++;
  36596. }
  36597. }
  36598. var vertexData = new VertexData();
  36599. vertexData.indices = indices;
  36600. vertexData.positions = positions;
  36601. if (colors) {
  36602. vertexData.colors = vertexColors;
  36603. }
  36604. return vertexData;
  36605. };
  36606. /**
  36607. * Create the VertexData for a DashedLines
  36608. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  36609. * - points an array successive Vector3
  36610. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  36611. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  36612. * - dashNb the intended total number of dashes, optional, default 200
  36613. * @returns the VertexData for the DashedLines
  36614. */
  36615. VertexData.CreateDashedLines = function (options) {
  36616. var dashSize = options.dashSize || 3;
  36617. var gapSize = options.gapSize || 1;
  36618. var dashNb = options.dashNb || 200;
  36619. var points = options.points;
  36620. var positions = new Array();
  36621. var indices = new Array();
  36622. var curvect = BABYLON.Vector3.Zero();
  36623. var lg = 0;
  36624. var nb = 0;
  36625. var shft = 0;
  36626. var dashshft = 0;
  36627. var curshft = 0;
  36628. var idx = 0;
  36629. var i = 0;
  36630. for (i = 0; i < points.length - 1; i++) {
  36631. points[i + 1].subtractToRef(points[i], curvect);
  36632. lg += curvect.length();
  36633. }
  36634. shft = lg / dashNb;
  36635. dashshft = dashSize * shft / (dashSize + gapSize);
  36636. for (i = 0; i < points.length - 1; i++) {
  36637. points[i + 1].subtractToRef(points[i], curvect);
  36638. nb = Math.floor(curvect.length() / shft);
  36639. curvect.normalize();
  36640. for (var j = 0; j < nb; j++) {
  36641. curshft = shft * j;
  36642. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36643. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36644. indices.push(idx, idx + 1);
  36645. idx += 2;
  36646. }
  36647. }
  36648. // Result
  36649. var vertexData = new VertexData();
  36650. vertexData.positions = positions;
  36651. vertexData.indices = indices;
  36652. return vertexData;
  36653. };
  36654. /**
  36655. * Creates the VertexData for a Ground
  36656. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36657. * - width the width (x direction) of the ground, optional, default 1
  36658. * - height the height (z direction) of the ground, optional, default 1
  36659. * - subdivisions the number of subdivisions per side, optional, default 1
  36660. * @returns the VertexData of the Ground
  36661. */
  36662. VertexData.CreateGround = function (options) {
  36663. var indices = [];
  36664. var positions = [];
  36665. var normals = [];
  36666. var uvs = [];
  36667. var row, col;
  36668. var width = options.width || 1;
  36669. var height = options.height || 1;
  36670. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36671. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36672. for (row = 0; row <= subdivisionsY; row++) {
  36673. for (col = 0; col <= subdivisionsX; col++) {
  36674. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36675. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36676. positions.push(position.x, position.y, position.z);
  36677. normals.push(normal.x, normal.y, normal.z);
  36678. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36679. }
  36680. }
  36681. for (row = 0; row < subdivisionsY; row++) {
  36682. for (col = 0; col < subdivisionsX; col++) {
  36683. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36684. indices.push(col + 1 + row * (subdivisionsX + 1));
  36685. indices.push(col + row * (subdivisionsX + 1));
  36686. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36687. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36688. indices.push(col + row * (subdivisionsX + 1));
  36689. }
  36690. }
  36691. // Result
  36692. var vertexData = new VertexData();
  36693. vertexData.indices = indices;
  36694. vertexData.positions = positions;
  36695. vertexData.normals = normals;
  36696. vertexData.uvs = uvs;
  36697. return vertexData;
  36698. };
  36699. /**
  36700. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  36701. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36702. * * xmin the ground minimum X coordinate, optional, default -1
  36703. * * zmin the ground minimum Z coordinate, optional, default -1
  36704. * * xmax the ground maximum X coordinate, optional, default 1
  36705. * * zmax the ground maximum Z coordinate, optional, default 1
  36706. * * 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}
  36707. * * 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}
  36708. * @returns the VertexData of the TiledGround
  36709. */
  36710. VertexData.CreateTiledGround = function (options) {
  36711. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36712. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36713. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36714. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36715. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36716. var precision = options.precision || { w: 1, h: 1 };
  36717. var indices = new Array();
  36718. var positions = new Array();
  36719. var normals = new Array();
  36720. var uvs = new Array();
  36721. var row, col, tileRow, tileCol;
  36722. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36723. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36724. precision.w = (precision.w < 1) ? 1 : precision.w;
  36725. precision.h = (precision.h < 1) ? 1 : precision.h;
  36726. var tileSize = {
  36727. 'w': (xmax - xmin) / subdivisions.w,
  36728. 'h': (zmax - zmin) / subdivisions.h
  36729. };
  36730. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36731. // Indices
  36732. var base = positions.length / 3;
  36733. var rowLength = precision.w + 1;
  36734. for (row = 0; row < precision.h; row++) {
  36735. for (col = 0; col < precision.w; col++) {
  36736. var square = [
  36737. base + col + row * rowLength,
  36738. base + (col + 1) + row * rowLength,
  36739. base + (col + 1) + (row + 1) * rowLength,
  36740. base + col + (row + 1) * rowLength
  36741. ];
  36742. indices.push(square[1]);
  36743. indices.push(square[2]);
  36744. indices.push(square[3]);
  36745. indices.push(square[0]);
  36746. indices.push(square[1]);
  36747. indices.push(square[3]);
  36748. }
  36749. }
  36750. // Position, normals and uvs
  36751. var position = BABYLON.Vector3.Zero();
  36752. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36753. for (row = 0; row <= precision.h; row++) {
  36754. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36755. for (col = 0; col <= precision.w; col++) {
  36756. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36757. position.y = 0;
  36758. positions.push(position.x, position.y, position.z);
  36759. normals.push(normal.x, normal.y, normal.z);
  36760. uvs.push(col / precision.w, row / precision.h);
  36761. }
  36762. }
  36763. }
  36764. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36765. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36766. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36767. }
  36768. }
  36769. // Result
  36770. var vertexData = new VertexData();
  36771. vertexData.indices = indices;
  36772. vertexData.positions = positions;
  36773. vertexData.normals = normals;
  36774. vertexData.uvs = uvs;
  36775. return vertexData;
  36776. };
  36777. /**
  36778. * Creates the VertexData of the Ground designed from a heightmap
  36779. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  36780. * * width the width (x direction) of the ground
  36781. * * height the height (z direction) of the ground
  36782. * * subdivisions the number of subdivisions per side
  36783. * * minHeight the minimum altitude on the ground, optional, default 0
  36784. * * maxHeight the maximum altitude on the ground, optional default 1
  36785. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  36786. * * buffer the array holding the image color data
  36787. * * bufferWidth the width of image
  36788. * * bufferHeight the height of image
  36789. * @returns the VertexData of the Ground designed from a heightmap
  36790. */
  36791. VertexData.CreateGroundFromHeightMap = function (options) {
  36792. var indices = [];
  36793. var positions = [];
  36794. var normals = [];
  36795. var uvs = [];
  36796. var row, col;
  36797. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36798. // Vertices
  36799. for (row = 0; row <= options.subdivisions; row++) {
  36800. for (col = 0; col <= options.subdivisions; col++) {
  36801. 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));
  36802. // Compute height
  36803. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36804. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36805. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36806. var r = options.buffer[pos] / 255.0;
  36807. var g = options.buffer[pos + 1] / 255.0;
  36808. var b = options.buffer[pos + 2] / 255.0;
  36809. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36810. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36811. // Add vertex
  36812. positions.push(position.x, position.y, position.z);
  36813. normals.push(0, 0, 0);
  36814. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36815. }
  36816. }
  36817. // Indices
  36818. for (row = 0; row < options.subdivisions; row++) {
  36819. for (col = 0; col < options.subdivisions; col++) {
  36820. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36821. indices.push(col + 1 + row * (options.subdivisions + 1));
  36822. indices.push(col + row * (options.subdivisions + 1));
  36823. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36824. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36825. indices.push(col + row * (options.subdivisions + 1));
  36826. }
  36827. }
  36828. // Normals
  36829. VertexData.ComputeNormals(positions, indices, normals);
  36830. // Result
  36831. var vertexData = new VertexData();
  36832. vertexData.indices = indices;
  36833. vertexData.positions = positions;
  36834. vertexData.normals = normals;
  36835. vertexData.uvs = uvs;
  36836. return vertexData;
  36837. };
  36838. /**
  36839. * Creates the VertexData for a Plane
  36840. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  36841. * * size sets the width and height of the plane to the value of size, optional default 1
  36842. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  36843. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  36844. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36845. * * 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)
  36846. * * 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)
  36847. * @returns the VertexData of the box
  36848. */
  36849. VertexData.CreatePlane = function (options) {
  36850. var indices = [];
  36851. var positions = [];
  36852. var normals = [];
  36853. var uvs = [];
  36854. var width = options.width || options.size || 1;
  36855. var height = options.height || options.size || 1;
  36856. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36857. // Vertices
  36858. var halfWidth = width / 2.0;
  36859. var halfHeight = height / 2.0;
  36860. positions.push(-halfWidth, -halfHeight, 0);
  36861. normals.push(0, 0, -1.0);
  36862. uvs.push(0.0, 0.0);
  36863. positions.push(halfWidth, -halfHeight, 0);
  36864. normals.push(0, 0, -1.0);
  36865. uvs.push(1.0, 0.0);
  36866. positions.push(halfWidth, halfHeight, 0);
  36867. normals.push(0, 0, -1.0);
  36868. uvs.push(1.0, 1.0);
  36869. positions.push(-halfWidth, halfHeight, 0);
  36870. normals.push(0, 0, -1.0);
  36871. uvs.push(0.0, 1.0);
  36872. // Indices
  36873. indices.push(0);
  36874. indices.push(1);
  36875. indices.push(2);
  36876. indices.push(0);
  36877. indices.push(2);
  36878. indices.push(3);
  36879. // Sides
  36880. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36881. // Result
  36882. var vertexData = new VertexData();
  36883. vertexData.indices = indices;
  36884. vertexData.positions = positions;
  36885. vertexData.normals = normals;
  36886. vertexData.uvs = uvs;
  36887. return vertexData;
  36888. };
  36889. /**
  36890. * Creates the VertexData of the Disc or regular Polygon
  36891. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  36892. * * radius the radius of the disc, optional default 0.5
  36893. * * tessellation the number of polygon sides, optional, default 64
  36894. * * 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
  36895. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36896. * * 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)
  36897. * * 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)
  36898. * @returns the VertexData of the box
  36899. */
  36900. VertexData.CreateDisc = function (options) {
  36901. var positions = new Array();
  36902. var indices = new Array();
  36903. var normals = new Array();
  36904. var uvs = new Array();
  36905. var radius = options.radius || 0.5;
  36906. var tessellation = options.tessellation || 64;
  36907. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36908. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36909. // positions and uvs
  36910. positions.push(0, 0, 0); // disc center first
  36911. uvs.push(0.5, 0.5);
  36912. var theta = Math.PI * 2 * arc;
  36913. var step = theta / tessellation;
  36914. for (var a = 0; a < theta; a += step) {
  36915. var x = Math.cos(a);
  36916. var y = Math.sin(a);
  36917. var u = (x + 1) / 2;
  36918. var v = (1 - y) / 2;
  36919. positions.push(radius * x, radius * y, 0);
  36920. uvs.push(u, v);
  36921. }
  36922. if (arc === 1) {
  36923. positions.push(positions[3], positions[4], positions[5]); // close the circle
  36924. uvs.push(uvs[2], uvs[3]);
  36925. }
  36926. //indices
  36927. var vertexNb = positions.length / 3;
  36928. for (var i = 1; i < vertexNb - 1; i++) {
  36929. indices.push(i + 1, 0, i);
  36930. }
  36931. // result
  36932. VertexData.ComputeNormals(positions, indices, normals);
  36933. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36934. var vertexData = new VertexData();
  36935. vertexData.indices = indices;
  36936. vertexData.positions = positions;
  36937. vertexData.normals = normals;
  36938. vertexData.uvs = uvs;
  36939. return vertexData;
  36940. };
  36941. /**
  36942. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  36943. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  36944. * @param polygon a mesh built from polygonTriangulation.build()
  36945. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36946. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36947. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36948. * @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)
  36949. * @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)
  36950. * @returns the VertexData of the Polygon
  36951. */
  36952. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  36953. var faceUV = fUV || new Array(3);
  36954. var faceColors = fColors;
  36955. var colors = [];
  36956. // default face colors and UV if undefined
  36957. for (var f = 0; f < 3; f++) {
  36958. if (faceUV[f] === undefined) {
  36959. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36960. }
  36961. if (faceColors && faceColors[f] === undefined) {
  36962. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36963. }
  36964. }
  36965. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36966. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36967. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36968. var indices = polygon.getIndices();
  36969. // set face colours and textures
  36970. var idx = 0;
  36971. var face = 0;
  36972. for (var index = 0; index < normals.length; index += 3) {
  36973. //Edge Face no. 1
  36974. if (Math.abs(normals[index + 1]) < 0.001) {
  36975. face = 1;
  36976. }
  36977. //Top Face no. 0
  36978. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  36979. face = 0;
  36980. }
  36981. //Bottom Face no. 2
  36982. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  36983. face = 2;
  36984. }
  36985. idx = index / 3;
  36986. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  36987. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  36988. if (faceColors) {
  36989. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  36990. }
  36991. }
  36992. // sides
  36993. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  36994. // Result
  36995. var vertexData = new VertexData();
  36996. vertexData.indices = indices;
  36997. vertexData.positions = positions;
  36998. vertexData.normals = normals;
  36999. vertexData.uvs = uvs;
  37000. if (faceColors) {
  37001. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37002. vertexData.colors = totalColors;
  37003. }
  37004. return vertexData;
  37005. };
  37006. /**
  37007. * Creates the VertexData of the IcoSphere
  37008. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37009. * * radius the radius of the IcoSphere, optional default 1
  37010. * * radiusX allows stretching in the x direction, optional, default radius
  37011. * * radiusY allows stretching in the y direction, optional, default radius
  37012. * * radiusZ allows stretching in the z direction, optional, default radius
  37013. * * flat when true creates a flat shaded mesh, optional, default true
  37014. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37015. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37016. * * 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)
  37017. * * 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)
  37018. * @returns the VertexData of the IcoSphere
  37019. */
  37020. VertexData.CreateIcoSphere = function (options) {
  37021. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37022. var radius = options.radius || 1;
  37023. var flat = (options.flat === undefined) ? true : options.flat;
  37024. var subdivisions = options.subdivisions || 4;
  37025. var radiusX = options.radiusX || radius;
  37026. var radiusY = options.radiusY || radius;
  37027. var radiusZ = options.radiusZ || radius;
  37028. var t = (1 + Math.sqrt(5)) / 2;
  37029. // 12 vertex x,y,z
  37030. var ico_vertices = [
  37031. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37032. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37033. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37034. ];
  37035. // index of 3 vertex makes a face of icopshere
  37036. var ico_indices = [
  37037. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37038. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37039. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37040. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37041. ];
  37042. // vertex for uv have aliased position, not for UV
  37043. var vertices_unalias_id = [
  37044. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37045. // vertex alias
  37046. 0,
  37047. 2,
  37048. 3,
  37049. 3,
  37050. 3,
  37051. 4,
  37052. 7,
  37053. 8,
  37054. 9,
  37055. 9,
  37056. 10,
  37057. 11 // 23: B + 12
  37058. ];
  37059. // uv as integer step (not pixels !)
  37060. var ico_vertexuv = [
  37061. 5, 1, 3, 1, 6, 4, 0, 0,
  37062. 5, 3, 4, 2, 2, 2, 4, 0,
  37063. 2, 0, 1, 1, 6, 0, 6, 2,
  37064. // vertex alias (for same vertex on different faces)
  37065. 0, 4,
  37066. 3, 3,
  37067. 4, 4,
  37068. 3, 1,
  37069. 4, 2,
  37070. 4, 4,
  37071. 0, 2,
  37072. 1, 1,
  37073. 2, 2,
  37074. 3, 3,
  37075. 1, 3,
  37076. 2, 4 // 23: B + 12
  37077. ];
  37078. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37079. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37080. // First island of uv mapping
  37081. // v = 4h 3+ 2
  37082. // v = 3h 9+ 4
  37083. // v = 2h 9+ 5 B
  37084. // v = 1h 9 1 0
  37085. // v = 0h 3 8 7 A
  37086. // u = 0 1 2 3 4 5 6 *a
  37087. // Second island of uv mapping
  37088. // v = 4h 0+ B+ 4+
  37089. // v = 3h A+ 2+
  37090. // v = 2h 7+ 6 3+
  37091. // v = 1h 8+ 3+
  37092. // v = 0h
  37093. // u = 0 1 2 3 4 5 6 *a
  37094. // Face layout on texture UV mapping
  37095. // ============
  37096. // \ 4 /\ 16 / ======
  37097. // \ / \ / /\ 11 /
  37098. // \/ 7 \/ / \ /
  37099. // ======= / 10 \/
  37100. // /\ 17 /\ =======
  37101. // / \ / \ \ 15 /\
  37102. // / 8 \/ 12 \ \ / \
  37103. // ============ \/ 6 \
  37104. // \ 18 /\ ============
  37105. // \ / \ \ 5 /\ 0 /
  37106. // \/ 13 \ \ / \ /
  37107. // ======= \/ 1 \/
  37108. // =============
  37109. // /\ 19 /\ 2 /\
  37110. // / \ / \ / \
  37111. // / 14 \/ 9 \/ 3 \
  37112. // ===================
  37113. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37114. var ustep = 138 / 1024;
  37115. var vstep = 239 / 1024;
  37116. var uoffset = 60 / 1024;
  37117. var voffset = 26 / 1024;
  37118. // Second island should have margin, not to touch the first island
  37119. // avoid any borderline artefact in pixel rounding
  37120. var island_u_offset = -40 / 1024;
  37121. var island_v_offset = +20 / 1024;
  37122. // face is either island 0 or 1 :
  37123. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37124. var island = [
  37125. 0, 0, 0, 0, 1,
  37126. 0, 0, 1, 1, 0,
  37127. 0, 0, 1, 1, 0,
  37128. 0, 1, 1, 1, 0 // 15 - 19
  37129. ];
  37130. var indices = new Array();
  37131. var positions = new Array();
  37132. var normals = new Array();
  37133. var uvs = new Array();
  37134. var current_indice = 0;
  37135. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37136. var face_vertex_pos = new Array(3);
  37137. var face_vertex_uv = new Array(3);
  37138. var v012;
  37139. for (v012 = 0; v012 < 3; v012++) {
  37140. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37141. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37142. }
  37143. // create all with normals
  37144. for (var face = 0; face < 20; face++) {
  37145. // 3 vertex per face
  37146. for (v012 = 0; v012 < 3; v012++) {
  37147. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37148. var v_id = ico_indices[3 * face + v012];
  37149. // vertex have 3D position (x,y,z)
  37150. 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]);
  37151. // Normalize to get normal, then scale to radius
  37152. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37153. // uv Coordinates from vertex ID
  37154. 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);
  37155. }
  37156. // Subdivide the face (interpolate pos, norm, uv)
  37157. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37158. // - norm is linear interpolation of vertex corner normal
  37159. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37160. // - uv is linear interpolation
  37161. //
  37162. // Topology is as below for sub-divide by 2
  37163. // vertex shown as v0,v1,v2
  37164. // interp index is i1 to progress in range [v0,v1[
  37165. // interp index is i2 to progress in range [v0,v2[
  37166. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37167. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37168. //
  37169. //
  37170. // i2 v2
  37171. // ^ ^
  37172. // / / \
  37173. // / / \
  37174. // / / \
  37175. // / / (0,1) \
  37176. // / #---------\
  37177. // / / \ (0,0)'/ \
  37178. // / / \ / \
  37179. // / / \ / \
  37180. // / / (0,0) \ / (1,0) \
  37181. // / #---------#---------\
  37182. // v0 v1
  37183. //
  37184. // --------------------> i1
  37185. //
  37186. // interp of (i1,i2):
  37187. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37188. // along i1 : lerp(x0,x1, i1/(S-i2))
  37189. //
  37190. // centroid of triangle is needed to get help normal computation
  37191. // (c1,c2) are used for centroid location
  37192. var interp_vertex = function (i1, i2, c1, c2) {
  37193. // vertex is interpolated from
  37194. // - face_vertex_pos[0..2]
  37195. // - face_vertex_uv[0..2]
  37196. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37197. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37198. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37199. pos_interp.normalize();
  37200. var vertex_normal;
  37201. if (flat) {
  37202. // in flat mode, recalculate normal as face centroid normal
  37203. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37204. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37205. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37206. }
  37207. else {
  37208. // in smooth mode, recalculate normal from each single vertex position
  37209. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37210. }
  37211. // Vertex normal need correction due to X,Y,Z radius scaling
  37212. vertex_normal.x /= radiusX;
  37213. vertex_normal.y /= radiusY;
  37214. vertex_normal.z /= radiusZ;
  37215. vertex_normal.normalize();
  37216. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37217. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37218. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37219. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37220. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37221. uvs.push(uv_interp.x, uv_interp.y);
  37222. // push each vertex has member of a face
  37223. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37224. indices.push(current_indice);
  37225. current_indice++;
  37226. };
  37227. for (var i2 = 0; i2 < subdivisions; i2++) {
  37228. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37229. // face : (i1,i2) for /\ :
  37230. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37231. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37232. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37233. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37234. if (i1 + i2 + 1 < subdivisions) {
  37235. // face : (i1,i2)' for \/ :
  37236. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37237. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37238. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37239. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37240. }
  37241. }
  37242. }
  37243. }
  37244. // Sides
  37245. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37246. // Result
  37247. var vertexData = new VertexData();
  37248. vertexData.indices = indices;
  37249. vertexData.positions = positions;
  37250. vertexData.normals = normals;
  37251. vertexData.uvs = uvs;
  37252. return vertexData;
  37253. };
  37254. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37255. /**
  37256. * Creates the VertexData for a Polyhedron
  37257. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37258. * * type provided types are:
  37259. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37260. * * 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)
  37261. * * size the size of the IcoSphere, optional default 1
  37262. * * sizeX allows stretching in the x direction, optional, default size
  37263. * * sizeY allows stretching in the y direction, optional, default size
  37264. * * sizeZ allows stretching in the z direction, optional, default size
  37265. * * 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
  37266. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37267. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37268. * * flat when true creates a flat shaded mesh, optional, default true
  37269. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37270. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37271. * * 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)
  37272. * * 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)
  37273. * @returns the VertexData of the Polyhedron
  37274. */
  37275. VertexData.CreatePolyhedron = function (options) {
  37276. // provided polyhedron types :
  37277. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37278. // 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)
  37279. var polyhedra = [];
  37280. 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]] };
  37281. 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]] };
  37282. polyhedra[2] = {
  37283. 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]],
  37284. 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]]
  37285. };
  37286. polyhedra[3] = {
  37287. 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]],
  37288. 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]]
  37289. };
  37290. polyhedra[4] = {
  37291. 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]],
  37292. 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]]
  37293. };
  37294. 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]] };
  37295. 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]] };
  37296. 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]] };
  37297. 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]] };
  37298. 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]] };
  37299. 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]] };
  37300. 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]] };
  37301. 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]] };
  37302. 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]] };
  37303. polyhedra[14] = {
  37304. 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]],
  37305. 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]]
  37306. };
  37307. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37308. var size = options.size;
  37309. var sizeX = options.sizeX || size || 1;
  37310. var sizeY = options.sizeY || size || 1;
  37311. var sizeZ = options.sizeZ || size || 1;
  37312. var data = options.custom || polyhedra[type];
  37313. var nbfaces = data.face.length;
  37314. var faceUV = options.faceUV || new Array(nbfaces);
  37315. var faceColors = options.faceColors;
  37316. var flat = (options.flat === undefined) ? true : options.flat;
  37317. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37318. var positions = new Array();
  37319. var indices = new Array();
  37320. var normals = new Array();
  37321. var uvs = new Array();
  37322. var colors = new Array();
  37323. var index = 0;
  37324. var faceIdx = 0; // face cursor in the array "indexes"
  37325. var indexes = new Array();
  37326. var i = 0;
  37327. var f = 0;
  37328. var u, v, ang, x, y, tmp;
  37329. // default face colors and UV if undefined
  37330. if (flat) {
  37331. for (f = 0; f < nbfaces; f++) {
  37332. if (faceColors && faceColors[f] === undefined) {
  37333. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37334. }
  37335. if (faceUV && faceUV[f] === undefined) {
  37336. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37337. }
  37338. }
  37339. }
  37340. if (!flat) {
  37341. for (i = 0; i < data.vertex.length; i++) {
  37342. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37343. uvs.push(0, 0);
  37344. }
  37345. for (f = 0; f < nbfaces; f++) {
  37346. for (i = 0; i < data.face[f].length - 2; i++) {
  37347. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37348. }
  37349. }
  37350. }
  37351. else {
  37352. for (f = 0; f < nbfaces; f++) {
  37353. var fl = data.face[f].length; // number of vertices of the current face
  37354. ang = 2 * Math.PI / fl;
  37355. x = 0.5 * Math.tan(ang / 2);
  37356. y = 0.5;
  37357. // positions, uvs, colors
  37358. for (i = 0; i < fl; i++) {
  37359. // positions
  37360. 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);
  37361. indexes.push(index);
  37362. index++;
  37363. // uvs
  37364. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37365. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37366. uvs.push(u, v);
  37367. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37368. y = x * Math.sin(ang) + y * Math.cos(ang);
  37369. x = tmp;
  37370. // colors
  37371. if (faceColors) {
  37372. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37373. }
  37374. }
  37375. // indices from indexes
  37376. for (i = 0; i < fl - 2; i++) {
  37377. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37378. }
  37379. faceIdx += fl;
  37380. }
  37381. }
  37382. VertexData.ComputeNormals(positions, indices, normals);
  37383. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37384. var vertexData = new VertexData();
  37385. vertexData.positions = positions;
  37386. vertexData.indices = indices;
  37387. vertexData.normals = normals;
  37388. vertexData.uvs = uvs;
  37389. if (faceColors && flat) {
  37390. vertexData.colors = colors;
  37391. }
  37392. return vertexData;
  37393. };
  37394. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37395. /**
  37396. * Creates the VertexData for a TorusKnot
  37397. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37398. * * radius the radius of the torus knot, optional, default 2
  37399. * * tube the thickness of the tube, optional, default 0.5
  37400. * * radialSegments the number of sides on each tube segments, optional, default 32
  37401. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37402. * * p the number of windings around the z axis, optional, default 2
  37403. * * q the number of windings around the x axis, optional, default 3
  37404. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37405. * * 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)
  37406. * * 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)
  37407. * @returns the VertexData of the Torus Knot
  37408. */
  37409. VertexData.CreateTorusKnot = function (options) {
  37410. var indices = new Array();
  37411. var positions = new Array();
  37412. var normals = new Array();
  37413. var uvs = new Array();
  37414. var radius = options.radius || 2;
  37415. var tube = options.tube || 0.5;
  37416. var radialSegments = options.radialSegments || 32;
  37417. var tubularSegments = options.tubularSegments || 32;
  37418. var p = options.p || 2;
  37419. var q = options.q || 3;
  37420. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37421. // Helper
  37422. var getPos = function (angle) {
  37423. var cu = Math.cos(angle);
  37424. var su = Math.sin(angle);
  37425. var quOverP = q / p * angle;
  37426. var cs = Math.cos(quOverP);
  37427. var tx = radius * (2 + cs) * 0.5 * cu;
  37428. var ty = radius * (2 + cs) * su * 0.5;
  37429. var tz = radius * Math.sin(quOverP) * 0.5;
  37430. return new BABYLON.Vector3(tx, ty, tz);
  37431. };
  37432. // Vertices
  37433. var i;
  37434. var j;
  37435. for (i = 0; i <= radialSegments; i++) {
  37436. var modI = i % radialSegments;
  37437. var u = modI / radialSegments * 2 * p * Math.PI;
  37438. var p1 = getPos(u);
  37439. var p2 = getPos(u + 0.01);
  37440. var tang = p2.subtract(p1);
  37441. var n = p2.add(p1);
  37442. var bitan = BABYLON.Vector3.Cross(tang, n);
  37443. n = BABYLON.Vector3.Cross(bitan, tang);
  37444. bitan.normalize();
  37445. n.normalize();
  37446. for (j = 0; j < tubularSegments; j++) {
  37447. var modJ = j % tubularSegments;
  37448. var v = modJ / tubularSegments * 2 * Math.PI;
  37449. var cx = -tube * Math.cos(v);
  37450. var cy = tube * Math.sin(v);
  37451. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37452. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37453. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37454. uvs.push(i / radialSegments);
  37455. uvs.push(j / tubularSegments);
  37456. }
  37457. }
  37458. for (i = 0; i < radialSegments; i++) {
  37459. for (j = 0; j < tubularSegments; j++) {
  37460. var jNext = (j + 1) % tubularSegments;
  37461. var a = i * tubularSegments + j;
  37462. var b = (i + 1) * tubularSegments + j;
  37463. var c = (i + 1) * tubularSegments + jNext;
  37464. var d = i * tubularSegments + jNext;
  37465. indices.push(d);
  37466. indices.push(b);
  37467. indices.push(a);
  37468. indices.push(d);
  37469. indices.push(c);
  37470. indices.push(b);
  37471. }
  37472. }
  37473. // Normals
  37474. VertexData.ComputeNormals(positions, indices, normals);
  37475. // Sides
  37476. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37477. // Result
  37478. var vertexData = new VertexData();
  37479. vertexData.indices = indices;
  37480. vertexData.positions = positions;
  37481. vertexData.normals = normals;
  37482. vertexData.uvs = uvs;
  37483. return vertexData;
  37484. };
  37485. // Tools
  37486. /**
  37487. * Compute normals for given positions and indices
  37488. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37489. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37490. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37491. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37492. * * facetNormals : optional array of facet normals (vector3)
  37493. * * facetPositions : optional array of facet positions (vector3)
  37494. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37495. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37496. * * bInfo : optional bounding info, required for facetPartitioning computation
  37497. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37498. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37499. * * useRightHandedSystem: optional boolean to for right handed system computation
  37500. * * depthSort : optional boolean to enable the facet depth sort computation
  37501. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37502. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37503. */
  37504. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37505. // temporary scalar variables
  37506. var index = 0; // facet index
  37507. var p1p2x = 0.0; // p1p2 vector x coordinate
  37508. var p1p2y = 0.0; // p1p2 vector y coordinate
  37509. var p1p2z = 0.0; // p1p2 vector z coordinate
  37510. var p3p2x = 0.0; // p3p2 vector x coordinate
  37511. var p3p2y = 0.0; // p3p2 vector y coordinate
  37512. var p3p2z = 0.0; // p3p2 vector z coordinate
  37513. var faceNormalx = 0.0; // facet normal x coordinate
  37514. var faceNormaly = 0.0; // facet normal y coordinate
  37515. var faceNormalz = 0.0; // facet normal z coordinate
  37516. var length = 0.0; // facet normal length before normalization
  37517. var v1x = 0; // vector1 x index in the positions array
  37518. var v1y = 0; // vector1 y index in the positions array
  37519. var v1z = 0; // vector1 z index in the positions array
  37520. var v2x = 0; // vector2 x index in the positions array
  37521. var v2y = 0; // vector2 y index in the positions array
  37522. var v2z = 0; // vector2 z index in the positions array
  37523. var v3x = 0; // vector3 x index in the positions array
  37524. var v3y = 0; // vector3 y index in the positions array
  37525. var v3z = 0; // vector3 z index in the positions array
  37526. var computeFacetNormals = false;
  37527. var computeFacetPositions = false;
  37528. var computeFacetPartitioning = false;
  37529. var computeDepthSort = false;
  37530. var faceNormalSign = 1;
  37531. var ratio = 0;
  37532. var distanceTo = null;
  37533. if (options) {
  37534. computeFacetNormals = (options.facetNormals) ? true : false;
  37535. computeFacetPositions = (options.facetPositions) ? true : false;
  37536. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37537. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37538. ratio = options.ratio || 0;
  37539. computeDepthSort = (options.depthSort) ? true : false;
  37540. distanceTo = (options.distanceTo);
  37541. if (computeDepthSort) {
  37542. if (distanceTo === undefined) {
  37543. distanceTo = BABYLON.Vector3.Zero();
  37544. }
  37545. var depthSortedFacets = options.depthSortedFacets;
  37546. }
  37547. }
  37548. // facetPartitioning reinit if needed
  37549. var xSubRatio = 0;
  37550. var ySubRatio = 0;
  37551. var zSubRatio = 0;
  37552. var subSq = 0;
  37553. if (computeFacetPartitioning && options && options.bbSize) {
  37554. var ox = 0; // X partitioning index for facet position
  37555. var oy = 0; // Y partinioning index for facet position
  37556. var oz = 0; // Z partinioning index for facet position
  37557. var b1x = 0; // X partitioning index for facet v1 vertex
  37558. var b1y = 0; // Y partitioning index for facet v1 vertex
  37559. var b1z = 0; // z partitioning index for facet v1 vertex
  37560. var b2x = 0; // X partitioning index for facet v2 vertex
  37561. var b2y = 0; // Y partitioning index for facet v2 vertex
  37562. var b2z = 0; // Z partitioning index for facet v2 vertex
  37563. var b3x = 0; // X partitioning index for facet v3 vertex
  37564. var b3y = 0; // Y partitioning index for facet v3 vertex
  37565. var b3z = 0; // Z partitioning index for facet v3 vertex
  37566. var block_idx_o = 0; // facet barycenter block index
  37567. var block_idx_v1 = 0; // v1 vertex block index
  37568. var block_idx_v2 = 0; // v2 vertex block index
  37569. var block_idx_v3 = 0; // v3 vertex block index
  37570. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37571. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37572. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37573. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37574. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37575. subSq = options.subDiv.max * options.subDiv.max;
  37576. options.facetPartitioning.length = 0;
  37577. }
  37578. // reset the normals
  37579. for (index = 0; index < positions.length; index++) {
  37580. normals[index] = 0.0;
  37581. }
  37582. // Loop : 1 indice triplet = 1 facet
  37583. var nbFaces = (indices.length / 3) | 0;
  37584. for (index = 0; index < nbFaces; index++) {
  37585. // get the indexes of the coordinates of each vertex of the facet
  37586. v1x = indices[index * 3] * 3;
  37587. v1y = v1x + 1;
  37588. v1z = v1x + 2;
  37589. v2x = indices[index * 3 + 1] * 3;
  37590. v2y = v2x + 1;
  37591. v2z = v2x + 2;
  37592. v3x = indices[index * 3 + 2] * 3;
  37593. v3y = v3x + 1;
  37594. v3z = v3x + 2;
  37595. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37596. p1p2y = positions[v1y] - positions[v2y];
  37597. p1p2z = positions[v1z] - positions[v2z];
  37598. p3p2x = positions[v3x] - positions[v2x];
  37599. p3p2y = positions[v3y] - positions[v2y];
  37600. p3p2z = positions[v3z] - positions[v2z];
  37601. // compute the face normal with the cross product
  37602. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37603. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37604. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37605. // normalize this normal and store it in the array facetData
  37606. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37607. length = (length === 0) ? 1.0 : length;
  37608. faceNormalx /= length;
  37609. faceNormaly /= length;
  37610. faceNormalz /= length;
  37611. if (computeFacetNormals && options) {
  37612. options.facetNormals[index].x = faceNormalx;
  37613. options.facetNormals[index].y = faceNormaly;
  37614. options.facetNormals[index].z = faceNormalz;
  37615. }
  37616. if (computeFacetPositions && options) {
  37617. // compute and the facet barycenter coordinates in the array facetPositions
  37618. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37619. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37620. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37621. }
  37622. if (computeFacetPartitioning && options) {
  37623. // store the facet indexes in arrays in the main facetPartitioning array :
  37624. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37625. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37626. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37627. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37628. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37629. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37630. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37631. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37632. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37633. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37634. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37635. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37636. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37637. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37638. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37639. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37640. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37641. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37642. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37643. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37644. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37645. // push each facet index in each block containing the vertex
  37646. options.facetPartitioning[block_idx_v1].push(index);
  37647. if (block_idx_v2 != block_idx_v1) {
  37648. options.facetPartitioning[block_idx_v2].push(index);
  37649. }
  37650. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37651. options.facetPartitioning[block_idx_v3].push(index);
  37652. }
  37653. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37654. options.facetPartitioning[block_idx_o].push(index);
  37655. }
  37656. }
  37657. if (computeDepthSort && options && options.facetPositions) {
  37658. var dsf = depthSortedFacets[index];
  37659. dsf.ind = index * 3;
  37660. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37661. }
  37662. // compute the normals anyway
  37663. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37664. normals[v1y] += faceNormaly;
  37665. normals[v1z] += faceNormalz;
  37666. normals[v2x] += faceNormalx;
  37667. normals[v2y] += faceNormaly;
  37668. normals[v2z] += faceNormalz;
  37669. normals[v3x] += faceNormalx;
  37670. normals[v3y] += faceNormaly;
  37671. normals[v3z] += faceNormalz;
  37672. }
  37673. // last normalization of each normal
  37674. for (index = 0; index < normals.length / 3; index++) {
  37675. faceNormalx = normals[index * 3];
  37676. faceNormaly = normals[index * 3 + 1];
  37677. faceNormalz = normals[index * 3 + 2];
  37678. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37679. length = (length === 0) ? 1.0 : length;
  37680. faceNormalx /= length;
  37681. faceNormaly /= length;
  37682. faceNormalz /= length;
  37683. normals[index * 3] = faceNormalx;
  37684. normals[index * 3 + 1] = faceNormaly;
  37685. normals[index * 3 + 2] = faceNormalz;
  37686. }
  37687. };
  37688. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37689. var li = indices.length;
  37690. var ln = normals.length;
  37691. var i;
  37692. var n;
  37693. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37694. switch (sideOrientation) {
  37695. case BABYLON.Mesh.FRONTSIDE:
  37696. // nothing changed
  37697. break;
  37698. case BABYLON.Mesh.BACKSIDE:
  37699. var tmp;
  37700. // indices
  37701. for (i = 0; i < li; i += 3) {
  37702. tmp = indices[i];
  37703. indices[i] = indices[i + 2];
  37704. indices[i + 2] = tmp;
  37705. }
  37706. // normals
  37707. for (n = 0; n < ln; n++) {
  37708. normals[n] = -normals[n];
  37709. }
  37710. break;
  37711. case BABYLON.Mesh.DOUBLESIDE:
  37712. // positions
  37713. var lp = positions.length;
  37714. var l = lp / 3;
  37715. for (var p = 0; p < lp; p++) {
  37716. positions[lp + p] = positions[p];
  37717. }
  37718. // indices
  37719. for (i = 0; i < li; i += 3) {
  37720. indices[i + li] = indices[i + 2] + l;
  37721. indices[i + 1 + li] = indices[i + 1] + l;
  37722. indices[i + 2 + li] = indices[i] + l;
  37723. }
  37724. // normals
  37725. for (n = 0; n < ln; n++) {
  37726. normals[ln + n] = -normals[n];
  37727. }
  37728. // uvs
  37729. var lu = uvs.length;
  37730. var u = 0;
  37731. for (u = 0; u < lu; u++) {
  37732. uvs[u + lu] = uvs[u];
  37733. }
  37734. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37735. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37736. u = 0;
  37737. for (i = 0; i < lu / 2; i++) {
  37738. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  37739. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  37740. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  37741. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  37742. u += 2;
  37743. }
  37744. break;
  37745. }
  37746. };
  37747. /**
  37748. * Applies VertexData created from the imported parameters to the geometry
  37749. * @param parsedVertexData the parsed data from an imported file
  37750. * @param geometry the geometry to apply the VertexData to
  37751. */
  37752. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37753. var vertexData = new VertexData();
  37754. // positions
  37755. var positions = parsedVertexData.positions;
  37756. if (positions) {
  37757. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37758. }
  37759. // normals
  37760. var normals = parsedVertexData.normals;
  37761. if (normals) {
  37762. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37763. }
  37764. // tangents
  37765. var tangents = parsedVertexData.tangents;
  37766. if (tangents) {
  37767. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  37768. }
  37769. // uvs
  37770. var uvs = parsedVertexData.uvs;
  37771. if (uvs) {
  37772. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37773. }
  37774. // uv2s
  37775. var uv2s = parsedVertexData.uv2s;
  37776. if (uv2s) {
  37777. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37778. }
  37779. // uv3s
  37780. var uv3s = parsedVertexData.uv3s;
  37781. if (uv3s) {
  37782. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37783. }
  37784. // uv4s
  37785. var uv4s = parsedVertexData.uv4s;
  37786. if (uv4s) {
  37787. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37788. }
  37789. // uv5s
  37790. var uv5s = parsedVertexData.uv5s;
  37791. if (uv5s) {
  37792. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37793. }
  37794. // uv6s
  37795. var uv6s = parsedVertexData.uv6s;
  37796. if (uv6s) {
  37797. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37798. }
  37799. // colors
  37800. var colors = parsedVertexData.colors;
  37801. if (colors) {
  37802. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37803. }
  37804. // matricesIndices
  37805. var matricesIndices = parsedVertexData.matricesIndices;
  37806. if (matricesIndices) {
  37807. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37808. }
  37809. // matricesWeights
  37810. var matricesWeights = parsedVertexData.matricesWeights;
  37811. if (matricesWeights) {
  37812. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37813. }
  37814. // indices
  37815. var indices = parsedVertexData.indices;
  37816. if (indices) {
  37817. vertexData.indices = indices;
  37818. }
  37819. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37820. };
  37821. return VertexData;
  37822. }());
  37823. BABYLON.VertexData = VertexData;
  37824. })(BABYLON || (BABYLON = {}));
  37825. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37826. "use strict";
  37827. var BABYLON;
  37828. (function (BABYLON) {
  37829. /**
  37830. * Class used to store geometry data (vertex buffers + index buffer)
  37831. */
  37832. var Geometry = /** @class */ (function () {
  37833. /**
  37834. * Creates a new geometry
  37835. * @param id defines the unique ID
  37836. * @param scene defines the hosting scene
  37837. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  37838. * @param updatable defines if geometry must be updatable (false by default)
  37839. * @param mesh defines the mesh that will be associated with the geometry
  37840. */
  37841. function Geometry(id, scene, vertexData, updatable, mesh) {
  37842. if (updatable === void 0) { updatable = false; }
  37843. if (mesh === void 0) { mesh = null; }
  37844. /**
  37845. * Gets the delay loading state of the geometry (none by default which means not delayed)
  37846. */
  37847. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37848. this._totalVertices = 0;
  37849. this._isDisposed = false;
  37850. this._indexBufferIsUpdatable = false;
  37851. this.id = id;
  37852. this._engine = scene.getEngine();
  37853. this._meshes = [];
  37854. this._scene = scene;
  37855. //Init vertex buffer cache
  37856. this._vertexBuffers = {};
  37857. this._indices = [];
  37858. this._updatable = updatable;
  37859. // vertexData
  37860. if (vertexData) {
  37861. this.setAllVerticesData(vertexData, updatable);
  37862. }
  37863. else {
  37864. this._totalVertices = 0;
  37865. this._indices = [];
  37866. }
  37867. if (this._engine.getCaps().vertexArrayObject) {
  37868. this._vertexArrayObjects = {};
  37869. }
  37870. // applyToMesh
  37871. if (mesh) {
  37872. if (mesh.getClassName() === "LinesMesh") {
  37873. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37874. this._updateExtend();
  37875. }
  37876. this.applyToMesh(mesh);
  37877. mesh.computeWorldMatrix(true);
  37878. }
  37879. }
  37880. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37881. /**
  37882. * 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
  37883. */
  37884. get: function () {
  37885. return this._boundingBias;
  37886. },
  37887. /**
  37888. * 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
  37889. */
  37890. set: function (value) {
  37891. if (this._boundingBias && this._boundingBias.equals(value)) {
  37892. return;
  37893. }
  37894. this._boundingBias = value.clone();
  37895. this._updateBoundingInfo(true, null);
  37896. },
  37897. enumerable: true,
  37898. configurable: true
  37899. });
  37900. /**
  37901. * Static function used to attach a new empty geometry to a mesh
  37902. * @param mesh defines the mesh to attach the geometry to
  37903. * @returns the new {BABYLON.Geometry}
  37904. */
  37905. Geometry.CreateGeometryForMesh = function (mesh) {
  37906. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  37907. geometry.applyToMesh(mesh);
  37908. return geometry;
  37909. };
  37910. Object.defineProperty(Geometry.prototype, "extend", {
  37911. /**
  37912. * Gets the current extend of the geometry
  37913. */
  37914. get: function () {
  37915. return this._extend;
  37916. },
  37917. enumerable: true,
  37918. configurable: true
  37919. });
  37920. /**
  37921. * Gets the hosting scene
  37922. * @returns the hosting {BABYLON.Scene}
  37923. */
  37924. Geometry.prototype.getScene = function () {
  37925. return this._scene;
  37926. };
  37927. /**
  37928. * Gets the hosting engine
  37929. * @returns the hosting {BABYLON.Engine}
  37930. */
  37931. Geometry.prototype.getEngine = function () {
  37932. return this._engine;
  37933. };
  37934. /**
  37935. * Defines if the geometry is ready to use
  37936. * @returns true if the geometry is ready to be used
  37937. */
  37938. Geometry.prototype.isReady = function () {
  37939. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37940. };
  37941. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37942. /**
  37943. * Gets a value indicating that the geometry should not be serialized
  37944. */
  37945. get: function () {
  37946. for (var index = 0; index < this._meshes.length; index++) {
  37947. if (!this._meshes[index].doNotSerialize) {
  37948. return false;
  37949. }
  37950. }
  37951. return true;
  37952. },
  37953. enumerable: true,
  37954. configurable: true
  37955. });
  37956. /** @ignore */
  37957. Geometry.prototype._rebuild = function () {
  37958. if (this._vertexArrayObjects) {
  37959. this._vertexArrayObjects = {};
  37960. }
  37961. // Index buffer
  37962. if (this._meshes.length !== 0 && this._indices) {
  37963. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37964. }
  37965. // Vertex buffers
  37966. for (var key in this._vertexBuffers) {
  37967. var vertexBuffer = this._vertexBuffers[key];
  37968. vertexBuffer._rebuild();
  37969. }
  37970. };
  37971. /**
  37972. * Affects all gemetry data in one call
  37973. * @param vertexData defines the geometry data
  37974. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  37975. */
  37976. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37977. vertexData.applyToGeometry(this, updatable);
  37978. this.notifyUpdate();
  37979. };
  37980. /**
  37981. * Set specific vertex data
  37982. * @param kind defines the data kind (Position, normal, etc...)
  37983. * @param data defines the vertex data to use
  37984. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  37985. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  37986. */
  37987. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37988. if (updatable === void 0) { updatable = false; }
  37989. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37990. this.setVerticesBuffer(buffer);
  37991. };
  37992. /**
  37993. * Removes a specific vertex data
  37994. * @param kind defines the data kind (Position, normal, etc...)
  37995. */
  37996. Geometry.prototype.removeVerticesData = function (kind) {
  37997. if (this._vertexBuffers[kind]) {
  37998. this._vertexBuffers[kind].dispose();
  37999. delete this._vertexBuffers[kind];
  38000. }
  38001. };
  38002. /**
  38003. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38004. * @param buffer defines the vertex buffer to use
  38005. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38006. */
  38007. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38008. if (totalVertices === void 0) { totalVertices = null; }
  38009. var kind = buffer.getKind();
  38010. if (this._vertexBuffers[kind]) {
  38011. this._vertexBuffers[kind].dispose();
  38012. }
  38013. this._vertexBuffers[kind] = buffer;
  38014. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38015. var data = buffer.getData();
  38016. if (totalVertices != null) {
  38017. this._totalVertices = totalVertices;
  38018. }
  38019. else {
  38020. if (data != null) {
  38021. this._totalVertices = data.length / (buffer.byteStride / 4);
  38022. }
  38023. }
  38024. this._updateExtend(data);
  38025. this._resetPointsArrayCache();
  38026. var meshes = this._meshes;
  38027. var numOfMeshes = meshes.length;
  38028. for (var index = 0; index < numOfMeshes; index++) {
  38029. var mesh = meshes[index];
  38030. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38031. mesh._createGlobalSubMesh(false);
  38032. mesh.computeWorldMatrix(true);
  38033. }
  38034. }
  38035. this.notifyUpdate(kind);
  38036. if (this._vertexArrayObjects) {
  38037. this._disposeVertexArrayObjects();
  38038. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38039. }
  38040. };
  38041. /**
  38042. * Update a specific vertex buffer
  38043. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38044. * It will do nothing if the buffer is not updatable
  38045. * @param kind defines the data kind (Position, normal, etc...)
  38046. * @param data defines the data to use
  38047. * @param offset defines the offset in the target buffer where to store the data
  38048. */
  38049. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  38050. var vertexBuffer = this.getVertexBuffer(kind);
  38051. if (!vertexBuffer) {
  38052. return;
  38053. }
  38054. vertexBuffer.updateDirectly(data, offset);
  38055. this.notifyUpdate(kind);
  38056. };
  38057. /**
  38058. * Update a specific vertex buffer
  38059. * This function will create a new buffer if the current one is not updatable
  38060. * @param kind defines the data kind (Position, normal, etc...)
  38061. * @param data defines the data to use
  38062. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38063. */
  38064. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38065. if (updateExtends === void 0) { updateExtends = false; }
  38066. var vertexBuffer = this.getVertexBuffer(kind);
  38067. if (!vertexBuffer) {
  38068. return;
  38069. }
  38070. vertexBuffer.update(data);
  38071. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38072. this._updateBoundingInfo(updateExtends, data);
  38073. }
  38074. this.notifyUpdate(kind);
  38075. };
  38076. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38077. if (updateExtends) {
  38078. this._updateExtend(data);
  38079. }
  38080. var meshes = this._meshes;
  38081. var numOfMeshes = meshes.length;
  38082. this._resetPointsArrayCache();
  38083. for (var index = 0; index < numOfMeshes; index++) {
  38084. var mesh = meshes[index];
  38085. if (updateExtends) {
  38086. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38087. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38088. var subMesh = mesh.subMeshes[subIndex];
  38089. subMesh.refreshBoundingInfo();
  38090. }
  38091. }
  38092. }
  38093. };
  38094. /** @ignore */
  38095. Geometry.prototype._bind = function (effect, indexToBind) {
  38096. if (!effect) {
  38097. return;
  38098. }
  38099. if (indexToBind === undefined) {
  38100. indexToBind = this._indexBuffer;
  38101. }
  38102. var vbs = this.getVertexBuffers();
  38103. if (!vbs) {
  38104. return;
  38105. }
  38106. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38107. this._engine.bindBuffers(vbs, indexToBind, effect);
  38108. return;
  38109. }
  38110. // Using VAO
  38111. if (!this._vertexArrayObjects[effect.key]) {
  38112. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38113. }
  38114. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38115. };
  38116. /**
  38117. * Gets total number of vertices
  38118. * @returns the total number of vertices
  38119. */
  38120. Geometry.prototype.getTotalVertices = function () {
  38121. if (!this.isReady()) {
  38122. return 0;
  38123. }
  38124. return this._totalVertices;
  38125. };
  38126. /**
  38127. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38128. * @param kind defines the data kind (Position, normal, etc...)
  38129. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38130. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38131. * @returns a float array containing vertex data
  38132. */
  38133. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38134. var vertexBuffer = this.getVertexBuffer(kind);
  38135. if (!vertexBuffer) {
  38136. return null;
  38137. }
  38138. var data = vertexBuffer.getData();
  38139. if (!data) {
  38140. return null;
  38141. }
  38142. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38143. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38144. var count = this._totalVertices * defaultStride;
  38145. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38146. var copy_1 = new Array(count);
  38147. vertexBuffer.forEach(count, function (value, index) {
  38148. copy_1[index] = value;
  38149. });
  38150. return copy_1;
  38151. }
  38152. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38153. if (data instanceof Array) {
  38154. var offset = vertexBuffer.byteOffset / 4;
  38155. return BABYLON.Tools.Slice(data, offset, offset + count);
  38156. }
  38157. else if (data instanceof ArrayBuffer) {
  38158. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38159. }
  38160. else {
  38161. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38162. }
  38163. }
  38164. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38165. return BABYLON.Tools.Slice(data);
  38166. }
  38167. return data;
  38168. };
  38169. /**
  38170. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38171. * @param kind defines the data kind (Position, normal, etc...)
  38172. * @returns true if the vertex buffer with the specified kind is updatable
  38173. */
  38174. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38175. var vb = this._vertexBuffers[kind];
  38176. if (!vb) {
  38177. return false;
  38178. }
  38179. return vb.isUpdatable();
  38180. };
  38181. /**
  38182. * Gets a specific vertex buffer
  38183. * @param kind defines the data kind (Position, normal, etc...)
  38184. * @returns a {BABYLON.VertexBuffer}
  38185. */
  38186. Geometry.prototype.getVertexBuffer = function (kind) {
  38187. if (!this.isReady()) {
  38188. return null;
  38189. }
  38190. return this._vertexBuffers[kind];
  38191. };
  38192. /**
  38193. * Returns all vertex buffers
  38194. * @return an object holding all vertex buffers indexed by kind
  38195. */
  38196. Geometry.prototype.getVertexBuffers = function () {
  38197. if (!this.isReady()) {
  38198. return null;
  38199. }
  38200. return this._vertexBuffers;
  38201. };
  38202. /**
  38203. * Gets a boolean indicating if specific vertex buffer is present
  38204. * @param kind defines the data kind (Position, normal, etc...)
  38205. * @returns true if data is present
  38206. */
  38207. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38208. if (!this._vertexBuffers) {
  38209. if (this._delayInfo) {
  38210. return this._delayInfo.indexOf(kind) !== -1;
  38211. }
  38212. return false;
  38213. }
  38214. return this._vertexBuffers[kind] !== undefined;
  38215. };
  38216. /**
  38217. * Gets a list of all attached data kinds (Position, normal, etc...)
  38218. * @returns a list of string containing all kinds
  38219. */
  38220. Geometry.prototype.getVerticesDataKinds = function () {
  38221. var result = [];
  38222. var kind;
  38223. if (!this._vertexBuffers && this._delayInfo) {
  38224. for (kind in this._delayInfo) {
  38225. result.push(kind);
  38226. }
  38227. }
  38228. else {
  38229. for (kind in this._vertexBuffers) {
  38230. result.push(kind);
  38231. }
  38232. }
  38233. return result;
  38234. };
  38235. /**
  38236. * Update index buffer
  38237. * @param indices defines the indices to store in the index buffer
  38238. * @param offset defines the offset in the target buffer where to store the data
  38239. */
  38240. Geometry.prototype.updateIndices = function (indices, offset) {
  38241. if (!this._indexBuffer) {
  38242. return;
  38243. }
  38244. if (!this._indexBufferIsUpdatable) {
  38245. this.setIndices(indices, null, true);
  38246. }
  38247. else {
  38248. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38249. }
  38250. };
  38251. /**
  38252. * Creates a new index buffer
  38253. * @param indices defines the indices to store in the index buffer
  38254. * @param totalVertices defines the total number of vertices (could be null)
  38255. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38256. */
  38257. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38258. if (totalVertices === void 0) { totalVertices = null; }
  38259. if (updatable === void 0) { updatable = false; }
  38260. if (this._indexBuffer) {
  38261. this._engine._releaseBuffer(this._indexBuffer);
  38262. }
  38263. this._disposeVertexArrayObjects();
  38264. this._indices = indices;
  38265. this._indexBufferIsUpdatable = updatable;
  38266. if (this._meshes.length !== 0 && this._indices) {
  38267. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38268. }
  38269. if (totalVertices != undefined) {
  38270. this._totalVertices = totalVertices;
  38271. }
  38272. var meshes = this._meshes;
  38273. var numOfMeshes = meshes.length;
  38274. for (var index = 0; index < numOfMeshes; index++) {
  38275. meshes[index]._createGlobalSubMesh(true);
  38276. }
  38277. this.notifyUpdate();
  38278. };
  38279. /**
  38280. * Return the total number of indices
  38281. * @returns the total number of indices
  38282. */
  38283. Geometry.prototype.getTotalIndices = function () {
  38284. if (!this.isReady()) {
  38285. return 0;
  38286. }
  38287. return this._indices.length;
  38288. };
  38289. /**
  38290. * Gets the index buffer array
  38291. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38292. * @returns the index buffer array
  38293. */
  38294. Geometry.prototype.getIndices = function (copyWhenShared) {
  38295. if (!this.isReady()) {
  38296. return null;
  38297. }
  38298. var orig = this._indices;
  38299. if (!copyWhenShared || this._meshes.length === 1) {
  38300. return orig;
  38301. }
  38302. else {
  38303. var len = orig.length;
  38304. var copy = [];
  38305. for (var i = 0; i < len; i++) {
  38306. copy.push(orig[i]);
  38307. }
  38308. return copy;
  38309. }
  38310. };
  38311. /**
  38312. * Gets the index buffer
  38313. * @return the index buffer
  38314. */
  38315. Geometry.prototype.getIndexBuffer = function () {
  38316. if (!this.isReady()) {
  38317. return null;
  38318. }
  38319. return this._indexBuffer;
  38320. };
  38321. /** @ignore */
  38322. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38323. if (effect === void 0) { effect = null; }
  38324. if (!effect || !this._vertexArrayObjects) {
  38325. return;
  38326. }
  38327. if (this._vertexArrayObjects[effect.key]) {
  38328. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38329. delete this._vertexArrayObjects[effect.key];
  38330. }
  38331. };
  38332. /**
  38333. * Release the associated resources for a specific mesh
  38334. * @param mesh defines the source mesh
  38335. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38336. */
  38337. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38338. var meshes = this._meshes;
  38339. var index = meshes.indexOf(mesh);
  38340. if (index === -1) {
  38341. return;
  38342. }
  38343. meshes.splice(index, 1);
  38344. mesh._geometry = null;
  38345. if (meshes.length === 0 && shouldDispose) {
  38346. this.dispose();
  38347. }
  38348. };
  38349. /**
  38350. * Apply current geometry to a given mesh
  38351. * @param mesh defines the mesh to apply geometry to
  38352. */
  38353. Geometry.prototype.applyToMesh = function (mesh) {
  38354. if (mesh._geometry === this) {
  38355. return;
  38356. }
  38357. var previousGeometry = mesh._geometry;
  38358. if (previousGeometry) {
  38359. previousGeometry.releaseForMesh(mesh);
  38360. }
  38361. var meshes = this._meshes;
  38362. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38363. mesh._geometry = this;
  38364. this._scene.pushGeometry(this);
  38365. meshes.push(mesh);
  38366. if (this.isReady()) {
  38367. this._applyToMesh(mesh);
  38368. }
  38369. else {
  38370. mesh._boundingInfo = this._boundingInfo;
  38371. }
  38372. };
  38373. Geometry.prototype._updateExtend = function (data) {
  38374. if (data === void 0) { data = null; }
  38375. if (!data) {
  38376. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38377. }
  38378. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38379. };
  38380. Geometry.prototype._applyToMesh = function (mesh) {
  38381. var numOfMeshes = this._meshes.length;
  38382. // vertexBuffers
  38383. for (var kind in this._vertexBuffers) {
  38384. if (numOfMeshes === 1) {
  38385. this._vertexBuffers[kind].create();
  38386. }
  38387. var buffer = this._vertexBuffers[kind].getBuffer();
  38388. if (buffer)
  38389. buffer.references = numOfMeshes;
  38390. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38391. if (!this._extend) {
  38392. this._updateExtend();
  38393. }
  38394. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38395. mesh._createGlobalSubMesh(false);
  38396. //bounding info was just created again, world matrix should be applied again.
  38397. mesh._updateBoundingInfo();
  38398. }
  38399. }
  38400. // indexBuffer
  38401. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38402. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38403. }
  38404. if (this._indexBuffer) {
  38405. this._indexBuffer.references = numOfMeshes;
  38406. }
  38407. };
  38408. Geometry.prototype.notifyUpdate = function (kind) {
  38409. if (this.onGeometryUpdated) {
  38410. this.onGeometryUpdated(this, kind);
  38411. }
  38412. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38413. var mesh = _a[_i];
  38414. mesh._markSubMeshesAsAttributesDirty();
  38415. }
  38416. };
  38417. /**
  38418. * Load the geometry if it was flagged as delay loaded
  38419. * @param scene defines the hosting scene
  38420. * @param onLoaded defines a callback called when the geometry is loaded
  38421. */
  38422. Geometry.prototype.load = function (scene, onLoaded) {
  38423. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38424. return;
  38425. }
  38426. if (this.isReady()) {
  38427. if (onLoaded) {
  38428. onLoaded();
  38429. }
  38430. return;
  38431. }
  38432. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38433. this._queueLoad(scene, onLoaded);
  38434. };
  38435. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38436. var _this = this;
  38437. if (!this.delayLoadingFile) {
  38438. return;
  38439. }
  38440. scene._addPendingData(this);
  38441. scene._loadFile(this.delayLoadingFile, function (data) {
  38442. if (!_this._delayLoadingFunction) {
  38443. return;
  38444. }
  38445. _this._delayLoadingFunction(JSON.parse(data), _this);
  38446. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38447. _this._delayInfo = [];
  38448. scene._removePendingData(_this);
  38449. var meshes = _this._meshes;
  38450. var numOfMeshes = meshes.length;
  38451. for (var index = 0; index < numOfMeshes; index++) {
  38452. _this._applyToMesh(meshes[index]);
  38453. }
  38454. if (onLoaded) {
  38455. onLoaded();
  38456. }
  38457. }, undefined, true);
  38458. };
  38459. /**
  38460. * Invert the geometry to move from a right handed system to a left handed one.
  38461. */
  38462. Geometry.prototype.toLeftHanded = function () {
  38463. // Flip faces
  38464. var tIndices = this.getIndices(false);
  38465. if (tIndices != null && tIndices.length > 0) {
  38466. for (var i = 0; i < tIndices.length; i += 3) {
  38467. var tTemp = tIndices[i + 0];
  38468. tIndices[i + 0] = tIndices[i + 2];
  38469. tIndices[i + 2] = tTemp;
  38470. }
  38471. this.setIndices(tIndices);
  38472. }
  38473. // Negate position.z
  38474. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38475. if (tPositions != null && tPositions.length > 0) {
  38476. for (var i = 0; i < tPositions.length; i += 3) {
  38477. tPositions[i + 2] = -tPositions[i + 2];
  38478. }
  38479. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38480. }
  38481. // Negate normal.z
  38482. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38483. if (tNormals != null && tNormals.length > 0) {
  38484. for (var i = 0; i < tNormals.length; i += 3) {
  38485. tNormals[i + 2] = -tNormals[i + 2];
  38486. }
  38487. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38488. }
  38489. };
  38490. // Cache
  38491. /** @ignore */
  38492. Geometry.prototype._resetPointsArrayCache = function () {
  38493. this._positions = null;
  38494. };
  38495. /** @ignore */
  38496. Geometry.prototype._generatePointsArray = function () {
  38497. if (this._positions)
  38498. return true;
  38499. this._positions = [];
  38500. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38501. if (!data) {
  38502. return false;
  38503. }
  38504. for (var index = 0; index < data.length; index += 3) {
  38505. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38506. }
  38507. return true;
  38508. };
  38509. /**
  38510. * Gets a value indicating if the geometry is disposed
  38511. * @returns true if the geometry was disposed
  38512. */
  38513. Geometry.prototype.isDisposed = function () {
  38514. return this._isDisposed;
  38515. };
  38516. Geometry.prototype._disposeVertexArrayObjects = function () {
  38517. if (this._vertexArrayObjects) {
  38518. for (var kind in this._vertexArrayObjects) {
  38519. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38520. }
  38521. this._vertexArrayObjects = {};
  38522. }
  38523. };
  38524. /**
  38525. * Free all associated resources
  38526. */
  38527. Geometry.prototype.dispose = function () {
  38528. var meshes = this._meshes;
  38529. var numOfMeshes = meshes.length;
  38530. var index;
  38531. for (index = 0; index < numOfMeshes; index++) {
  38532. this.releaseForMesh(meshes[index]);
  38533. }
  38534. this._meshes = [];
  38535. this._disposeVertexArrayObjects();
  38536. for (var kind in this._vertexBuffers) {
  38537. this._vertexBuffers[kind].dispose();
  38538. }
  38539. this._vertexBuffers = {};
  38540. this._totalVertices = 0;
  38541. if (this._indexBuffer) {
  38542. this._engine._releaseBuffer(this._indexBuffer);
  38543. }
  38544. this._indexBuffer = null;
  38545. this._indices = [];
  38546. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38547. this.delayLoadingFile = null;
  38548. this._delayLoadingFunction = null;
  38549. this._delayInfo = [];
  38550. this._boundingInfo = null;
  38551. this._scene.removeGeometry(this);
  38552. this._isDisposed = true;
  38553. };
  38554. /**
  38555. * Clone the current geometry into a new geometry
  38556. * @param id defines the unique ID of the new geometry
  38557. * @returns a new geometry object
  38558. */
  38559. Geometry.prototype.copy = function (id) {
  38560. var vertexData = new BABYLON.VertexData();
  38561. vertexData.indices = [];
  38562. var indices = this.getIndices();
  38563. if (indices) {
  38564. for (var index = 0; index < indices.length; index++) {
  38565. vertexData.indices.push(indices[index]);
  38566. }
  38567. }
  38568. var updatable = false;
  38569. var stopChecking = false;
  38570. var kind;
  38571. for (kind in this._vertexBuffers) {
  38572. // using slice() to make a copy of the array and not just reference it
  38573. var data = this.getVerticesData(kind);
  38574. if (data instanceof Float32Array) {
  38575. vertexData.set(new Float32Array(data), kind);
  38576. }
  38577. else {
  38578. vertexData.set(data.slice(0), kind);
  38579. }
  38580. if (!stopChecking) {
  38581. var vb = this.getVertexBuffer(kind);
  38582. if (vb) {
  38583. updatable = vb.isUpdatable();
  38584. stopChecking = !updatable;
  38585. }
  38586. }
  38587. }
  38588. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38589. geometry.delayLoadState = this.delayLoadState;
  38590. geometry.delayLoadingFile = this.delayLoadingFile;
  38591. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38592. for (kind in this._delayInfo) {
  38593. geometry._delayInfo = geometry._delayInfo || [];
  38594. geometry._delayInfo.push(kind);
  38595. }
  38596. // Bounding info
  38597. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38598. return geometry;
  38599. };
  38600. /**
  38601. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38602. * @return a JSON representation of the current geometry data (without the vertices data)
  38603. */
  38604. Geometry.prototype.serialize = function () {
  38605. var serializationObject = {};
  38606. serializationObject.id = this.id;
  38607. serializationObject.updatable = this._updatable;
  38608. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38609. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38610. }
  38611. return serializationObject;
  38612. };
  38613. Geometry.prototype.toNumberArray = function (origin) {
  38614. if (Array.isArray(origin)) {
  38615. return origin;
  38616. }
  38617. else {
  38618. return Array.prototype.slice.call(origin);
  38619. }
  38620. };
  38621. /**
  38622. * Serialize all vertices data into a JSON oject
  38623. * @returns a JSON representation of the current geometry data
  38624. */
  38625. Geometry.prototype.serializeVerticeData = function () {
  38626. var serializationObject = this.serialize();
  38627. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38628. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38629. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38630. serializationObject.positions._updatable = true;
  38631. }
  38632. }
  38633. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38634. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38635. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38636. serializationObject.normals._updatable = true;
  38637. }
  38638. }
  38639. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38640. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38641. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38642. serializationObject.tangets._updatable = true;
  38643. }
  38644. }
  38645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38646. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38647. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38648. serializationObject.uvs._updatable = true;
  38649. }
  38650. }
  38651. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38652. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38653. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38654. serializationObject.uv2s._updatable = true;
  38655. }
  38656. }
  38657. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38658. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38659. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38660. serializationObject.uv3s._updatable = true;
  38661. }
  38662. }
  38663. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38664. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38665. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38666. serializationObject.uv4s._updatable = true;
  38667. }
  38668. }
  38669. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38670. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38671. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38672. serializationObject.uv5s._updatable = true;
  38673. }
  38674. }
  38675. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38676. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38677. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38678. serializationObject.uv6s._updatable = true;
  38679. }
  38680. }
  38681. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38682. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38683. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38684. serializationObject.colors._updatable = true;
  38685. }
  38686. }
  38687. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38688. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38689. serializationObject.matricesIndices._isExpanded = true;
  38690. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38691. serializationObject.matricesIndices._updatable = true;
  38692. }
  38693. }
  38694. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38695. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38696. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38697. serializationObject.matricesWeights._updatable = true;
  38698. }
  38699. }
  38700. serializationObject.indices = this.toNumberArray(this.getIndices());
  38701. return serializationObject;
  38702. };
  38703. // Statics
  38704. /**
  38705. * Extracts a clone of a mesh geometry
  38706. * @param mesh defines the source mesh
  38707. * @param id defines the unique ID of the new geometry object
  38708. * @returns the new geometry object
  38709. */
  38710. Geometry.ExtractFromMesh = function (mesh, id) {
  38711. var geometry = mesh._geometry;
  38712. if (!geometry) {
  38713. return null;
  38714. }
  38715. return geometry.copy(id);
  38716. };
  38717. /**
  38718. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38719. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38720. * Be aware Math.random() could cause collisions, but:
  38721. * "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"
  38722. * @returns a string containing a new GUID
  38723. */
  38724. Geometry.RandomId = function () {
  38725. return BABYLON.Tools.RandomId();
  38726. };
  38727. /** @ignore */
  38728. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38729. var scene = mesh.getScene();
  38730. // Geometry
  38731. var geometryId = parsedGeometry.geometryId;
  38732. if (geometryId) {
  38733. var geometry = scene.getGeometryByID(geometryId);
  38734. if (geometry) {
  38735. geometry.applyToMesh(mesh);
  38736. }
  38737. }
  38738. else if (parsedGeometry instanceof ArrayBuffer) {
  38739. var binaryInfo = mesh._binaryInfo;
  38740. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  38741. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  38742. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  38743. }
  38744. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  38745. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  38746. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  38747. }
  38748. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  38749. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  38750. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  38751. }
  38752. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  38753. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  38754. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  38755. }
  38756. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  38757. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  38758. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  38759. }
  38760. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  38761. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  38762. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  38763. }
  38764. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  38765. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  38766. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  38767. }
  38768. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  38769. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  38770. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  38771. }
  38772. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  38773. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  38774. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  38775. }
  38776. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  38777. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  38778. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  38779. }
  38780. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  38781. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  38782. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  38783. }
  38784. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  38785. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  38786. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  38787. }
  38788. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  38789. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  38790. mesh.setIndices(indicesData, null);
  38791. }
  38792. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  38793. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  38794. mesh.subMeshes = [];
  38795. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  38796. var materialIndex = subMeshesData[(i * 5) + 0];
  38797. var verticesStart = subMeshesData[(i * 5) + 1];
  38798. var verticesCount = subMeshesData[(i * 5) + 2];
  38799. var indexStart = subMeshesData[(i * 5) + 3];
  38800. var indexCount = subMeshesData[(i * 5) + 4];
  38801. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  38802. }
  38803. }
  38804. }
  38805. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  38806. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  38807. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  38808. if (parsedGeometry.tangents) {
  38809. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  38810. }
  38811. if (parsedGeometry.uvs) {
  38812. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  38813. }
  38814. if (parsedGeometry.uvs2) {
  38815. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  38816. }
  38817. if (parsedGeometry.uvs3) {
  38818. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  38819. }
  38820. if (parsedGeometry.uvs4) {
  38821. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  38822. }
  38823. if (parsedGeometry.uvs5) {
  38824. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  38825. }
  38826. if (parsedGeometry.uvs6) {
  38827. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  38828. }
  38829. if (parsedGeometry.colors) {
  38830. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  38831. }
  38832. if (parsedGeometry.matricesIndices) {
  38833. if (!parsedGeometry.matricesIndices._isExpanded) {
  38834. var floatIndices = [];
  38835. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  38836. var matricesIndex = parsedGeometry.matricesIndices[i];
  38837. floatIndices.push(matricesIndex & 0x000000FF);
  38838. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38839. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38840. floatIndices.push(matricesIndex >> 24);
  38841. }
  38842. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  38843. }
  38844. else {
  38845. delete parsedGeometry.matricesIndices._isExpanded;
  38846. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  38847. }
  38848. }
  38849. if (parsedGeometry.matricesIndicesExtra) {
  38850. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  38851. var floatIndices = [];
  38852. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  38853. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  38854. floatIndices.push(matricesIndex & 0x000000FF);
  38855. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38856. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38857. floatIndices.push(matricesIndex >> 24);
  38858. }
  38859. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  38860. }
  38861. else {
  38862. delete parsedGeometry.matricesIndices._isExpanded;
  38863. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  38864. }
  38865. }
  38866. if (parsedGeometry.matricesWeights) {
  38867. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  38868. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  38869. }
  38870. if (parsedGeometry.matricesWeightsExtra) {
  38871. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  38872. }
  38873. mesh.setIndices(parsedGeometry.indices, null);
  38874. }
  38875. // SubMeshes
  38876. if (parsedGeometry.subMeshes) {
  38877. mesh.subMeshes = [];
  38878. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  38879. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  38880. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  38881. }
  38882. }
  38883. // Flat shading
  38884. if (mesh._shouldGenerateFlatShading) {
  38885. mesh.convertToFlatShadedMesh();
  38886. delete mesh._shouldGenerateFlatShading;
  38887. }
  38888. // Update
  38889. mesh.computeWorldMatrix(true);
  38890. // Octree
  38891. var sceneOctree = scene.selectionOctree;
  38892. if (sceneOctree !== undefined && sceneOctree !== null) {
  38893. sceneOctree.addMesh(mesh);
  38894. }
  38895. };
  38896. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  38897. var epsilon = 1e-3;
  38898. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  38899. return;
  38900. }
  38901. var noInfluenceBoneIndex = 0.0;
  38902. if (parsedGeometry.skeletonId > -1) {
  38903. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  38904. if (!skeleton) {
  38905. return;
  38906. }
  38907. noInfluenceBoneIndex = skeleton.bones.length;
  38908. }
  38909. else {
  38910. return;
  38911. }
  38912. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  38913. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38914. var matricesWeights = parsedGeometry.matricesWeights;
  38915. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  38916. var influencers = parsedGeometry.numBoneInfluencer;
  38917. var size = matricesWeights.length;
  38918. for (var i = 0; i < size; i += 4) {
  38919. var weight = 0.0;
  38920. var firstZeroWeight = -1;
  38921. for (var j = 0; j < 4; j++) {
  38922. var w = matricesWeights[i + j];
  38923. weight += w;
  38924. if (w < epsilon && firstZeroWeight < 0) {
  38925. firstZeroWeight = j;
  38926. }
  38927. }
  38928. if (matricesWeightsExtra) {
  38929. for (var j = 0; j < 4; j++) {
  38930. var w = matricesWeightsExtra[i + j];
  38931. weight += w;
  38932. if (w < epsilon && firstZeroWeight < 0) {
  38933. firstZeroWeight = j + 4;
  38934. }
  38935. }
  38936. }
  38937. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  38938. firstZeroWeight = influencers - 1;
  38939. }
  38940. if (weight > epsilon) {
  38941. var mweight = 1.0 / weight;
  38942. for (var j = 0; j < 4; j++) {
  38943. matricesWeights[i + j] *= mweight;
  38944. }
  38945. if (matricesWeightsExtra) {
  38946. for (var j = 0; j < 4; j++) {
  38947. matricesWeightsExtra[i + j] *= mweight;
  38948. }
  38949. }
  38950. }
  38951. else {
  38952. if (firstZeroWeight >= 4) {
  38953. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  38954. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  38955. }
  38956. else {
  38957. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  38958. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  38959. }
  38960. }
  38961. }
  38962. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  38963. if (parsedGeometry.matricesWeightsExtra) {
  38964. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  38965. }
  38966. };
  38967. /**
  38968. * Create a new geometry from persisted data (Using .babylon file format)
  38969. * @param parsedVertexData defines the persisted data
  38970. * @param scene defines the hosting scene
  38971. * @param rootUrl defines the root url to use to load assets (like delayed data)
  38972. * @returns the new geometry object
  38973. */
  38974. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  38975. if (scene.getGeometryByID(parsedVertexData.id)) {
  38976. return null; // null since geometry could be something else than a box...
  38977. }
  38978. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  38979. if (BABYLON.Tags) {
  38980. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  38981. }
  38982. if (parsedVertexData.delayLoadingFile) {
  38983. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38984. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  38985. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  38986. geometry._delayInfo = [];
  38987. if (parsedVertexData.hasUVs) {
  38988. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  38989. }
  38990. if (parsedVertexData.hasUVs2) {
  38991. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  38992. }
  38993. if (parsedVertexData.hasUVs3) {
  38994. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  38995. }
  38996. if (parsedVertexData.hasUVs4) {
  38997. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  38998. }
  38999. if (parsedVertexData.hasUVs5) {
  39000. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39001. }
  39002. if (parsedVertexData.hasUVs6) {
  39003. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39004. }
  39005. if (parsedVertexData.hasColors) {
  39006. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39007. }
  39008. if (parsedVertexData.hasMatricesIndices) {
  39009. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39010. }
  39011. if (parsedVertexData.hasMatricesWeights) {
  39012. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39013. }
  39014. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39015. }
  39016. else {
  39017. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39018. }
  39019. scene.pushGeometry(geometry, true);
  39020. return geometry;
  39021. };
  39022. return Geometry;
  39023. }());
  39024. BABYLON.Geometry = Geometry;
  39025. // Primitives
  39026. /// Abstract class
  39027. /**
  39028. * Abstract class used to provide common services for all typed geometries
  39029. */
  39030. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39031. __extends(_PrimitiveGeometry, _super);
  39032. /**
  39033. * Creates a new typed geometry
  39034. * @param id defines the unique ID of the geometry
  39035. * @param scene defines the hosting scene
  39036. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39037. * @param mesh defines the hosting mesh (can be null)
  39038. */
  39039. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39040. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39041. if (mesh === void 0) { mesh = null; }
  39042. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39043. _this._canBeRegenerated = _canBeRegenerated;
  39044. _this._beingRegenerated = true;
  39045. _this.regenerate();
  39046. _this._beingRegenerated = false;
  39047. return _this;
  39048. }
  39049. /**
  39050. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39051. * @returns true if the geometry can be regenerated
  39052. */
  39053. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39054. return this._canBeRegenerated;
  39055. };
  39056. /**
  39057. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39058. */
  39059. _PrimitiveGeometry.prototype.regenerate = function () {
  39060. if (!this._canBeRegenerated) {
  39061. return;
  39062. }
  39063. this._beingRegenerated = true;
  39064. this.setAllVerticesData(this._regenerateVertexData(), false);
  39065. this._beingRegenerated = false;
  39066. };
  39067. /**
  39068. * Clone the geometry
  39069. * @param id defines the unique ID of the new geometry
  39070. * @returns the new geometry
  39071. */
  39072. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39073. return _super.prototype.copy.call(this, id);
  39074. };
  39075. // overrides
  39076. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39077. if (!this._beingRegenerated) {
  39078. return;
  39079. }
  39080. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39081. };
  39082. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39083. if (!this._beingRegenerated) {
  39084. return;
  39085. }
  39086. _super.prototype.setVerticesData.call(this, kind, data, false);
  39087. };
  39088. // to override
  39089. /** @ignore */
  39090. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39091. throw new Error("Abstract method");
  39092. };
  39093. _PrimitiveGeometry.prototype.copy = function (id) {
  39094. throw new Error("Must be overriden in sub-classes.");
  39095. };
  39096. _PrimitiveGeometry.prototype.serialize = function () {
  39097. var serializationObject = _super.prototype.serialize.call(this);
  39098. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39099. return serializationObject;
  39100. };
  39101. return _PrimitiveGeometry;
  39102. }(Geometry));
  39103. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39104. /**
  39105. * Creates a ribbon geometry
  39106. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39107. */
  39108. var RibbonGeometry = /** @class */ (function (_super) {
  39109. __extends(RibbonGeometry, _super);
  39110. /**
  39111. * Creates a ribbon geometry
  39112. * @param id defines the unique ID of the geometry
  39113. * @param scene defines the hosting scene
  39114. * @param pathArray defines the array of paths to use
  39115. * @param closeArray defines if the last path and the first path must be joined
  39116. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39117. * @param offset defines the offset between points
  39118. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39119. * @param mesh defines the hosting mesh (can be null)
  39120. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39121. */
  39122. function RibbonGeometry(id, scene,
  39123. /**
  39124. * Defines the array of paths to use
  39125. */
  39126. pathArray,
  39127. /**
  39128. * Defines if the last and first points of each path in your pathArray must be joined
  39129. */
  39130. closeArray,
  39131. /**
  39132. * Defines if the last and first points of each path in your pathArray must be joined
  39133. */
  39134. closePath,
  39135. /**
  39136. * Defines the offset between points
  39137. */
  39138. offset, canBeRegenerated, mesh,
  39139. /**
  39140. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39141. */
  39142. side) {
  39143. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39144. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39145. _this.pathArray = pathArray;
  39146. _this.closeArray = closeArray;
  39147. _this.closePath = closePath;
  39148. _this.offset = offset;
  39149. _this.side = side;
  39150. return _this;
  39151. }
  39152. /** @ignore */
  39153. RibbonGeometry.prototype._regenerateVertexData = function () {
  39154. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39155. };
  39156. RibbonGeometry.prototype.copy = function (id) {
  39157. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39158. };
  39159. return RibbonGeometry;
  39160. }(_PrimitiveGeometry));
  39161. BABYLON.RibbonGeometry = RibbonGeometry;
  39162. /**
  39163. * Creates a box geometry
  39164. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39165. */
  39166. var BoxGeometry = /** @class */ (function (_super) {
  39167. __extends(BoxGeometry, _super);
  39168. /**
  39169. * Creates a box geometry
  39170. * @param id defines the unique ID of the geometry
  39171. * @param scene defines the hosting scene
  39172. * @param size defines the zise of the box (width, height and depth are the same)
  39173. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39174. * @param mesh defines the hosting mesh (can be null)
  39175. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39176. */
  39177. function BoxGeometry(id, scene,
  39178. /**
  39179. * Defines the zise of the box (width, height and depth are the same)
  39180. */
  39181. size, canBeRegenerated, mesh,
  39182. /**
  39183. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39184. */
  39185. side) {
  39186. if (mesh === void 0) { mesh = null; }
  39187. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39188. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39189. _this.size = size;
  39190. _this.side = side;
  39191. return _this;
  39192. }
  39193. BoxGeometry.prototype._regenerateVertexData = function () {
  39194. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39195. };
  39196. BoxGeometry.prototype.copy = function (id) {
  39197. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39198. };
  39199. BoxGeometry.prototype.serialize = function () {
  39200. var serializationObject = _super.prototype.serialize.call(this);
  39201. serializationObject.size = this.size;
  39202. return serializationObject;
  39203. };
  39204. BoxGeometry.Parse = function (parsedBox, scene) {
  39205. if (scene.getGeometryByID(parsedBox.id)) {
  39206. return null; // null since geometry could be something else than a box...
  39207. }
  39208. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39209. if (BABYLON.Tags) {
  39210. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39211. }
  39212. scene.pushGeometry(box, true);
  39213. return box;
  39214. };
  39215. return BoxGeometry;
  39216. }(_PrimitiveGeometry));
  39217. BABYLON.BoxGeometry = BoxGeometry;
  39218. /**
  39219. * Creates a sphere geometry
  39220. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39221. */
  39222. var SphereGeometry = /** @class */ (function (_super) {
  39223. __extends(SphereGeometry, _super);
  39224. /**
  39225. * Create a new sphere geometry
  39226. * @param id defines the unique ID of the geometry
  39227. * @param scene defines the hosting scene
  39228. * @param segments defines the number of segments to use to create the sphere
  39229. * @param diameter defines the diameter of the sphere
  39230. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39231. * @param mesh defines the hosting mesh (can be null)
  39232. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39233. */
  39234. function SphereGeometry(id, scene,
  39235. /**
  39236. * Defines the number of segments to use to create the sphere
  39237. */
  39238. segments,
  39239. /**
  39240. * Defines the diameter of the sphere
  39241. */
  39242. diameter, canBeRegenerated, mesh,
  39243. /**
  39244. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39245. */
  39246. side) {
  39247. if (mesh === void 0) { mesh = null; }
  39248. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39249. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39250. _this.segments = segments;
  39251. _this.diameter = diameter;
  39252. _this.side = side;
  39253. return _this;
  39254. }
  39255. SphereGeometry.prototype._regenerateVertexData = function () {
  39256. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39257. };
  39258. SphereGeometry.prototype.copy = function (id) {
  39259. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39260. };
  39261. SphereGeometry.prototype.serialize = function () {
  39262. var serializationObject = _super.prototype.serialize.call(this);
  39263. serializationObject.segments = this.segments;
  39264. serializationObject.diameter = this.diameter;
  39265. return serializationObject;
  39266. };
  39267. SphereGeometry.Parse = function (parsedSphere, scene) {
  39268. if (scene.getGeometryByID(parsedSphere.id)) {
  39269. return null; // null since geometry could be something else than a sphere...
  39270. }
  39271. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39272. if (BABYLON.Tags) {
  39273. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39274. }
  39275. scene.pushGeometry(sphere, true);
  39276. return sphere;
  39277. };
  39278. return SphereGeometry;
  39279. }(_PrimitiveGeometry));
  39280. BABYLON.SphereGeometry = SphereGeometry;
  39281. /**
  39282. * Creates a disc geometry
  39283. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39284. */
  39285. var DiscGeometry = /** @class */ (function (_super) {
  39286. __extends(DiscGeometry, _super);
  39287. /**
  39288. * Creates a new disc geometry
  39289. * @param id defines the unique ID of the geometry
  39290. * @param scene defines the hosting scene
  39291. * @param radius defines the radius of the disc
  39292. * @param tessellation defines the tesselation factor to apply to the disc
  39293. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39294. * @param mesh defines the hosting mesh (can be null)
  39295. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39296. */
  39297. function DiscGeometry(id, scene,
  39298. /**
  39299. * Defines the radius of the disc
  39300. */
  39301. radius,
  39302. /**
  39303. * Defines the tesselation factor to apply to the disc
  39304. */
  39305. tessellation, canBeRegenerated, mesh,
  39306. /**
  39307. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39308. */
  39309. side) {
  39310. if (mesh === void 0) { mesh = null; }
  39311. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39312. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39313. _this.radius = radius;
  39314. _this.tessellation = tessellation;
  39315. _this.side = side;
  39316. return _this;
  39317. }
  39318. DiscGeometry.prototype._regenerateVertexData = function () {
  39319. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39320. };
  39321. DiscGeometry.prototype.copy = function (id) {
  39322. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39323. };
  39324. return DiscGeometry;
  39325. }(_PrimitiveGeometry));
  39326. BABYLON.DiscGeometry = DiscGeometry;
  39327. /**
  39328. * Creates a new cylinder geometry
  39329. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39330. */
  39331. var CylinderGeometry = /** @class */ (function (_super) {
  39332. __extends(CylinderGeometry, _super);
  39333. /**
  39334. * Creates a new cylinder geometry
  39335. * @param id defines the unique ID of the geometry
  39336. * @param scene defines the hosting scene
  39337. * @param height defines the height of the cylinder
  39338. * @param diameterTop defines the diameter of the cylinder's top cap
  39339. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39340. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39341. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39342. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39343. * @param mesh defines the hosting mesh (can be null)
  39344. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39345. */
  39346. function CylinderGeometry(id, scene,
  39347. /**
  39348. * Defines the height of the cylinder
  39349. */
  39350. height,
  39351. /**
  39352. * Defines the diameter of the cylinder's top cap
  39353. */
  39354. diameterTop,
  39355. /**
  39356. * Defines the diameter of the cylinder's bottom cap
  39357. */
  39358. diameterBottom,
  39359. /**
  39360. * Defines the tessellation factor to apply to the cylinder
  39361. */
  39362. tessellation,
  39363. /**
  39364. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39365. */
  39366. subdivisions, canBeRegenerated, mesh,
  39367. /**
  39368. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39369. */
  39370. side) {
  39371. if (subdivisions === void 0) { subdivisions = 1; }
  39372. if (mesh === void 0) { mesh = null; }
  39373. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39374. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39375. _this.height = height;
  39376. _this.diameterTop = diameterTop;
  39377. _this.diameterBottom = diameterBottom;
  39378. _this.tessellation = tessellation;
  39379. _this.subdivisions = subdivisions;
  39380. _this.side = side;
  39381. return _this;
  39382. }
  39383. CylinderGeometry.prototype._regenerateVertexData = function () {
  39384. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39385. };
  39386. CylinderGeometry.prototype.copy = function (id) {
  39387. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39388. };
  39389. CylinderGeometry.prototype.serialize = function () {
  39390. var serializationObject = _super.prototype.serialize.call(this);
  39391. serializationObject.height = this.height;
  39392. serializationObject.diameterTop = this.diameterTop;
  39393. serializationObject.diameterBottom = this.diameterBottom;
  39394. serializationObject.tessellation = this.tessellation;
  39395. return serializationObject;
  39396. };
  39397. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39398. if (scene.getGeometryByID(parsedCylinder.id)) {
  39399. return null; // null since geometry could be something else than a cylinder...
  39400. }
  39401. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39402. if (BABYLON.Tags) {
  39403. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39404. }
  39405. scene.pushGeometry(cylinder, true);
  39406. return cylinder;
  39407. };
  39408. return CylinderGeometry;
  39409. }(_PrimitiveGeometry));
  39410. BABYLON.CylinderGeometry = CylinderGeometry;
  39411. /**
  39412. * Creates a new torus geometry
  39413. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39414. */
  39415. var TorusGeometry = /** @class */ (function (_super) {
  39416. __extends(TorusGeometry, _super);
  39417. /**
  39418. * Creates a new torus geometry
  39419. * @param id defines the unique ID of the geometry
  39420. * @param scene defines the hosting scene
  39421. * @param diameter defines the diameter of the torus
  39422. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39423. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39424. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39425. * @param mesh defines the hosting mesh (can be null)
  39426. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39427. */
  39428. function TorusGeometry(id, scene,
  39429. /**
  39430. * Defines the diameter of the torus
  39431. */
  39432. diameter,
  39433. /**
  39434. * Defines the thickness of the torus (ie. internal diameter)
  39435. */
  39436. thickness,
  39437. /**
  39438. * Defines the tesselation factor to apply to the torus
  39439. */
  39440. tessellation, canBeRegenerated, mesh,
  39441. /**
  39442. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39443. */
  39444. side) {
  39445. if (mesh === void 0) { mesh = null; }
  39446. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39447. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39448. _this.diameter = diameter;
  39449. _this.thickness = thickness;
  39450. _this.tessellation = tessellation;
  39451. _this.side = side;
  39452. return _this;
  39453. }
  39454. TorusGeometry.prototype._regenerateVertexData = function () {
  39455. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39456. };
  39457. TorusGeometry.prototype.copy = function (id) {
  39458. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39459. };
  39460. TorusGeometry.prototype.serialize = function () {
  39461. var serializationObject = _super.prototype.serialize.call(this);
  39462. serializationObject.diameter = this.diameter;
  39463. serializationObject.thickness = this.thickness;
  39464. serializationObject.tessellation = this.tessellation;
  39465. return serializationObject;
  39466. };
  39467. TorusGeometry.Parse = function (parsedTorus, scene) {
  39468. if (scene.getGeometryByID(parsedTorus.id)) {
  39469. return null; // null since geometry could be something else than a torus...
  39470. }
  39471. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39472. if (BABYLON.Tags) {
  39473. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39474. }
  39475. scene.pushGeometry(torus, true);
  39476. return torus;
  39477. };
  39478. return TorusGeometry;
  39479. }(_PrimitiveGeometry));
  39480. BABYLON.TorusGeometry = TorusGeometry;
  39481. /**
  39482. * Creates a new ground geometry
  39483. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39484. */
  39485. var GroundGeometry = /** @class */ (function (_super) {
  39486. __extends(GroundGeometry, _super);
  39487. /**
  39488. * Creates a new ground geometry
  39489. * @param id defines the unique ID of the geometry
  39490. * @param scene defines the hosting scene
  39491. * @param width defines the width of the ground
  39492. * @param height defines the height of the ground
  39493. * @param subdivisions defines the subdivisions to apply to the ground
  39494. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39495. * @param mesh defines the hosting mesh (can be null)
  39496. */
  39497. function GroundGeometry(id, scene,
  39498. /**
  39499. * Defines the width of the ground
  39500. */
  39501. width,
  39502. /**
  39503. * Defines the height of the ground
  39504. */
  39505. height,
  39506. /**
  39507. * Defines the subdivisions to apply to the ground
  39508. */
  39509. subdivisions, canBeRegenerated, mesh) {
  39510. if (mesh === void 0) { mesh = null; }
  39511. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39512. _this.width = width;
  39513. _this.height = height;
  39514. _this.subdivisions = subdivisions;
  39515. return _this;
  39516. }
  39517. GroundGeometry.prototype._regenerateVertexData = function () {
  39518. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39519. };
  39520. GroundGeometry.prototype.copy = function (id) {
  39521. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39522. };
  39523. GroundGeometry.prototype.serialize = function () {
  39524. var serializationObject = _super.prototype.serialize.call(this);
  39525. serializationObject.width = this.width;
  39526. serializationObject.height = this.height;
  39527. serializationObject.subdivisions = this.subdivisions;
  39528. return serializationObject;
  39529. };
  39530. GroundGeometry.Parse = function (parsedGround, scene) {
  39531. if (scene.getGeometryByID(parsedGround.id)) {
  39532. return null; // null since geometry could be something else than a ground...
  39533. }
  39534. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39535. if (BABYLON.Tags) {
  39536. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39537. }
  39538. scene.pushGeometry(ground, true);
  39539. return ground;
  39540. };
  39541. return GroundGeometry;
  39542. }(_PrimitiveGeometry));
  39543. BABYLON.GroundGeometry = GroundGeometry;
  39544. /**
  39545. * Creates a tiled ground geometry
  39546. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39547. */
  39548. var TiledGroundGeometry = /** @class */ (function (_super) {
  39549. __extends(TiledGroundGeometry, _super);
  39550. /**
  39551. * Creates a tiled ground geometry
  39552. * @param id defines the unique ID of the geometry
  39553. * @param scene defines the hosting scene
  39554. * @param xmin defines the minimum value on X axis
  39555. * @param zmin defines the minimum value on Z axis
  39556. * @param xmax defines the maximum value on X axis
  39557. * @param zmax defines the maximum value on Z axis
  39558. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39559. * @param precision defines the precision to use when computing the tiles
  39560. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39561. * @param mesh defines the hosting mesh (can be null)
  39562. */
  39563. function TiledGroundGeometry(id, scene,
  39564. /**
  39565. * Defines the minimum value on X axis
  39566. */
  39567. xmin,
  39568. /**
  39569. * Defines the minimum value on Z axis
  39570. */
  39571. zmin,
  39572. /**
  39573. * Defines the maximum value on X axis
  39574. */
  39575. xmax,
  39576. /**
  39577. * Defines the maximum value on Z axis
  39578. */
  39579. zmax,
  39580. /**
  39581. * Defines the subdivisions to apply to the ground
  39582. */
  39583. subdivisions,
  39584. /**
  39585. * Defines the precision to use when computing the tiles
  39586. */
  39587. precision, canBeRegenerated, mesh) {
  39588. if (mesh === void 0) { mesh = null; }
  39589. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39590. _this.xmin = xmin;
  39591. _this.zmin = zmin;
  39592. _this.xmax = xmax;
  39593. _this.zmax = zmax;
  39594. _this.subdivisions = subdivisions;
  39595. _this.precision = precision;
  39596. return _this;
  39597. }
  39598. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39599. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39600. };
  39601. TiledGroundGeometry.prototype.copy = function (id) {
  39602. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39603. };
  39604. return TiledGroundGeometry;
  39605. }(_PrimitiveGeometry));
  39606. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39607. /**
  39608. * Creates a plane geometry
  39609. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39610. */
  39611. var PlaneGeometry = /** @class */ (function (_super) {
  39612. __extends(PlaneGeometry, _super);
  39613. /**
  39614. * Creates a plane geometry
  39615. * @param id defines the unique ID of the geometry
  39616. * @param scene defines the hosting scene
  39617. * @param size defines the size of the plane (width === height)
  39618. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39619. * @param mesh defines the hosting mesh (can be null)
  39620. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39621. */
  39622. function PlaneGeometry(id, scene,
  39623. /**
  39624. * Defines the size of the plane (width === height)
  39625. */
  39626. size, canBeRegenerated, mesh,
  39627. /**
  39628. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39629. */
  39630. side) {
  39631. if (mesh === void 0) { mesh = null; }
  39632. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39633. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39634. _this.size = size;
  39635. _this.side = side;
  39636. return _this;
  39637. }
  39638. PlaneGeometry.prototype._regenerateVertexData = function () {
  39639. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39640. };
  39641. PlaneGeometry.prototype.copy = function (id) {
  39642. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39643. };
  39644. PlaneGeometry.prototype.serialize = function () {
  39645. var serializationObject = _super.prototype.serialize.call(this);
  39646. serializationObject.size = this.size;
  39647. return serializationObject;
  39648. };
  39649. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39650. if (scene.getGeometryByID(parsedPlane.id)) {
  39651. return null; // null since geometry could be something else than a ground...
  39652. }
  39653. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39654. if (BABYLON.Tags) {
  39655. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39656. }
  39657. scene.pushGeometry(plane, true);
  39658. return plane;
  39659. };
  39660. return PlaneGeometry;
  39661. }(_PrimitiveGeometry));
  39662. BABYLON.PlaneGeometry = PlaneGeometry;
  39663. /**
  39664. * Creates a torus knot geometry
  39665. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39666. */
  39667. var TorusKnotGeometry = /** @class */ (function (_super) {
  39668. __extends(TorusKnotGeometry, _super);
  39669. /**
  39670. * Creates a torus knot geometry
  39671. * @param id defines the unique ID of the geometry
  39672. * @param scene defines the hosting scene
  39673. * @param radius defines the radius of the torus knot
  39674. * @param tube defines the thickness of the torus knot tube
  39675. * @param radialSegments defines the number of radial segments
  39676. * @param tubularSegments defines the number of tubular segments
  39677. * @param p defines the first number of windings
  39678. * @param q defines the second number of windings
  39679. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39680. * @param mesh defines the hosting mesh (can be null)
  39681. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39682. */
  39683. function TorusKnotGeometry(id, scene,
  39684. /**
  39685. * Defines the radius of the torus knot
  39686. */
  39687. radius,
  39688. /**
  39689. * Defines the thickness of the torus knot tube
  39690. */
  39691. tube,
  39692. /**
  39693. * Defines the number of radial segments
  39694. */
  39695. radialSegments,
  39696. /**
  39697. * Defines the number of tubular segments
  39698. */
  39699. tubularSegments,
  39700. /**
  39701. * Defines the first number of windings
  39702. */
  39703. p,
  39704. /**
  39705. * Defines the second number of windings
  39706. */
  39707. q, canBeRegenerated, mesh,
  39708. /**
  39709. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39710. */
  39711. side) {
  39712. if (mesh === void 0) { mesh = null; }
  39713. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39714. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39715. _this.radius = radius;
  39716. _this.tube = tube;
  39717. _this.radialSegments = radialSegments;
  39718. _this.tubularSegments = tubularSegments;
  39719. _this.p = p;
  39720. _this.q = q;
  39721. _this.side = side;
  39722. return _this;
  39723. }
  39724. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39725. 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 });
  39726. };
  39727. TorusKnotGeometry.prototype.copy = function (id) {
  39728. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39729. };
  39730. TorusKnotGeometry.prototype.serialize = function () {
  39731. var serializationObject = _super.prototype.serialize.call(this);
  39732. serializationObject.radius = this.radius;
  39733. serializationObject.tube = this.tube;
  39734. serializationObject.radialSegments = this.radialSegments;
  39735. serializationObject.tubularSegments = this.tubularSegments;
  39736. serializationObject.p = this.p;
  39737. serializationObject.q = this.q;
  39738. return serializationObject;
  39739. };
  39740. ;
  39741. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  39742. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  39743. return null; // null since geometry could be something else than a ground...
  39744. }
  39745. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  39746. if (BABYLON.Tags) {
  39747. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  39748. }
  39749. scene.pushGeometry(torusKnot, true);
  39750. return torusKnot;
  39751. };
  39752. return TorusKnotGeometry;
  39753. }(_PrimitiveGeometry));
  39754. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  39755. //}
  39756. })(BABYLON || (BABYLON = {}));
  39757. //# sourceMappingURL=babylon.geometry.js.map
  39758. "use strict";
  39759. var BABYLON;
  39760. (function (BABYLON) {
  39761. /**
  39762. * PostProcessManager is used to manage one or more post processes or post process pipelines
  39763. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  39764. */
  39765. var PostProcessManager = /** @class */ (function () {
  39766. /**
  39767. * Creates a new instance PostProcess
  39768. * @param scene The scene that the post process is associated with.
  39769. */
  39770. function PostProcessManager(scene) {
  39771. this._vertexBuffers = {};
  39772. this._scene = scene;
  39773. }
  39774. PostProcessManager.prototype._prepareBuffers = function () {
  39775. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  39776. return;
  39777. }
  39778. // VBO
  39779. var vertices = [];
  39780. vertices.push(1, 1);
  39781. vertices.push(-1, 1);
  39782. vertices.push(-1, -1);
  39783. vertices.push(1, -1);
  39784. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39785. this._buildIndexBuffer();
  39786. };
  39787. PostProcessManager.prototype._buildIndexBuffer = function () {
  39788. // Indices
  39789. var indices = [];
  39790. indices.push(0);
  39791. indices.push(1);
  39792. indices.push(2);
  39793. indices.push(0);
  39794. indices.push(2);
  39795. indices.push(3);
  39796. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  39797. };
  39798. /**
  39799. * Rebuilds the vertex buffers of the manager.
  39800. */
  39801. PostProcessManager.prototype._rebuild = function () {
  39802. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39803. if (!vb) {
  39804. return;
  39805. }
  39806. vb._rebuild();
  39807. this._buildIndexBuffer();
  39808. };
  39809. // Methods
  39810. /**
  39811. * Prepares a frame to be run through a post process.
  39812. * @param sourceTexture The input texture to the post procesess. (default: null)
  39813. * @param postProcesses An array of post processes to be run. (default: null)
  39814. * @returns True if the post processes were able to be run.
  39815. */
  39816. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  39817. if (sourceTexture === void 0) { sourceTexture = null; }
  39818. if (postProcesses === void 0) { postProcesses = null; }
  39819. var camera = this._scene.activeCamera;
  39820. if (!camera) {
  39821. return false;
  39822. }
  39823. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39824. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39825. return false;
  39826. }
  39827. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  39828. return true;
  39829. };
  39830. /**
  39831. * Manually render a set of post processes to a texture.
  39832. * @param postProcesses An array of post processes to be run.
  39833. * @param targetTexture The target texture to render to.
  39834. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  39835. */
  39836. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  39837. if (targetTexture === void 0) { targetTexture = null; }
  39838. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39839. var engine = this._scene.getEngine();
  39840. for (var index = 0; index < postProcesses.length; index++) {
  39841. if (index < postProcesses.length - 1) {
  39842. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  39843. }
  39844. else {
  39845. if (targetTexture) {
  39846. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  39847. }
  39848. else {
  39849. engine.restoreDefaultFramebuffer();
  39850. }
  39851. }
  39852. var pp = postProcesses[index];
  39853. var effect = pp.apply();
  39854. if (effect) {
  39855. pp.onBeforeRenderObservable.notifyObservers(effect);
  39856. // VBOs
  39857. this._prepareBuffers();
  39858. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39859. // Draw order
  39860. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39861. pp.onAfterRenderObservable.notifyObservers(effect);
  39862. }
  39863. }
  39864. // Restore depth buffer
  39865. engine.setDepthBuffer(true);
  39866. engine.setDepthWrite(true);
  39867. };
  39868. /**
  39869. * Finalize the result of the output of the postprocesses.
  39870. * @param doNotPresent If true the result will not be displayed to the screen.
  39871. * @param targetTexture The target texture to render to.
  39872. * @param faceIndex The index of the face to bind the target texture to.
  39873. * @param postProcesses The array of post processes to render.
  39874. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  39875. */
  39876. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  39877. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39878. var camera = this._scene.activeCamera;
  39879. if (!camera) {
  39880. return;
  39881. }
  39882. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39883. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39884. return;
  39885. }
  39886. var engine = this._scene.getEngine();
  39887. for (var index = 0, len = postProcesses.length; index < len; index++) {
  39888. var pp = postProcesses[index];
  39889. if (index < len - 1) {
  39890. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  39891. }
  39892. else {
  39893. if (targetTexture) {
  39894. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  39895. pp._outputTexture = targetTexture;
  39896. }
  39897. else {
  39898. engine.restoreDefaultFramebuffer();
  39899. pp._outputTexture = null;
  39900. }
  39901. }
  39902. if (doNotPresent) {
  39903. break;
  39904. }
  39905. var effect = pp.apply();
  39906. if (effect) {
  39907. pp.onBeforeRenderObservable.notifyObservers(effect);
  39908. // VBOs
  39909. this._prepareBuffers();
  39910. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39911. // Draw order
  39912. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39913. pp.onAfterRenderObservable.notifyObservers(effect);
  39914. }
  39915. }
  39916. // Restore states
  39917. engine.setDepthBuffer(true);
  39918. engine.setDepthWrite(true);
  39919. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39920. };
  39921. /**
  39922. * Disposes of the post process manager.
  39923. */
  39924. PostProcessManager.prototype.dispose = function () {
  39925. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39926. if (buffer) {
  39927. buffer.dispose();
  39928. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39929. }
  39930. if (this._indexBuffer) {
  39931. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39932. this._indexBuffer = null;
  39933. }
  39934. };
  39935. return PostProcessManager;
  39936. }());
  39937. BABYLON.PostProcessManager = PostProcessManager;
  39938. })(BABYLON || (BABYLON = {}));
  39939. //# sourceMappingURL=babylon.postProcessManager.js.map
  39940. "use strict";
  39941. var BABYLON;
  39942. (function (BABYLON) {
  39943. /**
  39944. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  39945. */
  39946. var PerformanceMonitor = /** @class */ (function () {
  39947. /**
  39948. * constructor
  39949. * @param frameSampleSize The number of samples required to saturate the sliding window
  39950. */
  39951. function PerformanceMonitor(frameSampleSize) {
  39952. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  39953. this._enabled = true;
  39954. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  39955. }
  39956. /**
  39957. * Samples current frame
  39958. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  39959. */
  39960. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  39961. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  39962. if (!this._enabled)
  39963. return;
  39964. if (this._lastFrameTimeMs != null) {
  39965. var dt = timeMs - this._lastFrameTimeMs;
  39966. this._rollingFrameTime.add(dt);
  39967. }
  39968. this._lastFrameTimeMs = timeMs;
  39969. };
  39970. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  39971. /**
  39972. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39973. * @return Average frame time in milliseconds
  39974. */
  39975. get: function () {
  39976. return this._rollingFrameTime.average;
  39977. },
  39978. enumerable: true,
  39979. configurable: true
  39980. });
  39981. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  39982. /**
  39983. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39984. * @return Frame time variance in milliseconds squared
  39985. */
  39986. get: function () {
  39987. return this._rollingFrameTime.variance;
  39988. },
  39989. enumerable: true,
  39990. configurable: true
  39991. });
  39992. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  39993. /**
  39994. * Returns the frame time of the most recent frame
  39995. * @return Frame time in milliseconds
  39996. */
  39997. get: function () {
  39998. return this._rollingFrameTime.history(0);
  39999. },
  40000. enumerable: true,
  40001. configurable: true
  40002. });
  40003. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40004. /**
  40005. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40006. * @return Framerate in frames per second
  40007. */
  40008. get: function () {
  40009. return 1000.0 / this._rollingFrameTime.average;
  40010. },
  40011. enumerable: true,
  40012. configurable: true
  40013. });
  40014. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40015. /**
  40016. * Returns the average framerate in frames per second using the most recent frame time
  40017. * @return Framerate in frames per second
  40018. */
  40019. get: function () {
  40020. var history = this._rollingFrameTime.history(0);
  40021. if (history === 0) {
  40022. return 0;
  40023. }
  40024. return 1000.0 / history;
  40025. },
  40026. enumerable: true,
  40027. configurable: true
  40028. });
  40029. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40030. /**
  40031. * Returns true if enough samples have been taken to completely fill the sliding window
  40032. * @return true if saturated
  40033. */
  40034. get: function () {
  40035. return this._rollingFrameTime.isSaturated();
  40036. },
  40037. enumerable: true,
  40038. configurable: true
  40039. });
  40040. /**
  40041. * Enables contributions to the sliding window sample set
  40042. */
  40043. PerformanceMonitor.prototype.enable = function () {
  40044. this._enabled = true;
  40045. };
  40046. /**
  40047. * Disables contributions to the sliding window sample set
  40048. * Samples will not be interpolated over the disabled period
  40049. */
  40050. PerformanceMonitor.prototype.disable = function () {
  40051. this._enabled = false;
  40052. //clear last sample to avoid interpolating over the disabled period when next enabled
  40053. this._lastFrameTimeMs = null;
  40054. };
  40055. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40056. /**
  40057. * Returns true if sampling is enabled
  40058. * @return true if enabled
  40059. */
  40060. get: function () {
  40061. return this._enabled;
  40062. },
  40063. enumerable: true,
  40064. configurable: true
  40065. });
  40066. /**
  40067. * Resets performance monitor
  40068. */
  40069. PerformanceMonitor.prototype.reset = function () {
  40070. //clear last sample to avoid interpolating over the disabled period when next enabled
  40071. this._lastFrameTimeMs = null;
  40072. //wipe record
  40073. this._rollingFrameTime.reset();
  40074. };
  40075. return PerformanceMonitor;
  40076. }());
  40077. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40078. /**
  40079. * RollingAverage
  40080. *
  40081. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40082. */
  40083. var RollingAverage = /** @class */ (function () {
  40084. /**
  40085. * constructor
  40086. * @param length The number of samples required to saturate the sliding window
  40087. */
  40088. function RollingAverage(length) {
  40089. this._samples = new Array(length);
  40090. this.reset();
  40091. }
  40092. /**
  40093. * Adds a sample to the sample set
  40094. * @param v The sample value
  40095. */
  40096. RollingAverage.prototype.add = function (v) {
  40097. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40098. var delta;
  40099. //we need to check if we've already wrapped round
  40100. if (this.isSaturated()) {
  40101. //remove bottom of stack from mean
  40102. var bottomValue = this._samples[this._pos];
  40103. delta = bottomValue - this.average;
  40104. this.average -= delta / (this._sampleCount - 1);
  40105. this._m2 -= delta * (bottomValue - this.average);
  40106. }
  40107. else {
  40108. this._sampleCount++;
  40109. }
  40110. //add new value to mean
  40111. delta = v - this.average;
  40112. this.average += delta / (this._sampleCount);
  40113. this._m2 += delta * (v - this.average);
  40114. //set the new variance
  40115. this.variance = this._m2 / (this._sampleCount - 1);
  40116. this._samples[this._pos] = v;
  40117. this._pos++;
  40118. this._pos %= this._samples.length; //positive wrap around
  40119. };
  40120. /**
  40121. * Returns previously added values or null if outside of history or outside the sliding window domain
  40122. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40123. * @return Value previously recorded with add() or null if outside of range
  40124. */
  40125. RollingAverage.prototype.history = function (i) {
  40126. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40127. return 0;
  40128. }
  40129. var i0 = this._wrapPosition(this._pos - 1.0);
  40130. return this._samples[this._wrapPosition(i0 - i)];
  40131. };
  40132. /**
  40133. * Returns true if enough samples have been taken to completely fill the sliding window
  40134. * @return true if sample-set saturated
  40135. */
  40136. RollingAverage.prototype.isSaturated = function () {
  40137. return this._sampleCount >= this._samples.length;
  40138. };
  40139. /**
  40140. * Resets the rolling average (equivalent to 0 samples taken so far)
  40141. */
  40142. RollingAverage.prototype.reset = function () {
  40143. this.average = 0;
  40144. this.variance = 0;
  40145. this._sampleCount = 0;
  40146. this._pos = 0;
  40147. this._m2 = 0;
  40148. };
  40149. /**
  40150. * Wraps a value around the sample range boundaries
  40151. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40152. * @return Wrapped position in sample range
  40153. */
  40154. RollingAverage.prototype._wrapPosition = function (i) {
  40155. var max = this._samples.length;
  40156. return ((i % max) + max) % max;
  40157. };
  40158. return RollingAverage;
  40159. }());
  40160. BABYLON.RollingAverage = RollingAverage;
  40161. })(BABYLON || (BABYLON = {}));
  40162. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40163. "use strict";
  40164. var BABYLON;
  40165. (function (BABYLON) {
  40166. /**
  40167. * This groups together the common properties used for image processing either in direct forward pass
  40168. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40169. * or not.
  40170. */
  40171. var ImageProcessingConfiguration = /** @class */ (function () {
  40172. function ImageProcessingConfiguration() {
  40173. /**
  40174. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40175. */
  40176. this.colorCurves = new BABYLON.ColorCurves();
  40177. this._colorCurvesEnabled = false;
  40178. this._colorGradingEnabled = false;
  40179. this._colorGradingWithGreenDepth = true;
  40180. this._colorGradingBGR = true;
  40181. this._exposure = 1.0;
  40182. this._toneMappingEnabled = false;
  40183. this._contrast = 1.0;
  40184. /**
  40185. * Vignette stretch size.
  40186. */
  40187. this.vignetteStretch = 0;
  40188. /**
  40189. * Vignette centre X Offset.
  40190. */
  40191. this.vignetteCentreX = 0;
  40192. /**
  40193. * Vignette centre Y Offset.
  40194. */
  40195. this.vignetteCentreY = 0;
  40196. /**
  40197. * Vignette weight or intensity of the vignette effect.
  40198. */
  40199. this.vignetteWeight = 1.5;
  40200. /**
  40201. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40202. * if vignetteEnabled is set to true.
  40203. */
  40204. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40205. /**
  40206. * Camera field of view used by the Vignette effect.
  40207. */
  40208. this.vignetteCameraFov = 0.5;
  40209. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40210. this._vignetteEnabled = false;
  40211. this._applyByPostProcess = false;
  40212. this._isEnabled = true;
  40213. /**
  40214. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40215. */
  40216. this.onUpdateParameters = new BABYLON.Observable();
  40217. }
  40218. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40219. /**
  40220. * Gets wether the color curves effect is enabled.
  40221. */
  40222. get: function () {
  40223. return this._colorCurvesEnabled;
  40224. },
  40225. /**
  40226. * Sets wether the color curves effect is enabled.
  40227. */
  40228. set: function (value) {
  40229. if (this._colorCurvesEnabled === value) {
  40230. return;
  40231. }
  40232. this._colorCurvesEnabled = value;
  40233. this._updateParameters();
  40234. },
  40235. enumerable: true,
  40236. configurable: true
  40237. });
  40238. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40239. /**
  40240. * Gets wether the color grading effect is enabled.
  40241. */
  40242. get: function () {
  40243. return this._colorGradingEnabled;
  40244. },
  40245. /**
  40246. * Sets wether the color grading effect is enabled.
  40247. */
  40248. set: function (value) {
  40249. if (this._colorGradingEnabled === value) {
  40250. return;
  40251. }
  40252. this._colorGradingEnabled = value;
  40253. this._updateParameters();
  40254. },
  40255. enumerable: true,
  40256. configurable: true
  40257. });
  40258. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40259. /**
  40260. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40261. */
  40262. get: function () {
  40263. return this._colorGradingWithGreenDepth;
  40264. },
  40265. /**
  40266. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40267. */
  40268. set: function (value) {
  40269. if (this._colorGradingWithGreenDepth === value) {
  40270. return;
  40271. }
  40272. this._colorGradingWithGreenDepth = value;
  40273. this._updateParameters();
  40274. },
  40275. enumerable: true,
  40276. configurable: true
  40277. });
  40278. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40279. /**
  40280. * Gets wether the color grading texture contains BGR values.
  40281. */
  40282. get: function () {
  40283. return this._colorGradingBGR;
  40284. },
  40285. /**
  40286. * Sets wether the color grading texture contains BGR values.
  40287. */
  40288. set: function (value) {
  40289. if (this._colorGradingBGR === value) {
  40290. return;
  40291. }
  40292. this._colorGradingBGR = value;
  40293. this._updateParameters();
  40294. },
  40295. enumerable: true,
  40296. configurable: true
  40297. });
  40298. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40299. /**
  40300. * Gets the Exposure used in the effect.
  40301. */
  40302. get: function () {
  40303. return this._exposure;
  40304. },
  40305. /**
  40306. * Sets the Exposure used in the effect.
  40307. */
  40308. set: function (value) {
  40309. if (this._exposure === value) {
  40310. return;
  40311. }
  40312. this._exposure = value;
  40313. this._updateParameters();
  40314. },
  40315. enumerable: true,
  40316. configurable: true
  40317. });
  40318. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40319. /**
  40320. * Gets wether the tone mapping effect is enabled.
  40321. */
  40322. get: function () {
  40323. return this._toneMappingEnabled;
  40324. },
  40325. /**
  40326. * Sets wether the tone mapping effect is enabled.
  40327. */
  40328. set: function (value) {
  40329. if (this._toneMappingEnabled === value) {
  40330. return;
  40331. }
  40332. this._toneMappingEnabled = value;
  40333. this._updateParameters();
  40334. },
  40335. enumerable: true,
  40336. configurable: true
  40337. });
  40338. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40339. /**
  40340. * Gets the contrast used in the effect.
  40341. */
  40342. get: function () {
  40343. return this._contrast;
  40344. },
  40345. /**
  40346. * Sets the contrast used in the effect.
  40347. */
  40348. set: function (value) {
  40349. if (this._contrast === value) {
  40350. return;
  40351. }
  40352. this._contrast = value;
  40353. this._updateParameters();
  40354. },
  40355. enumerable: true,
  40356. configurable: true
  40357. });
  40358. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40359. /**
  40360. * Gets the vignette blend mode allowing different kind of effect.
  40361. */
  40362. get: function () {
  40363. return this._vignetteBlendMode;
  40364. },
  40365. /**
  40366. * Sets the vignette blend mode allowing different kind of effect.
  40367. */
  40368. set: function (value) {
  40369. if (this._vignetteBlendMode === value) {
  40370. return;
  40371. }
  40372. this._vignetteBlendMode = value;
  40373. this._updateParameters();
  40374. },
  40375. enumerable: true,
  40376. configurable: true
  40377. });
  40378. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40379. /**
  40380. * Gets wether the vignette effect is enabled.
  40381. */
  40382. get: function () {
  40383. return this._vignetteEnabled;
  40384. },
  40385. /**
  40386. * Sets wether the vignette effect is enabled.
  40387. */
  40388. set: function (value) {
  40389. if (this._vignetteEnabled === value) {
  40390. return;
  40391. }
  40392. this._vignetteEnabled = value;
  40393. this._updateParameters();
  40394. },
  40395. enumerable: true,
  40396. configurable: true
  40397. });
  40398. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40399. /**
  40400. * Gets wether the image processing is applied through a post process or not.
  40401. */
  40402. get: function () {
  40403. return this._applyByPostProcess;
  40404. },
  40405. /**
  40406. * Sets wether the image processing is applied through a post process or not.
  40407. */
  40408. set: function (value) {
  40409. if (this._applyByPostProcess === value) {
  40410. return;
  40411. }
  40412. this._applyByPostProcess = value;
  40413. this._updateParameters();
  40414. },
  40415. enumerable: true,
  40416. configurable: true
  40417. });
  40418. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40419. /**
  40420. * Gets wether the image processing is enabled or not.
  40421. */
  40422. get: function () {
  40423. return this._isEnabled;
  40424. },
  40425. /**
  40426. * Sets wether the image processing is enabled or not.
  40427. */
  40428. set: function (value) {
  40429. if (this._isEnabled === value) {
  40430. return;
  40431. }
  40432. this._isEnabled = value;
  40433. this._updateParameters();
  40434. },
  40435. enumerable: true,
  40436. configurable: true
  40437. });
  40438. /**
  40439. * Method called each time the image processing information changes requires to recompile the effect.
  40440. */
  40441. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40442. this.onUpdateParameters.notifyObservers(this);
  40443. };
  40444. ImageProcessingConfiguration.prototype.getClassName = function () {
  40445. return "ImageProcessingConfiguration";
  40446. };
  40447. /**
  40448. * Prepare the list of uniforms associated with the Image Processing effects.
  40449. * @param uniformsList The list of uniforms used in the effect
  40450. * @param defines the list of defines currently in use
  40451. */
  40452. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40453. if (defines.EXPOSURE) {
  40454. uniforms.push("exposureLinear");
  40455. }
  40456. if (defines.CONTRAST) {
  40457. uniforms.push("contrast");
  40458. }
  40459. if (defines.COLORGRADING) {
  40460. uniforms.push("colorTransformSettings");
  40461. }
  40462. if (defines.VIGNETTE) {
  40463. uniforms.push("vInverseScreenSize");
  40464. uniforms.push("vignetteSettings1");
  40465. uniforms.push("vignetteSettings2");
  40466. }
  40467. if (defines.COLORCURVES) {
  40468. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40469. }
  40470. };
  40471. /**
  40472. * Prepare the list of samplers associated with the Image Processing effects.
  40473. * @param uniformsList The list of uniforms used in the effect
  40474. * @param defines the list of defines currently in use
  40475. */
  40476. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40477. if (defines.COLORGRADING) {
  40478. samplersList.push("txColorTransform");
  40479. }
  40480. };
  40481. /**
  40482. * Prepare the list of defines associated to the shader.
  40483. * @param defines the list of defines to complete
  40484. */
  40485. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40486. if (forPostProcess === void 0) { forPostProcess = false; }
  40487. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40488. defines.VIGNETTE = false;
  40489. defines.TONEMAPPING = false;
  40490. defines.CONTRAST = false;
  40491. defines.EXPOSURE = false;
  40492. defines.COLORCURVES = false;
  40493. defines.COLORGRADING = false;
  40494. defines.COLORGRADING3D = false;
  40495. defines.IMAGEPROCESSING = false;
  40496. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40497. return;
  40498. }
  40499. defines.VIGNETTE = this.vignetteEnabled;
  40500. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40501. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40502. defines.TONEMAPPING = this.toneMappingEnabled;
  40503. defines.CONTRAST = (this.contrast !== 1.0);
  40504. defines.EXPOSURE = (this.exposure !== 1.0);
  40505. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40506. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40507. if (defines.COLORGRADING) {
  40508. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40509. }
  40510. else {
  40511. defines.COLORGRADING3D = false;
  40512. }
  40513. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40514. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40515. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40516. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40517. };
  40518. /**
  40519. * Returns true if all the image processing information are ready.
  40520. */
  40521. ImageProcessingConfiguration.prototype.isReady = function () {
  40522. // Color Grading texure can not be none blocking.
  40523. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40524. };
  40525. /**
  40526. * Binds the image processing to the shader.
  40527. * @param effect The effect to bind to
  40528. */
  40529. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40530. if (aspectRatio === void 0) { aspectRatio = 1; }
  40531. // Color Curves
  40532. if (this._colorCurvesEnabled && this.colorCurves) {
  40533. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40534. }
  40535. // Vignette
  40536. if (this._vignetteEnabled) {
  40537. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40538. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40539. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40540. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40541. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40542. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40543. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40544. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40545. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40546. var vignettePower = -2.0 * this.vignetteWeight;
  40547. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40548. }
  40549. // Exposure
  40550. effect.setFloat("exposureLinear", this.exposure);
  40551. // Contrast
  40552. effect.setFloat("contrast", this.contrast);
  40553. // Color transform settings
  40554. if (this.colorGradingTexture) {
  40555. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40556. var textureSize = this.colorGradingTexture.getSize().height;
  40557. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40558. 0.5 / textureSize, // textureOffset
  40559. textureSize, // textureSize
  40560. this.colorGradingTexture.level // weight
  40561. );
  40562. }
  40563. };
  40564. /**
  40565. * Clones the current image processing instance.
  40566. * @return The cloned image processing
  40567. */
  40568. ImageProcessingConfiguration.prototype.clone = function () {
  40569. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40570. };
  40571. /**
  40572. * Serializes the current image processing instance to a json representation.
  40573. * @return a JSON representation
  40574. */
  40575. ImageProcessingConfiguration.prototype.serialize = function () {
  40576. return BABYLON.SerializationHelper.Serialize(this);
  40577. };
  40578. /**
  40579. * Parses the image processing from a json representation.
  40580. * @param source the JSON source to parse
  40581. * @return The parsed image processing
  40582. */
  40583. ImageProcessingConfiguration.Parse = function (source) {
  40584. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40585. };
  40586. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40587. /**
  40588. * Used to apply the vignette as a mix with the pixel color.
  40589. */
  40590. get: function () {
  40591. return this._VIGNETTEMODE_MULTIPLY;
  40592. },
  40593. enumerable: true,
  40594. configurable: true
  40595. });
  40596. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40597. /**
  40598. * Used to apply the vignette as a replacement of the pixel color.
  40599. */
  40600. get: function () {
  40601. return this._VIGNETTEMODE_OPAQUE;
  40602. },
  40603. enumerable: true,
  40604. configurable: true
  40605. });
  40606. // Static constants associated to the image processing.
  40607. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40608. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40609. __decorate([
  40610. BABYLON.serializeAsColorCurves()
  40611. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40612. __decorate([
  40613. BABYLON.serialize()
  40614. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40615. __decorate([
  40616. BABYLON.serializeAsTexture()
  40617. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40618. __decorate([
  40619. BABYLON.serialize()
  40620. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40621. __decorate([
  40622. BABYLON.serialize()
  40623. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40624. __decorate([
  40625. BABYLON.serialize()
  40626. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40627. __decorate([
  40628. BABYLON.serialize()
  40629. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40630. __decorate([
  40631. BABYLON.serialize()
  40632. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40633. __decorate([
  40634. BABYLON.serialize()
  40635. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40636. __decorate([
  40637. BABYLON.serialize()
  40638. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40639. __decorate([
  40640. BABYLON.serialize()
  40641. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40642. __decorate([
  40643. BABYLON.serialize()
  40644. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40645. __decorate([
  40646. BABYLON.serialize()
  40647. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40648. __decorate([
  40649. BABYLON.serializeAsColor4()
  40650. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40651. __decorate([
  40652. BABYLON.serialize()
  40653. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40654. __decorate([
  40655. BABYLON.serialize()
  40656. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40657. __decorate([
  40658. BABYLON.serialize()
  40659. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40660. __decorate([
  40661. BABYLON.serialize()
  40662. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40663. __decorate([
  40664. BABYLON.serialize()
  40665. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40666. return ImageProcessingConfiguration;
  40667. }());
  40668. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40669. })(BABYLON || (BABYLON = {}));
  40670. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40671. "use strict";
  40672. var BABYLON;
  40673. (function (BABYLON) {
  40674. /**
  40675. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40676. * It can help converting any input color in a desired output one. This can then be used to create effects
  40677. * from sepia, black and white to sixties or futuristic rendering...
  40678. *
  40679. * The only supported format is currently 3dl.
  40680. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40681. */
  40682. var ColorGradingTexture = /** @class */ (function (_super) {
  40683. __extends(ColorGradingTexture, _super);
  40684. /**
  40685. * Instantiates a ColorGradingTexture from the following parameters.
  40686. *
  40687. * @param url The location of the color gradind data (currently only supporting 3dl)
  40688. * @param scene The scene the texture will be used in
  40689. */
  40690. function ColorGradingTexture(url, scene) {
  40691. var _this = _super.call(this, scene) || this;
  40692. if (!url) {
  40693. return _this;
  40694. }
  40695. _this._engine = scene.getEngine();
  40696. _this._textureMatrix = BABYLON.Matrix.Identity();
  40697. _this.name = url;
  40698. _this.url = url;
  40699. _this.hasAlpha = false;
  40700. _this.isCube = false;
  40701. _this.is3D = _this._engine.webGLVersion > 1;
  40702. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40703. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40704. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40705. _this.anisotropicFilteringLevel = 1;
  40706. _this._texture = _this._getFromCache(url, true);
  40707. if (!_this._texture) {
  40708. if (!scene.useDelayedTextureLoading) {
  40709. _this.loadTexture();
  40710. }
  40711. else {
  40712. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40713. }
  40714. }
  40715. return _this;
  40716. }
  40717. /**
  40718. * Returns the texture matrix used in most of the material.
  40719. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40720. */
  40721. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40722. return this._textureMatrix;
  40723. };
  40724. /**
  40725. * Occurs when the file being loaded is a .3dl LUT file.
  40726. */
  40727. ColorGradingTexture.prototype.load3dlTexture = function () {
  40728. var engine = this._engine;
  40729. var texture;
  40730. if (engine.webGLVersion === 1) {
  40731. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40732. }
  40733. else {
  40734. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40735. }
  40736. this._texture = texture;
  40737. var callback = function (text) {
  40738. if (typeof text !== "string") {
  40739. return;
  40740. }
  40741. var data = null;
  40742. var tempData = null;
  40743. var line;
  40744. var lines = text.split('\n');
  40745. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  40746. var maxColor = 0;
  40747. for (var i = 0; i < lines.length; i++) {
  40748. line = lines[i];
  40749. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  40750. continue;
  40751. if (line.indexOf('#') === 0)
  40752. continue;
  40753. var words = line.split(" ");
  40754. if (size === 0) {
  40755. // Number of space + one
  40756. size = words.length;
  40757. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  40758. tempData = new Float32Array(size * size * size * 4);
  40759. continue;
  40760. }
  40761. if (size != 0) {
  40762. var r = Math.max(parseInt(words[0]), 0);
  40763. var g = Math.max(parseInt(words[1]), 0);
  40764. var b = Math.max(parseInt(words[2]), 0);
  40765. maxColor = Math.max(r, maxColor);
  40766. maxColor = Math.max(g, maxColor);
  40767. maxColor = Math.max(b, maxColor);
  40768. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  40769. if (tempData) {
  40770. tempData[pixelStorageIndex + 0] = r;
  40771. tempData[pixelStorageIndex + 1] = g;
  40772. tempData[pixelStorageIndex + 2] = b;
  40773. }
  40774. pixelIndexSlice++;
  40775. if (pixelIndexSlice % size == 0) {
  40776. pixelIndexH++;
  40777. pixelIndexSlice = 0;
  40778. if (pixelIndexH % size == 0) {
  40779. pixelIndexW++;
  40780. pixelIndexH = 0;
  40781. }
  40782. }
  40783. }
  40784. }
  40785. if (tempData && data) {
  40786. for (var i = 0; i < tempData.length; i++) {
  40787. if (i > 0 && (i + 1) % 4 === 0) {
  40788. data[i] = 255;
  40789. }
  40790. else {
  40791. var value = tempData[i];
  40792. data[i] = (value / maxColor * 255);
  40793. }
  40794. }
  40795. }
  40796. if (texture.is3D) {
  40797. texture.updateSize(size, size, size);
  40798. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40799. }
  40800. else {
  40801. texture.updateSize(size * size, size);
  40802. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40803. }
  40804. };
  40805. var scene = this.getScene();
  40806. if (scene) {
  40807. scene._loadFile(this.url, callback);
  40808. }
  40809. else {
  40810. this._engine._loadFile(this.url, callback);
  40811. }
  40812. return this._texture;
  40813. };
  40814. /**
  40815. * Starts the loading process of the texture.
  40816. */
  40817. ColorGradingTexture.prototype.loadTexture = function () {
  40818. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  40819. this.load3dlTexture();
  40820. }
  40821. };
  40822. /**
  40823. * Clones the color gradind texture.
  40824. */
  40825. ColorGradingTexture.prototype.clone = function () {
  40826. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  40827. // Base texture
  40828. newTexture.level = this.level;
  40829. return newTexture;
  40830. };
  40831. /**
  40832. * Called during delayed load for textures.
  40833. */
  40834. ColorGradingTexture.prototype.delayLoad = function () {
  40835. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40836. return;
  40837. }
  40838. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40839. this._texture = this._getFromCache(this.url, true);
  40840. if (!this._texture) {
  40841. this.loadTexture();
  40842. }
  40843. };
  40844. /**
  40845. * Parses a color grading texture serialized by Babylon.
  40846. * @param parsedTexture The texture information being parsedTexture
  40847. * @param scene The scene to load the texture in
  40848. * @param rootUrl The root url of the data assets to load
  40849. * @return A color gradind texture
  40850. */
  40851. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40852. var texture = null;
  40853. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40854. texture = new ColorGradingTexture(parsedTexture.name, scene);
  40855. texture.name = parsedTexture.name;
  40856. texture.level = parsedTexture.level;
  40857. }
  40858. return texture;
  40859. };
  40860. /**
  40861. * Serializes the LUT texture to json format.
  40862. */
  40863. ColorGradingTexture.prototype.serialize = function () {
  40864. if (!this.name) {
  40865. return null;
  40866. }
  40867. var serializationObject = {};
  40868. serializationObject.name = this.name;
  40869. serializationObject.level = this.level;
  40870. serializationObject.customType = "BABYLON.ColorGradingTexture";
  40871. return serializationObject;
  40872. };
  40873. /**
  40874. * Empty line regex stored for GC.
  40875. */
  40876. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  40877. return ColorGradingTexture;
  40878. }(BABYLON.BaseTexture));
  40879. BABYLON.ColorGradingTexture = ColorGradingTexture;
  40880. })(BABYLON || (BABYLON = {}));
  40881. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  40882. "use strict";
  40883. var BABYLON;
  40884. (function (BABYLON) {
  40885. /**
  40886. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40887. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40888. * 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;
  40889. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40890. */
  40891. var ColorCurves = /** @class */ (function () {
  40892. function ColorCurves() {
  40893. this._dirty = true;
  40894. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  40895. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  40896. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40897. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  40898. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40899. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  40900. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  40901. this._globalHue = 30;
  40902. this._globalDensity = 0;
  40903. this._globalSaturation = 0;
  40904. this._globalExposure = 0;
  40905. this._highlightsHue = 30;
  40906. this._highlightsDensity = 0;
  40907. this._highlightsSaturation = 0;
  40908. this._highlightsExposure = 0;
  40909. this._midtonesHue = 30;
  40910. this._midtonesDensity = 0;
  40911. this._midtonesSaturation = 0;
  40912. this._midtonesExposure = 0;
  40913. this._shadowsHue = 30;
  40914. this._shadowsDensity = 0;
  40915. this._shadowsSaturation = 0;
  40916. this._shadowsExposure = 0;
  40917. }
  40918. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  40919. /**
  40920. * Gets the global Hue value.
  40921. * 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).
  40922. */
  40923. get: function () {
  40924. return this._globalHue;
  40925. },
  40926. /**
  40927. * Sets the global Hue value.
  40928. * 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).
  40929. */
  40930. set: function (value) {
  40931. this._globalHue = value;
  40932. this._dirty = true;
  40933. },
  40934. enumerable: true,
  40935. configurable: true
  40936. });
  40937. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  40938. /**
  40939. * Gets the global Density value.
  40940. * 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.
  40941. * Values less than zero provide a filter of opposite hue.
  40942. */
  40943. get: function () {
  40944. return this._globalDensity;
  40945. },
  40946. /**
  40947. * Sets the global Density value.
  40948. * 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.
  40949. * Values less than zero provide a filter of opposite hue.
  40950. */
  40951. set: function (value) {
  40952. this._globalDensity = value;
  40953. this._dirty = true;
  40954. },
  40955. enumerable: true,
  40956. configurable: true
  40957. });
  40958. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  40959. /**
  40960. * Gets the global Saturation value.
  40961. * 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.
  40962. */
  40963. get: function () {
  40964. return this._globalSaturation;
  40965. },
  40966. /**
  40967. * Sets the global Saturation value.
  40968. * 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.
  40969. */
  40970. set: function (value) {
  40971. this._globalSaturation = value;
  40972. this._dirty = true;
  40973. },
  40974. enumerable: true,
  40975. configurable: true
  40976. });
  40977. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  40978. /**
  40979. * Gets the highlights Hue value.
  40980. * 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).
  40981. */
  40982. get: function () {
  40983. return this._highlightsHue;
  40984. },
  40985. /**
  40986. * Sets the highlights Hue value.
  40987. * 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).
  40988. */
  40989. set: function (value) {
  40990. this._highlightsHue = value;
  40991. this._dirty = true;
  40992. },
  40993. enumerable: true,
  40994. configurable: true
  40995. });
  40996. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  40997. /**
  40998. * Gets the highlights Density value.
  40999. * 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.
  41000. * Values less than zero provide a filter of opposite hue.
  41001. */
  41002. get: function () {
  41003. return this._highlightsDensity;
  41004. },
  41005. /**
  41006. * Sets the highlights Density value.
  41007. * 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.
  41008. * Values less than zero provide a filter of opposite hue.
  41009. */
  41010. set: function (value) {
  41011. this._highlightsDensity = value;
  41012. this._dirty = true;
  41013. },
  41014. enumerable: true,
  41015. configurable: true
  41016. });
  41017. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41018. /**
  41019. * Gets the highlights Saturation value.
  41020. * 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.
  41021. */
  41022. get: function () {
  41023. return this._highlightsSaturation;
  41024. },
  41025. /**
  41026. * Sets the highlights Saturation value.
  41027. * 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.
  41028. */
  41029. set: function (value) {
  41030. this._highlightsSaturation = value;
  41031. this._dirty = true;
  41032. },
  41033. enumerable: true,
  41034. configurable: true
  41035. });
  41036. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41037. /**
  41038. * Gets the highlights Exposure value.
  41039. * 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.
  41040. */
  41041. get: function () {
  41042. return this._highlightsExposure;
  41043. },
  41044. /**
  41045. * Sets the highlights Exposure value.
  41046. * 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.
  41047. */
  41048. set: function (value) {
  41049. this._highlightsExposure = value;
  41050. this._dirty = true;
  41051. },
  41052. enumerable: true,
  41053. configurable: true
  41054. });
  41055. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41056. /**
  41057. * Gets the midtones Hue value.
  41058. * 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).
  41059. */
  41060. get: function () {
  41061. return this._midtonesHue;
  41062. },
  41063. /**
  41064. * Sets the midtones Hue value.
  41065. * 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).
  41066. */
  41067. set: function (value) {
  41068. this._midtonesHue = value;
  41069. this._dirty = true;
  41070. },
  41071. enumerable: true,
  41072. configurable: true
  41073. });
  41074. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41075. /**
  41076. * Gets the midtones Density value.
  41077. * 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.
  41078. * Values less than zero provide a filter of opposite hue.
  41079. */
  41080. get: function () {
  41081. return this._midtonesDensity;
  41082. },
  41083. /**
  41084. * Sets the midtones Density value.
  41085. * 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.
  41086. * Values less than zero provide a filter of opposite hue.
  41087. */
  41088. set: function (value) {
  41089. this._midtonesDensity = value;
  41090. this._dirty = true;
  41091. },
  41092. enumerable: true,
  41093. configurable: true
  41094. });
  41095. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41096. /**
  41097. * Gets the midtones Saturation value.
  41098. * 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.
  41099. */
  41100. get: function () {
  41101. return this._midtonesSaturation;
  41102. },
  41103. /**
  41104. * Sets the midtones Saturation value.
  41105. * 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.
  41106. */
  41107. set: function (value) {
  41108. this._midtonesSaturation = value;
  41109. this._dirty = true;
  41110. },
  41111. enumerable: true,
  41112. configurable: true
  41113. });
  41114. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41115. /**
  41116. * Gets the midtones Exposure value.
  41117. * 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.
  41118. */
  41119. get: function () {
  41120. return this._midtonesExposure;
  41121. },
  41122. /**
  41123. * Sets the midtones Exposure value.
  41124. * 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.
  41125. */
  41126. set: function (value) {
  41127. this._midtonesExposure = value;
  41128. this._dirty = true;
  41129. },
  41130. enumerable: true,
  41131. configurable: true
  41132. });
  41133. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41134. /**
  41135. * Gets the shadows Hue value.
  41136. * 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).
  41137. */
  41138. get: function () {
  41139. return this._shadowsHue;
  41140. },
  41141. /**
  41142. * Sets the shadows Hue value.
  41143. * 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).
  41144. */
  41145. set: function (value) {
  41146. this._shadowsHue = value;
  41147. this._dirty = true;
  41148. },
  41149. enumerable: true,
  41150. configurable: true
  41151. });
  41152. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41153. /**
  41154. * Gets the shadows Density value.
  41155. * 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.
  41156. * Values less than zero provide a filter of opposite hue.
  41157. */
  41158. get: function () {
  41159. return this._shadowsDensity;
  41160. },
  41161. /**
  41162. * Sets the shadows Density value.
  41163. * 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.
  41164. * Values less than zero provide a filter of opposite hue.
  41165. */
  41166. set: function (value) {
  41167. this._shadowsDensity = value;
  41168. this._dirty = true;
  41169. },
  41170. enumerable: true,
  41171. configurable: true
  41172. });
  41173. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41174. /**
  41175. * Gets the shadows Saturation value.
  41176. * 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.
  41177. */
  41178. get: function () {
  41179. return this._shadowsSaturation;
  41180. },
  41181. /**
  41182. * Sets the shadows Saturation value.
  41183. * 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.
  41184. */
  41185. set: function (value) {
  41186. this._shadowsSaturation = value;
  41187. this._dirty = true;
  41188. },
  41189. enumerable: true,
  41190. configurable: true
  41191. });
  41192. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41193. /**
  41194. * Gets the shadows Exposure value.
  41195. * 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.
  41196. */
  41197. get: function () {
  41198. return this._shadowsExposure;
  41199. },
  41200. /**
  41201. * Sets the shadows Exposure value.
  41202. * 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.
  41203. */
  41204. set: function (value) {
  41205. this._shadowsExposure = value;
  41206. this._dirty = true;
  41207. },
  41208. enumerable: true,
  41209. configurable: true
  41210. });
  41211. ColorCurves.prototype.getClassName = function () {
  41212. return "ColorCurves";
  41213. };
  41214. /**
  41215. * Binds the color curves to the shader.
  41216. * @param colorCurves The color curve to bind
  41217. * @param effect The effect to bind to
  41218. */
  41219. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41220. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41221. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41222. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41223. if (colorCurves._dirty) {
  41224. colorCurves._dirty = false;
  41225. // Fill in global info.
  41226. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41227. // Compute highlights info.
  41228. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41229. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41230. // Compute midtones info.
  41231. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41232. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41233. // Compute shadows info.
  41234. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41235. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41236. // Compute deltas (neutral is midtones).
  41237. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41238. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41239. }
  41240. if (effect) {
  41241. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41242. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41243. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41244. }
  41245. };
  41246. /**
  41247. * Prepare the list of uniforms associated with the ColorCurves effects.
  41248. * @param uniformsList The list of uniforms used in the effect
  41249. */
  41250. ColorCurves.PrepareUniforms = function (uniformsList) {
  41251. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41252. };
  41253. /**
  41254. * Returns color grading data based on a hue, density, saturation and exposure value.
  41255. * @param filterHue The hue of the color filter.
  41256. * @param filterDensity The density of the color filter.
  41257. * @param saturation The saturation.
  41258. * @param exposure The exposure.
  41259. * @param result The result data container.
  41260. */
  41261. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41262. if (hue == null) {
  41263. return;
  41264. }
  41265. hue = ColorCurves.clamp(hue, 0, 360);
  41266. density = ColorCurves.clamp(density, -100, 100);
  41267. saturation = ColorCurves.clamp(saturation, -100, 100);
  41268. exposure = ColorCurves.clamp(exposure, -100, 100);
  41269. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41270. // so that the maximum filter density is only 50% control. This provides fine control
  41271. // for small values and reasonable range.
  41272. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41273. density *= 0.5;
  41274. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41275. if (density < 0) {
  41276. density *= -1;
  41277. hue = (hue + 180) % 360;
  41278. }
  41279. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41280. result.scaleToRef(2, result);
  41281. result.a = 1 + 0.01 * saturation;
  41282. };
  41283. /**
  41284. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41285. * @param value The input slider value in range [-100,100].
  41286. * @returns Adjusted value.
  41287. */
  41288. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41289. value /= 100;
  41290. var x = Math.abs(value);
  41291. x = Math.pow(x, 2);
  41292. if (value < 0) {
  41293. x *= -1;
  41294. }
  41295. x *= 100;
  41296. return x;
  41297. };
  41298. /**
  41299. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41300. * @param hue The hue (H) input.
  41301. * @param saturation The saturation (S) input.
  41302. * @param brightness The brightness (B) input.
  41303. * @result An RGBA color represented as Vector4.
  41304. */
  41305. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41306. var h = ColorCurves.clamp(hue, 0, 360);
  41307. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41308. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41309. if (s === 0) {
  41310. result.r = v;
  41311. result.g = v;
  41312. result.b = v;
  41313. }
  41314. else {
  41315. // sector 0 to 5
  41316. h /= 60;
  41317. var i = Math.floor(h);
  41318. // fractional part of h
  41319. var f = h - i;
  41320. var p = v * (1 - s);
  41321. var q = v * (1 - s * f);
  41322. var t = v * (1 - s * (1 - f));
  41323. switch (i) {
  41324. case 0:
  41325. result.r = v;
  41326. result.g = t;
  41327. result.b = p;
  41328. break;
  41329. case 1:
  41330. result.r = q;
  41331. result.g = v;
  41332. result.b = p;
  41333. break;
  41334. case 2:
  41335. result.r = p;
  41336. result.g = v;
  41337. result.b = t;
  41338. break;
  41339. case 3:
  41340. result.r = p;
  41341. result.g = q;
  41342. result.b = v;
  41343. break;
  41344. case 4:
  41345. result.r = t;
  41346. result.g = p;
  41347. result.b = v;
  41348. break;
  41349. default:// case 5:
  41350. result.r = v;
  41351. result.g = p;
  41352. result.b = q;
  41353. break;
  41354. }
  41355. }
  41356. result.a = 1;
  41357. };
  41358. /**
  41359. * Returns a value clamped between min and max
  41360. * @param value The value to clamp
  41361. * @param min The minimum of value
  41362. * @param max The maximum of value
  41363. * @returns The clamped value.
  41364. */
  41365. ColorCurves.clamp = function (value, min, max) {
  41366. return Math.min(Math.max(value, min), max);
  41367. };
  41368. /**
  41369. * Clones the current color curve instance.
  41370. * @return The cloned curves
  41371. */
  41372. ColorCurves.prototype.clone = function () {
  41373. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41374. };
  41375. /**
  41376. * Serializes the current color curve instance to a json representation.
  41377. * @return a JSON representation
  41378. */
  41379. ColorCurves.prototype.serialize = function () {
  41380. return BABYLON.SerializationHelper.Serialize(this);
  41381. };
  41382. /**
  41383. * Parses the color curve from a json representation.
  41384. * @param source the JSON source to parse
  41385. * @return The parsed curves
  41386. */
  41387. ColorCurves.Parse = function (source) {
  41388. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41389. };
  41390. __decorate([
  41391. BABYLON.serialize()
  41392. ], ColorCurves.prototype, "_globalHue", void 0);
  41393. __decorate([
  41394. BABYLON.serialize()
  41395. ], ColorCurves.prototype, "_globalDensity", void 0);
  41396. __decorate([
  41397. BABYLON.serialize()
  41398. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41399. __decorate([
  41400. BABYLON.serialize()
  41401. ], ColorCurves.prototype, "_globalExposure", void 0);
  41402. __decorate([
  41403. BABYLON.serialize()
  41404. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41405. __decorate([
  41406. BABYLON.serialize()
  41407. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41408. __decorate([
  41409. BABYLON.serialize()
  41410. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41411. __decorate([
  41412. BABYLON.serialize()
  41413. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41414. __decorate([
  41415. BABYLON.serialize()
  41416. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41417. __decorate([
  41418. BABYLON.serialize()
  41419. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41420. __decorate([
  41421. BABYLON.serialize()
  41422. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41423. __decorate([
  41424. BABYLON.serialize()
  41425. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41426. return ColorCurves;
  41427. }());
  41428. BABYLON.ColorCurves = ColorCurves;
  41429. })(BABYLON || (BABYLON = {}));
  41430. //# sourceMappingURL=babylon.colorCurves.js.map
  41431. "use strict";
  41432. //# sourceMappingURL=babylon.behavior.js.map
  41433. "use strict";
  41434. var BABYLON;
  41435. (function (BABYLON) {
  41436. /**
  41437. * "Static Class" containing the most commonly used helper while dealing with material for
  41438. * rendering purpose.
  41439. *
  41440. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41441. *
  41442. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41443. */
  41444. var MaterialHelper = /** @class */ (function () {
  41445. function MaterialHelper() {
  41446. }
  41447. /**
  41448. * Bind the current view position to an effect.
  41449. * @param effect The effect to be bound
  41450. * @param scene The scene the eyes position is used from
  41451. */
  41452. MaterialHelper.BindEyePosition = function (effect, scene) {
  41453. if (scene._forcedViewPosition) {
  41454. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41455. return;
  41456. }
  41457. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41458. };
  41459. /**
  41460. * Helps preparing the defines values about the UVs in used in the effect.
  41461. * UVs are shared as much as we can accross chanels in the shaders.
  41462. * @param texture The texture we are preparing the UVs for
  41463. * @param defines The defines to update
  41464. * @param key The chanel key "diffuse", "specular"... used in the shader
  41465. */
  41466. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41467. defines._needUVs = true;
  41468. defines[key] = true;
  41469. if (texture.getTextureMatrix().isIdentity(true)) {
  41470. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41471. if (texture.coordinatesIndex === 0) {
  41472. defines["MAINUV1"] = true;
  41473. }
  41474. else {
  41475. defines["MAINUV2"] = true;
  41476. }
  41477. }
  41478. else {
  41479. defines[key + "DIRECTUV"] = 0;
  41480. }
  41481. };
  41482. /**
  41483. * Binds a texture matrix value to its corrsponding uniform
  41484. * @param texture The texture to bind the matrix for
  41485. * @param uniformBuffer The uniform buffer receivin the data
  41486. * @param key The chanel key "diffuse", "specular"... used in the shader
  41487. */
  41488. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41489. var matrix = texture.getTextureMatrix();
  41490. if (!matrix.isIdentity(true)) {
  41491. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41492. }
  41493. };
  41494. /**
  41495. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41496. * @param mesh defines the current mesh
  41497. * @param scene defines the current scene
  41498. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41499. * @param pointsCloud defines if point cloud rendering has to be turned on
  41500. * @param fogEnabled defines if fog has to be turned on
  41501. * @param alphaTest defines if alpha testing has to be turned on
  41502. * @param defines defines the current list of defines
  41503. */
  41504. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41505. if (defines._areMiscDirty) {
  41506. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41507. defines["POINTSIZE"] = pointsCloud;
  41508. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41509. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41510. defines["ALPHATEST"] = alphaTest;
  41511. }
  41512. };
  41513. /**
  41514. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41515. * @param scene defines the current scene
  41516. * @param engine defines the current engine
  41517. * @param defines specifies the list of active defines
  41518. * @param useInstances defines if instances have to be turned on
  41519. * @param useClipPlane defines if clip plane have to be turned on
  41520. */
  41521. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41522. if (useClipPlane === void 0) { useClipPlane = null; }
  41523. var changed = false;
  41524. if (useClipPlane == null) {
  41525. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41526. }
  41527. if (defines["CLIPPLANE"] !== useClipPlane) {
  41528. defines["CLIPPLANE"] = useClipPlane;
  41529. changed = true;
  41530. }
  41531. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41532. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41533. changed = true;
  41534. }
  41535. if (defines["INSTANCES"] !== useInstances) {
  41536. defines["INSTANCES"] = useInstances;
  41537. changed = true;
  41538. }
  41539. if (changed) {
  41540. defines.markAsUnprocessed();
  41541. }
  41542. };
  41543. /**
  41544. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41545. * @param mesh The mesh containing the geometry data we will draw
  41546. * @param defines The defines to update
  41547. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41548. * @param useBones Precise whether bones should be used or not (override mesh info)
  41549. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41550. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41551. * @returns false if defines are considered not dirty and have not been checked
  41552. */
  41553. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41554. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41555. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41556. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41557. return false;
  41558. }
  41559. defines._normals = defines._needNormals;
  41560. defines._uvs = defines._needUVs;
  41561. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41562. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41563. defines["TANGENT"] = true;
  41564. }
  41565. if (defines._needUVs) {
  41566. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41567. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41568. }
  41569. else {
  41570. defines["UV1"] = false;
  41571. defines["UV2"] = false;
  41572. }
  41573. if (useVertexColor) {
  41574. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41575. defines["VERTEXCOLOR"] = hasVertexColors;
  41576. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41577. }
  41578. if (useBones) {
  41579. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41580. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41581. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41582. }
  41583. else {
  41584. defines["NUM_BONE_INFLUENCERS"] = 0;
  41585. defines["BonesPerMesh"] = 0;
  41586. }
  41587. }
  41588. if (useMorphTargets) {
  41589. var manager = mesh.morphTargetManager;
  41590. if (manager) {
  41591. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41592. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41593. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41594. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41595. }
  41596. else {
  41597. defines["MORPHTARGETS_TANGENT"] = false;
  41598. defines["MORPHTARGETS_NORMAL"] = false;
  41599. defines["MORPHTARGETS"] = false;
  41600. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41601. }
  41602. }
  41603. return true;
  41604. };
  41605. /**
  41606. * Prepares the defines related to the light information passed in parameter
  41607. * @param scene The scene we are intending to draw
  41608. * @param mesh The mesh the effect is compiling for
  41609. * @param defines The defines to update
  41610. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41611. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41612. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41613. * @returns true if normals will be required for the rest of the effect
  41614. */
  41615. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41616. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41617. if (disableLighting === void 0) { disableLighting = false; }
  41618. if (!defines._areLightsDirty) {
  41619. return defines._needNormals;
  41620. }
  41621. var lightIndex = 0;
  41622. var needNormals = false;
  41623. var needRebuild = false;
  41624. var lightmapMode = false;
  41625. var shadowEnabled = false;
  41626. var specularEnabled = false;
  41627. if (scene.lightsEnabled && !disableLighting) {
  41628. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41629. var light = _a[_i];
  41630. needNormals = true;
  41631. if (defines["LIGHT" + lightIndex] === undefined) {
  41632. needRebuild = true;
  41633. }
  41634. defines["LIGHT" + lightIndex] = true;
  41635. defines["SPOTLIGHT" + lightIndex] = false;
  41636. defines["HEMILIGHT" + lightIndex] = false;
  41637. defines["POINTLIGHT" + lightIndex] = false;
  41638. defines["DIRLIGHT" + lightIndex] = false;
  41639. var type;
  41640. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41641. type = "SPOTLIGHT" + lightIndex;
  41642. var spotLight = light;
  41643. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  41644. }
  41645. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41646. type = "HEMILIGHT" + lightIndex;
  41647. }
  41648. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41649. type = "POINTLIGHT" + lightIndex;
  41650. }
  41651. else {
  41652. type = "DIRLIGHT" + lightIndex;
  41653. }
  41654. defines[type] = true;
  41655. // Specular
  41656. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41657. specularEnabled = true;
  41658. }
  41659. // Shadows
  41660. defines["SHADOW" + lightIndex] = false;
  41661. defines["SHADOWPCF" + lightIndex] = false;
  41662. defines["SHADOWPCSS" + lightIndex] = false;
  41663. defines["SHADOWPOISSON" + lightIndex] = false;
  41664. defines["SHADOWESM" + lightIndex] = false;
  41665. defines["SHADOWCUBE" + lightIndex] = false;
  41666. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41667. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41668. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41669. var shadowGenerator = light.getShadowGenerator();
  41670. if (shadowGenerator) {
  41671. shadowEnabled = true;
  41672. shadowGenerator.prepareDefines(defines, lightIndex);
  41673. }
  41674. }
  41675. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41676. lightmapMode = true;
  41677. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41678. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41679. }
  41680. else {
  41681. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41682. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41683. }
  41684. lightIndex++;
  41685. if (lightIndex === maxSimultaneousLights)
  41686. break;
  41687. }
  41688. }
  41689. defines["SPECULARTERM"] = specularEnabled;
  41690. defines["SHADOWS"] = shadowEnabled;
  41691. // Resetting all other lights if any
  41692. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41693. if (defines["LIGHT" + index] !== undefined) {
  41694. defines["LIGHT" + index] = false;
  41695. defines["HEMILIGHT" + lightIndex] = false;
  41696. defines["POINTLIGHT" + lightIndex] = false;
  41697. defines["DIRLIGHT" + lightIndex] = false;
  41698. defines["SPOTLIGHT" + lightIndex] = false;
  41699. defines["SHADOW" + lightIndex] = false;
  41700. }
  41701. }
  41702. var caps = scene.getEngine().getCaps();
  41703. if (defines["SHADOWFLOAT"] === undefined) {
  41704. needRebuild = true;
  41705. }
  41706. defines["SHADOWFLOAT"] = shadowEnabled &&
  41707. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41708. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41709. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41710. if (needRebuild) {
  41711. defines.rebuild();
  41712. }
  41713. return needNormals;
  41714. };
  41715. /**
  41716. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41717. * that won t be acctive due to defines being turned off.
  41718. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41719. * @param samplersList The samplers list
  41720. * @param defines The defines helping in the list generation
  41721. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41722. */
  41723. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41724. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41725. var uniformsList;
  41726. var uniformBuffersList = null;
  41727. if (uniformsListOrOptions.uniformsNames) {
  41728. var options = uniformsListOrOptions;
  41729. uniformsList = options.uniformsNames;
  41730. uniformBuffersList = options.uniformBuffersNames;
  41731. samplersList = options.samplers;
  41732. defines = options.defines;
  41733. maxSimultaneousLights = options.maxSimultaneousLights;
  41734. }
  41735. else {
  41736. uniformsList = uniformsListOrOptions;
  41737. if (!samplersList) {
  41738. samplersList = [];
  41739. }
  41740. }
  41741. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41742. if (!defines["LIGHT" + lightIndex]) {
  41743. break;
  41744. }
  41745. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41746. if (uniformBuffersList) {
  41747. uniformBuffersList.push("Light" + lightIndex);
  41748. }
  41749. samplersList.push("shadowSampler" + lightIndex);
  41750. samplersList.push("depthSampler" + lightIndex);
  41751. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41752. samplersList.push("projectionLightSampler" + lightIndex);
  41753. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41754. }
  41755. }
  41756. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41757. uniformsList.push("morphTargetInfluences");
  41758. }
  41759. };
  41760. /**
  41761. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41762. * @param defines The defines to update while falling back
  41763. * @param fallbacks The authorized effect fallbacks
  41764. * @param maxSimultaneousLights The maximum number of lights allowed
  41765. * @param rank the current rank of the Effect
  41766. * @returns The newly affected rank
  41767. */
  41768. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41769. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41770. if (rank === void 0) { rank = 0; }
  41771. var lightFallbackRank = 0;
  41772. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41773. if (!defines["LIGHT" + lightIndex]) {
  41774. break;
  41775. }
  41776. if (lightIndex > 0) {
  41777. lightFallbackRank = rank + lightIndex;
  41778. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41779. }
  41780. if (!defines["SHADOWS"]) {
  41781. if (defines["SHADOW" + lightIndex]) {
  41782. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41783. }
  41784. if (defines["SHADOWPCF" + lightIndex]) {
  41785. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41786. }
  41787. if (defines["SHADOWPCSS" + lightIndex]) {
  41788. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41789. }
  41790. if (defines["SHADOWPOISSON" + lightIndex]) {
  41791. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41792. }
  41793. if (defines["SHADOWESM" + lightIndex]) {
  41794. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41795. }
  41796. }
  41797. }
  41798. return lightFallbackRank++;
  41799. };
  41800. /**
  41801. * Prepares the list of attributes required for morph targets according to the effect defines.
  41802. * @param attribs The current list of supported attribs
  41803. * @param mesh The mesh to prepare the morph targets attributes for
  41804. * @param defines The current Defines of the effect
  41805. */
  41806. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41807. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41808. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41809. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41810. var manager = mesh.morphTargetManager;
  41811. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41812. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41813. for (var index = 0; index < influencers; index++) {
  41814. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41815. if (normal) {
  41816. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41817. }
  41818. if (tangent) {
  41819. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41820. }
  41821. if (attribs.length > maxAttributesCount) {
  41822. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41823. }
  41824. }
  41825. }
  41826. };
  41827. /**
  41828. * Prepares the list of attributes required for bones according to the effect defines.
  41829. * @param attribs The current list of supported attribs
  41830. * @param mesh The mesh to prepare the bones attributes for
  41831. * @param defines The current Defines of the effect
  41832. * @param fallbacks The current efffect fallback strategy
  41833. */
  41834. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41835. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41836. fallbacks.addCPUSkinningFallback(0, mesh);
  41837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41839. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41840. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41841. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41842. }
  41843. }
  41844. };
  41845. /**
  41846. * Prepares the list of attributes required for instances according to the effect defines.
  41847. * @param attribs The current list of supported attribs
  41848. * @param defines The current Defines of the effect
  41849. */
  41850. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41851. if (defines["INSTANCES"]) {
  41852. attribs.push("world0");
  41853. attribs.push("world1");
  41854. attribs.push("world2");
  41855. attribs.push("world3");
  41856. }
  41857. };
  41858. /**
  41859. * Binds the light shadow information to the effect for the given mesh.
  41860. * @param light The light containing the generator
  41861. * @param scene The scene the lights belongs to
  41862. * @param mesh The mesh we are binding the information to render
  41863. * @param lightIndex The light index in the effect used to render the mesh
  41864. * @param effect The effect we are binding the data to
  41865. */
  41866. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41867. if (light.shadowEnabled && mesh.receiveShadows) {
  41868. var shadowGenerator = light.getShadowGenerator();
  41869. if (shadowGenerator) {
  41870. shadowGenerator.bindShadowLight(lightIndex, effect);
  41871. }
  41872. }
  41873. };
  41874. /**
  41875. * Binds the light information to the effect.
  41876. * @param light The light containing the generator
  41877. * @param effect The effect we are binding the data to
  41878. * @param lightIndex The light index in the effect used to render
  41879. */
  41880. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41881. light.transferToEffect(effect, lightIndex + "");
  41882. };
  41883. /**
  41884. * Binds the lights information from the scene to the effect for the given mesh.
  41885. * @param scene The scene the lights belongs to
  41886. * @param mesh The mesh we are binding the information to render
  41887. * @param effect The effect we are binding the data to
  41888. * @param defines The generated defines for the effect
  41889. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41890. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41891. */
  41892. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41893. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41894. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41895. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41896. for (var i = 0; i < len; i++) {
  41897. var light = mesh._lightSources[i];
  41898. var iAsString = i.toString();
  41899. var scaledIntensity = light.getScaledIntensity();
  41900. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41901. MaterialHelper.BindLightProperties(light, effect, i);
  41902. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41903. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41904. if (defines["SPECULARTERM"]) {
  41905. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41906. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41907. }
  41908. // Shadows
  41909. if (scene.shadowsEnabled) {
  41910. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41911. }
  41912. light._uniformBuffer.update();
  41913. }
  41914. };
  41915. /**
  41916. * Binds the fog information from the scene to the effect for the given mesh.
  41917. * @param scene The scene the lights belongs to
  41918. * @param mesh The mesh we are binding the information to render
  41919. * @param effect The effect we are binding the data to
  41920. */
  41921. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41922. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41923. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41924. effect.setColor3("vFogColor", scene.fogColor);
  41925. }
  41926. };
  41927. /**
  41928. * Binds the bones information from the mesh to the effect.
  41929. * @param mesh The mesh we are binding the information to render
  41930. * @param effect The effect we are binding the data to
  41931. */
  41932. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41933. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41934. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41935. if (matrices && effect) {
  41936. effect.setMatrices("mBones", matrices);
  41937. }
  41938. }
  41939. };
  41940. /**
  41941. * Binds the morph targets information from the mesh to the effect.
  41942. * @param abstractMesh The mesh we are binding the information to render
  41943. * @param effect The effect we are binding the data to
  41944. */
  41945. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41946. var manager = abstractMesh.morphTargetManager;
  41947. if (!abstractMesh || !manager) {
  41948. return;
  41949. }
  41950. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41951. };
  41952. /**
  41953. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41954. * @param defines The generated defines used in the effect
  41955. * @param effect The effect we are binding the data to
  41956. * @param scene The scene we are willing to render with logarithmic scale for
  41957. */
  41958. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41959. if (defines["LOGARITHMICDEPTH"]) {
  41960. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41961. }
  41962. };
  41963. /**
  41964. * Binds the clip plane information from the scene to the effect.
  41965. * @param scene The scene the clip plane information are extracted from
  41966. * @param effect The effect we are binding the data to
  41967. */
  41968. MaterialHelper.BindClipPlane = function (effect, scene) {
  41969. if (scene.clipPlane) {
  41970. var clipPlane = scene.clipPlane;
  41971. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41972. }
  41973. };
  41974. return MaterialHelper;
  41975. }());
  41976. BABYLON.MaterialHelper = MaterialHelper;
  41977. })(BABYLON || (BABYLON = {}));
  41978. //# sourceMappingURL=babylon.materialHelper.js.map
  41979. "use strict";
  41980. var BABYLON;
  41981. (function (BABYLON) {
  41982. var PushMaterial = /** @class */ (function (_super) {
  41983. __extends(PushMaterial, _super);
  41984. function PushMaterial(name, scene) {
  41985. var _this = _super.call(this, name, scene) || this;
  41986. _this._normalMatrix = new BABYLON.Matrix();
  41987. _this.storeEffectOnSubMeshes = true;
  41988. return _this;
  41989. }
  41990. PushMaterial.prototype.getEffect = function () {
  41991. return this._activeEffect;
  41992. };
  41993. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41994. if (!mesh) {
  41995. return false;
  41996. }
  41997. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41998. return true;
  41999. }
  42000. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42001. };
  42002. /**
  42003. * Binds the given world matrix to the active effect
  42004. *
  42005. * @param world the matrix to bind
  42006. */
  42007. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42008. this._activeEffect.setMatrix("world", world);
  42009. };
  42010. /**
  42011. * Binds the given normal matrix to the active effect
  42012. *
  42013. * @param normalMatrix the matrix to bind
  42014. */
  42015. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42016. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42017. };
  42018. PushMaterial.prototype.bind = function (world, mesh) {
  42019. if (!mesh) {
  42020. return;
  42021. }
  42022. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42023. };
  42024. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42025. if (effect === void 0) { effect = null; }
  42026. _super.prototype._afterBind.call(this, mesh);
  42027. this.getScene()._cachedEffect = effect;
  42028. };
  42029. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42030. if (visibility === void 0) { visibility = 1; }
  42031. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42032. };
  42033. return PushMaterial;
  42034. }(BABYLON.Material));
  42035. BABYLON.PushMaterial = PushMaterial;
  42036. })(BABYLON || (BABYLON = {}));
  42037. //# sourceMappingURL=babylon.pushMaterial.js.map
  42038. "use strict";
  42039. var BABYLON;
  42040. (function (BABYLON) {
  42041. /** @ignore */
  42042. var StandardMaterialDefines = /** @class */ (function (_super) {
  42043. __extends(StandardMaterialDefines, _super);
  42044. function StandardMaterialDefines() {
  42045. var _this = _super.call(this) || this;
  42046. _this.MAINUV1 = false;
  42047. _this.MAINUV2 = false;
  42048. _this.DIFFUSE = false;
  42049. _this.DIFFUSEDIRECTUV = 0;
  42050. _this.AMBIENT = false;
  42051. _this.AMBIENTDIRECTUV = 0;
  42052. _this.OPACITY = false;
  42053. _this.OPACITYDIRECTUV = 0;
  42054. _this.OPACITYRGB = false;
  42055. _this.REFLECTION = false;
  42056. _this.EMISSIVE = false;
  42057. _this.EMISSIVEDIRECTUV = 0;
  42058. _this.SPECULAR = false;
  42059. _this.SPECULARDIRECTUV = 0;
  42060. _this.BUMP = false;
  42061. _this.BUMPDIRECTUV = 0;
  42062. _this.PARALLAX = false;
  42063. _this.PARALLAXOCCLUSION = false;
  42064. _this.SPECULAROVERALPHA = false;
  42065. _this.CLIPPLANE = false;
  42066. _this.ALPHATEST = false;
  42067. _this.DEPTHPREPASS = false;
  42068. _this.ALPHAFROMDIFFUSE = false;
  42069. _this.POINTSIZE = false;
  42070. _this.FOG = false;
  42071. _this.SPECULARTERM = false;
  42072. _this.DIFFUSEFRESNEL = false;
  42073. _this.OPACITYFRESNEL = false;
  42074. _this.REFLECTIONFRESNEL = false;
  42075. _this.REFRACTIONFRESNEL = false;
  42076. _this.EMISSIVEFRESNEL = false;
  42077. _this.FRESNEL = false;
  42078. _this.NORMAL = false;
  42079. _this.UV1 = false;
  42080. _this.UV2 = false;
  42081. _this.VERTEXCOLOR = false;
  42082. _this.VERTEXALPHA = false;
  42083. _this.NUM_BONE_INFLUENCERS = 0;
  42084. _this.BonesPerMesh = 0;
  42085. _this.INSTANCES = false;
  42086. _this.GLOSSINESS = false;
  42087. _this.ROUGHNESS = false;
  42088. _this.EMISSIVEASILLUMINATION = false;
  42089. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42090. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42091. _this.LIGHTMAP = false;
  42092. _this.LIGHTMAPDIRECTUV = 0;
  42093. _this.OBJECTSPACE_NORMALMAP = false;
  42094. _this.USELIGHTMAPASSHADOWMAP = false;
  42095. _this.REFLECTIONMAP_3D = false;
  42096. _this.REFLECTIONMAP_SPHERICAL = false;
  42097. _this.REFLECTIONMAP_PLANAR = false;
  42098. _this.REFLECTIONMAP_CUBIC = false;
  42099. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42100. _this.REFLECTIONMAP_PROJECTION = false;
  42101. _this.REFLECTIONMAP_SKYBOX = false;
  42102. _this.REFLECTIONMAP_EXPLICIT = false;
  42103. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42104. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42105. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42106. _this.INVERTCUBICMAP = false;
  42107. _this.LOGARITHMICDEPTH = false;
  42108. _this.REFRACTION = false;
  42109. _this.REFRACTIONMAP_3D = false;
  42110. _this.REFLECTIONOVERALPHA = false;
  42111. _this.TWOSIDEDLIGHTING = false;
  42112. _this.SHADOWFLOAT = false;
  42113. _this.MORPHTARGETS = false;
  42114. _this.MORPHTARGETS_NORMAL = false;
  42115. _this.MORPHTARGETS_TANGENT = false;
  42116. _this.NUM_MORPH_INFLUENCERS = 0;
  42117. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42118. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42119. _this.IMAGEPROCESSING = false;
  42120. _this.VIGNETTE = false;
  42121. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42122. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42123. _this.TONEMAPPING = false;
  42124. _this.CONTRAST = false;
  42125. _this.COLORCURVES = false;
  42126. _this.COLORGRADING = false;
  42127. _this.COLORGRADING3D = false;
  42128. _this.SAMPLER3DGREENDEPTH = false;
  42129. _this.SAMPLER3DBGRMAP = false;
  42130. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42131. /**
  42132. * If the reflection texture on this material is in linear color space
  42133. * @ignore
  42134. */
  42135. _this.IS_REFLECTION_LINEAR = false;
  42136. /**
  42137. * If the refraction texture on this material is in linear color space
  42138. * @ignore
  42139. */
  42140. _this.IS_REFRACTION_LINEAR = false;
  42141. _this.EXPOSURE = false;
  42142. _this.rebuild();
  42143. return _this;
  42144. }
  42145. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42146. var modes = [
  42147. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42148. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42149. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42150. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42151. ];
  42152. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42153. var mode = modes_1[_i];
  42154. this[mode] = (mode === modeToEnable);
  42155. }
  42156. };
  42157. return StandardMaterialDefines;
  42158. }(BABYLON.MaterialDefines));
  42159. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42160. var StandardMaterial = /** @class */ (function (_super) {
  42161. __extends(StandardMaterial, _super);
  42162. function StandardMaterial(name, scene) {
  42163. var _this = _super.call(this, name, scene) || this;
  42164. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42165. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42166. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42167. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42168. _this.specularPower = 64;
  42169. _this._useAlphaFromDiffuseTexture = false;
  42170. _this._useEmissiveAsIllumination = false;
  42171. _this._linkEmissiveWithDiffuse = false;
  42172. _this._useSpecularOverAlpha = false;
  42173. _this._useReflectionOverAlpha = false;
  42174. _this._disableLighting = false;
  42175. _this._useObjectSpaceNormalMap = false;
  42176. _this._useParallax = false;
  42177. _this._useParallaxOcclusion = false;
  42178. _this.parallaxScaleBias = 0.05;
  42179. _this._roughness = 0;
  42180. _this.indexOfRefraction = 0.98;
  42181. _this.invertRefractionY = true;
  42182. _this._useLightmapAsShadowmap = false;
  42183. _this._useReflectionFresnelFromSpecular = false;
  42184. _this._useGlossinessFromSpecularMapAlpha = false;
  42185. _this._maxSimultaneousLights = 4;
  42186. /**
  42187. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42188. */
  42189. _this._invertNormalMapX = false;
  42190. /**
  42191. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42192. */
  42193. _this._invertNormalMapY = false;
  42194. /**
  42195. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42196. */
  42197. _this._twoSidedLighting = false;
  42198. _this._renderTargets = new BABYLON.SmartArray(16);
  42199. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42200. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42201. // Setup the default processing configuration to the scene.
  42202. _this._attachImageProcessingConfiguration(null);
  42203. _this.getRenderTargetTextures = function () {
  42204. _this._renderTargets.reset();
  42205. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42206. _this._renderTargets.push(_this._reflectionTexture);
  42207. }
  42208. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42209. _this._renderTargets.push(_this._refractionTexture);
  42210. }
  42211. return _this._renderTargets;
  42212. };
  42213. return _this;
  42214. }
  42215. ;
  42216. ;
  42217. ;
  42218. ;
  42219. ;
  42220. ;
  42221. ;
  42222. ;
  42223. ;
  42224. ;
  42225. ;
  42226. ;
  42227. ;
  42228. ;
  42229. ;
  42230. ;
  42231. ;
  42232. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42233. /**
  42234. * Gets the image processing configuration used either in this material.
  42235. */
  42236. get: function () {
  42237. return this._imageProcessingConfiguration;
  42238. },
  42239. /**
  42240. * Sets the Default image processing configuration used either in the this material.
  42241. *
  42242. * If sets to null, the scene one is in use.
  42243. */
  42244. set: function (value) {
  42245. this._attachImageProcessingConfiguration(value);
  42246. // Ensure the effect will be rebuilt.
  42247. this._markAllSubMeshesAsTexturesDirty();
  42248. },
  42249. enumerable: true,
  42250. configurable: true
  42251. });
  42252. /**
  42253. * Attaches a new image processing configuration to the Standard Material.
  42254. * @param configuration
  42255. */
  42256. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42257. var _this = this;
  42258. if (configuration === this._imageProcessingConfiguration) {
  42259. return;
  42260. }
  42261. // Detaches observer.
  42262. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42263. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42264. }
  42265. // Pick the scene configuration if needed.
  42266. if (!configuration) {
  42267. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42268. }
  42269. else {
  42270. this._imageProcessingConfiguration = configuration;
  42271. }
  42272. // Attaches observer.
  42273. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42274. _this._markAllSubMeshesAsImageProcessingDirty();
  42275. });
  42276. };
  42277. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42278. /**
  42279. * Gets wether the color curves effect is enabled.
  42280. */
  42281. get: function () {
  42282. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42283. },
  42284. /**
  42285. * Sets wether the color curves effect is enabled.
  42286. */
  42287. set: function (value) {
  42288. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42289. },
  42290. enumerable: true,
  42291. configurable: true
  42292. });
  42293. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42294. /**
  42295. * Gets wether the color grading effect is enabled.
  42296. */
  42297. get: function () {
  42298. return this.imageProcessingConfiguration.colorGradingEnabled;
  42299. },
  42300. /**
  42301. * Gets wether the color grading effect is enabled.
  42302. */
  42303. set: function (value) {
  42304. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42305. },
  42306. enumerable: true,
  42307. configurable: true
  42308. });
  42309. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42310. /**
  42311. * Gets wether tonemapping is enabled or not.
  42312. */
  42313. get: function () {
  42314. return this._imageProcessingConfiguration.toneMappingEnabled;
  42315. },
  42316. /**
  42317. * Sets wether tonemapping is enabled or not
  42318. */
  42319. set: function (value) {
  42320. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42321. },
  42322. enumerable: true,
  42323. configurable: true
  42324. });
  42325. ;
  42326. ;
  42327. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42328. /**
  42329. * The camera exposure used on this material.
  42330. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42331. * This corresponds to a photographic exposure.
  42332. */
  42333. get: function () {
  42334. return this._imageProcessingConfiguration.exposure;
  42335. },
  42336. /**
  42337. * The camera exposure used on this material.
  42338. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42339. * This corresponds to a photographic exposure.
  42340. */
  42341. set: function (value) {
  42342. this._imageProcessingConfiguration.exposure = value;
  42343. },
  42344. enumerable: true,
  42345. configurable: true
  42346. });
  42347. ;
  42348. ;
  42349. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42350. /**
  42351. * Gets The camera contrast used on this material.
  42352. */
  42353. get: function () {
  42354. return this._imageProcessingConfiguration.contrast;
  42355. },
  42356. /**
  42357. * Sets The camera contrast used on this material.
  42358. */
  42359. set: function (value) {
  42360. this._imageProcessingConfiguration.contrast = value;
  42361. },
  42362. enumerable: true,
  42363. configurable: true
  42364. });
  42365. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42366. /**
  42367. * Gets the Color Grading 2D Lookup Texture.
  42368. */
  42369. get: function () {
  42370. return this._imageProcessingConfiguration.colorGradingTexture;
  42371. },
  42372. /**
  42373. * Sets the Color Grading 2D Lookup Texture.
  42374. */
  42375. set: function (value) {
  42376. this._imageProcessingConfiguration.colorGradingTexture = value;
  42377. },
  42378. enumerable: true,
  42379. configurable: true
  42380. });
  42381. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42382. /**
  42383. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42384. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42385. * 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;
  42386. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42387. */
  42388. get: function () {
  42389. return this._imageProcessingConfiguration.colorCurves;
  42390. },
  42391. /**
  42392. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42393. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42394. * 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;
  42395. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42396. */
  42397. set: function (value) {
  42398. this._imageProcessingConfiguration.colorCurves = value;
  42399. },
  42400. enumerable: true,
  42401. configurable: true
  42402. });
  42403. StandardMaterial.prototype.getClassName = function () {
  42404. return "StandardMaterial";
  42405. };
  42406. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42407. get: function () {
  42408. return this._useLogarithmicDepth;
  42409. },
  42410. set: function (value) {
  42411. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42412. this._markAllSubMeshesAsMiscDirty();
  42413. },
  42414. enumerable: true,
  42415. configurable: true
  42416. });
  42417. StandardMaterial.prototype.needAlphaBlending = function () {
  42418. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42419. };
  42420. StandardMaterial.prototype.needAlphaTesting = function () {
  42421. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42422. };
  42423. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42424. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42425. };
  42426. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42427. return this._diffuseTexture;
  42428. };
  42429. /**
  42430. * Child classes can use it to update shaders
  42431. */
  42432. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42433. if (useInstances === void 0) { useInstances = false; }
  42434. if (subMesh.effect && this.isFrozen) {
  42435. if (this._wasPreviouslyReady && subMesh.effect) {
  42436. return true;
  42437. }
  42438. }
  42439. if (!subMesh._materialDefines) {
  42440. subMesh._materialDefines = new StandardMaterialDefines();
  42441. }
  42442. var scene = this.getScene();
  42443. var defines = subMesh._materialDefines;
  42444. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42445. if (defines._renderId === scene.getRenderId()) {
  42446. return true;
  42447. }
  42448. }
  42449. var engine = scene.getEngine();
  42450. // Lights
  42451. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42452. // Textures
  42453. if (defines._areTexturesDirty) {
  42454. defines._needUVs = false;
  42455. defines.MAINUV1 = false;
  42456. defines.MAINUV2 = false;
  42457. if (scene.texturesEnabled) {
  42458. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42459. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42460. return false;
  42461. }
  42462. else {
  42463. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42464. }
  42465. }
  42466. else {
  42467. defines.DIFFUSE = false;
  42468. }
  42469. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42470. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42471. return false;
  42472. }
  42473. else {
  42474. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42475. }
  42476. }
  42477. else {
  42478. defines.AMBIENT = false;
  42479. }
  42480. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42481. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42482. return false;
  42483. }
  42484. else {
  42485. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42486. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42487. }
  42488. }
  42489. else {
  42490. defines.OPACITY = false;
  42491. }
  42492. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42493. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42494. return false;
  42495. }
  42496. else {
  42497. defines._needNormals = true;
  42498. defines.REFLECTION = true;
  42499. defines.ROUGHNESS = (this._roughness > 0);
  42500. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42501. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42502. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42503. switch (this._reflectionTexture.coordinatesMode) {
  42504. case BABYLON.Texture.CUBIC_MODE:
  42505. case BABYLON.Texture.INVCUBIC_MODE:
  42506. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42507. break;
  42508. case BABYLON.Texture.EXPLICIT_MODE:
  42509. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42510. break;
  42511. case BABYLON.Texture.PLANAR_MODE:
  42512. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42513. break;
  42514. case BABYLON.Texture.PROJECTION_MODE:
  42515. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42516. break;
  42517. case BABYLON.Texture.SKYBOX_MODE:
  42518. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42519. break;
  42520. case BABYLON.Texture.SPHERICAL_MODE:
  42521. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42522. break;
  42523. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42524. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42525. break;
  42526. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42527. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42528. break;
  42529. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42530. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42531. break;
  42532. }
  42533. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42534. }
  42535. }
  42536. else {
  42537. defines.REFLECTION = false;
  42538. }
  42539. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42540. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42541. return false;
  42542. }
  42543. else {
  42544. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42545. }
  42546. }
  42547. else {
  42548. defines.EMISSIVE = false;
  42549. }
  42550. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42551. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42552. return false;
  42553. }
  42554. else {
  42555. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42556. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42557. }
  42558. }
  42559. else {
  42560. defines.LIGHTMAP = false;
  42561. }
  42562. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42563. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42564. return false;
  42565. }
  42566. else {
  42567. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42568. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42569. }
  42570. }
  42571. else {
  42572. defines.SPECULAR = false;
  42573. }
  42574. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42575. // Bump texure can not be not blocking.
  42576. if (!this._bumpTexture.isReady()) {
  42577. return false;
  42578. }
  42579. else {
  42580. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42581. defines.PARALLAX = this._useParallax;
  42582. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42583. }
  42584. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42585. }
  42586. else {
  42587. defines.BUMP = false;
  42588. }
  42589. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42590. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42591. return false;
  42592. }
  42593. else {
  42594. defines._needUVs = true;
  42595. defines.REFRACTION = true;
  42596. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42597. }
  42598. }
  42599. else {
  42600. defines.REFRACTION = false;
  42601. }
  42602. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42603. }
  42604. else {
  42605. defines.DIFFUSE = false;
  42606. defines.AMBIENT = false;
  42607. defines.OPACITY = false;
  42608. defines.REFLECTION = false;
  42609. defines.EMISSIVE = false;
  42610. defines.LIGHTMAP = false;
  42611. defines.BUMP = false;
  42612. defines.REFRACTION = false;
  42613. }
  42614. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42615. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42616. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42617. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42618. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42619. }
  42620. if (defines._areImageProcessingDirty) {
  42621. if (!this._imageProcessingConfiguration.isReady()) {
  42622. return false;
  42623. }
  42624. this._imageProcessingConfiguration.prepareDefines(defines);
  42625. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42626. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42627. }
  42628. if (defines._areFresnelDirty) {
  42629. if (StandardMaterial.FresnelEnabled) {
  42630. // Fresnel
  42631. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42632. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42633. this._reflectionFresnelParameters) {
  42634. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42635. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42636. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42637. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42638. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42639. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42640. defines._needNormals = true;
  42641. defines.FRESNEL = true;
  42642. }
  42643. }
  42644. else {
  42645. defines.FRESNEL = false;
  42646. }
  42647. }
  42648. // Misc.
  42649. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42650. // Attribs
  42651. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42652. // Values that need to be evaluated on every frame
  42653. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42654. // Get correct effect
  42655. if (defines.isDirty) {
  42656. defines.markAsProcessed();
  42657. scene.resetCachedMaterial();
  42658. // Fallbacks
  42659. var fallbacks = new BABYLON.EffectFallbacks();
  42660. if (defines.REFLECTION) {
  42661. fallbacks.addFallback(0, "REFLECTION");
  42662. }
  42663. if (defines.SPECULAR) {
  42664. fallbacks.addFallback(0, "SPECULAR");
  42665. }
  42666. if (defines.BUMP) {
  42667. fallbacks.addFallback(0, "BUMP");
  42668. }
  42669. if (defines.PARALLAX) {
  42670. fallbacks.addFallback(1, "PARALLAX");
  42671. }
  42672. if (defines.PARALLAXOCCLUSION) {
  42673. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42674. }
  42675. if (defines.SPECULAROVERALPHA) {
  42676. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42677. }
  42678. if (defines.FOG) {
  42679. fallbacks.addFallback(1, "FOG");
  42680. }
  42681. if (defines.POINTSIZE) {
  42682. fallbacks.addFallback(0, "POINTSIZE");
  42683. }
  42684. if (defines.LOGARITHMICDEPTH) {
  42685. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42686. }
  42687. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42688. if (defines.SPECULARTERM) {
  42689. fallbacks.addFallback(0, "SPECULARTERM");
  42690. }
  42691. if (defines.DIFFUSEFRESNEL) {
  42692. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42693. }
  42694. if (defines.OPACITYFRESNEL) {
  42695. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42696. }
  42697. if (defines.REFLECTIONFRESNEL) {
  42698. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42699. }
  42700. if (defines.EMISSIVEFRESNEL) {
  42701. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42702. }
  42703. if (defines.FRESNEL) {
  42704. fallbacks.addFallback(4, "FRESNEL");
  42705. }
  42706. //Attributes
  42707. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42708. if (defines.NORMAL) {
  42709. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42710. }
  42711. if (defines.UV1) {
  42712. attribs.push(BABYLON.VertexBuffer.UVKind);
  42713. }
  42714. if (defines.UV2) {
  42715. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42716. }
  42717. if (defines.VERTEXCOLOR) {
  42718. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42719. }
  42720. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42721. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42722. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42723. var shaderName = "default";
  42724. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42725. "vFogInfos", "vFogColor", "pointSize",
  42726. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42727. "mBones",
  42728. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42729. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42730. "vReflectionPosition", "vReflectionSize",
  42731. "logarithmicDepthConstant", "vTangentSpaceParams"
  42732. ];
  42733. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42734. var uniformBuffers = ["Material", "Scene"];
  42735. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42736. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42737. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42738. uniformsNames: uniforms,
  42739. uniformBuffersNames: uniformBuffers,
  42740. samplers: samplers,
  42741. defines: defines,
  42742. maxSimultaneousLights: this._maxSimultaneousLights
  42743. });
  42744. if (this.customShaderNameResolve) {
  42745. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42746. }
  42747. var join = defines.toString();
  42748. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42749. attributes: attribs,
  42750. uniformsNames: uniforms,
  42751. uniformBuffersNames: uniformBuffers,
  42752. samplers: samplers,
  42753. defines: join,
  42754. fallbacks: fallbacks,
  42755. onCompiled: this.onCompiled,
  42756. onError: this.onError,
  42757. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42758. }, engine), defines);
  42759. this.buildUniformLayout();
  42760. }
  42761. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42762. return false;
  42763. }
  42764. defines._renderId = scene.getRenderId();
  42765. this._wasPreviouslyReady = true;
  42766. return true;
  42767. };
  42768. StandardMaterial.prototype.buildUniformLayout = function () {
  42769. // Order is important !
  42770. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42771. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42772. this._uniformBuffer.addUniform("opacityParts", 4);
  42773. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42774. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42775. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42776. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42777. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42778. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42779. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42780. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42781. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42782. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42783. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42784. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42785. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42786. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42787. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42788. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42789. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42790. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42791. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42792. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42793. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42794. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42795. this._uniformBuffer.addUniform("specularMatrix", 16);
  42796. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42797. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42798. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42799. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42800. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42801. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42802. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42803. this._uniformBuffer.addUniform("pointSize", 1);
  42804. this._uniformBuffer.create();
  42805. };
  42806. StandardMaterial.prototype.unbind = function () {
  42807. if (this._activeEffect) {
  42808. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42809. this._activeEffect.setTexture("reflection2DSampler", null);
  42810. }
  42811. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42812. this._activeEffect.setTexture("refraction2DSampler", null);
  42813. }
  42814. }
  42815. _super.prototype.unbind.call(this);
  42816. };
  42817. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42818. var scene = this.getScene();
  42819. var defines = subMesh._materialDefines;
  42820. if (!defines) {
  42821. return;
  42822. }
  42823. var effect = subMesh.effect;
  42824. if (!effect) {
  42825. return;
  42826. }
  42827. this._activeEffect = effect;
  42828. // Matrices
  42829. this.bindOnlyWorldMatrix(world);
  42830. // Normal Matrix
  42831. if (defines.OBJECTSPACE_NORMALMAP) {
  42832. world.toNormalMatrix(this._normalMatrix);
  42833. this.bindOnlyNormalMatrix(this._normalMatrix);
  42834. }
  42835. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42836. // Bones
  42837. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42838. if (mustRebind) {
  42839. this._uniformBuffer.bindToEffect(effect, "Material");
  42840. this.bindViewProjection(effect);
  42841. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42842. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42843. // Fresnel
  42844. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42845. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42846. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42847. }
  42848. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42849. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42850. }
  42851. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42852. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42853. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42854. }
  42855. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42856. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42857. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42858. }
  42859. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42860. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42861. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42862. }
  42863. }
  42864. // Textures
  42865. if (scene.texturesEnabled) {
  42866. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42867. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42868. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42869. }
  42870. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42871. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42872. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42873. }
  42874. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42875. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42876. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42877. }
  42878. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42879. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42880. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42881. if (this._reflectionTexture.boundingBoxSize) {
  42882. var cubeTexture = this._reflectionTexture;
  42883. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42884. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42885. }
  42886. }
  42887. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42888. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42889. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42890. }
  42891. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42892. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42893. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42894. }
  42895. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42896. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42897. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42898. }
  42899. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42900. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42901. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42902. if (scene._mirroredCameraPosition) {
  42903. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42904. }
  42905. else {
  42906. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42907. }
  42908. }
  42909. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42910. var depth = 1.0;
  42911. if (!this._refractionTexture.isCube) {
  42912. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42913. if (this._refractionTexture.depth) {
  42914. depth = this._refractionTexture.depth;
  42915. }
  42916. }
  42917. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42918. }
  42919. }
  42920. // Point size
  42921. if (this.pointsCloud) {
  42922. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42923. }
  42924. if (defines.SPECULARTERM) {
  42925. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42926. }
  42927. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42928. // Diffuse
  42929. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42930. }
  42931. // Textures
  42932. if (scene.texturesEnabled) {
  42933. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42934. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42935. }
  42936. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42937. effect.setTexture("ambientSampler", this._ambientTexture);
  42938. }
  42939. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42940. effect.setTexture("opacitySampler", this._opacityTexture);
  42941. }
  42942. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42943. if (this._reflectionTexture.isCube) {
  42944. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42945. }
  42946. else {
  42947. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42948. }
  42949. }
  42950. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42951. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42952. }
  42953. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42954. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42955. }
  42956. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42957. effect.setTexture("specularSampler", this._specularTexture);
  42958. }
  42959. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42960. effect.setTexture("bumpSampler", this._bumpTexture);
  42961. }
  42962. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42963. var depth = 1.0;
  42964. if (this._refractionTexture.isCube) {
  42965. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42966. }
  42967. else {
  42968. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42969. }
  42970. }
  42971. }
  42972. // Clip plane
  42973. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42974. // Colors
  42975. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42976. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42977. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42978. }
  42979. if (mustRebind || !this.isFrozen) {
  42980. // Lights
  42981. if (scene.lightsEnabled && !this._disableLighting) {
  42982. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42983. }
  42984. // View
  42985. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42986. this.bindView(effect);
  42987. }
  42988. // Fog
  42989. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42990. // Morph targets
  42991. if (defines.NUM_MORPH_INFLUENCERS) {
  42992. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42993. }
  42994. // Log. depth
  42995. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42996. // image processing
  42997. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  42998. this._imageProcessingConfiguration.bind(this._activeEffect);
  42999. }
  43000. }
  43001. this._uniformBuffer.update();
  43002. this._afterBind(mesh, this._activeEffect);
  43003. };
  43004. StandardMaterial.prototype.getAnimatables = function () {
  43005. var results = [];
  43006. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43007. results.push(this._diffuseTexture);
  43008. }
  43009. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43010. results.push(this._ambientTexture);
  43011. }
  43012. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43013. results.push(this._opacityTexture);
  43014. }
  43015. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43016. results.push(this._reflectionTexture);
  43017. }
  43018. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43019. results.push(this._emissiveTexture);
  43020. }
  43021. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43022. results.push(this._specularTexture);
  43023. }
  43024. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43025. results.push(this._bumpTexture);
  43026. }
  43027. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43028. results.push(this._lightmapTexture);
  43029. }
  43030. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43031. results.push(this._refractionTexture);
  43032. }
  43033. return results;
  43034. };
  43035. StandardMaterial.prototype.getActiveTextures = function () {
  43036. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43037. if (this._diffuseTexture) {
  43038. activeTextures.push(this._diffuseTexture);
  43039. }
  43040. if (this._ambientTexture) {
  43041. activeTextures.push(this._ambientTexture);
  43042. }
  43043. if (this._opacityTexture) {
  43044. activeTextures.push(this._opacityTexture);
  43045. }
  43046. if (this._reflectionTexture) {
  43047. activeTextures.push(this._reflectionTexture);
  43048. }
  43049. if (this._emissiveTexture) {
  43050. activeTextures.push(this._emissiveTexture);
  43051. }
  43052. if (this._specularTexture) {
  43053. activeTextures.push(this._specularTexture);
  43054. }
  43055. if (this._bumpTexture) {
  43056. activeTextures.push(this._bumpTexture);
  43057. }
  43058. if (this._lightmapTexture) {
  43059. activeTextures.push(this._lightmapTexture);
  43060. }
  43061. if (this._refractionTexture) {
  43062. activeTextures.push(this._refractionTexture);
  43063. }
  43064. return activeTextures;
  43065. };
  43066. StandardMaterial.prototype.hasTexture = function (texture) {
  43067. if (_super.prototype.hasTexture.call(this, texture)) {
  43068. return true;
  43069. }
  43070. if (this._diffuseTexture === texture) {
  43071. return true;
  43072. }
  43073. if (this._ambientTexture === texture) {
  43074. return true;
  43075. }
  43076. if (this._opacityTexture === texture) {
  43077. return true;
  43078. }
  43079. if (this._reflectionTexture === texture) {
  43080. return true;
  43081. }
  43082. if (this._emissiveTexture === texture) {
  43083. return true;
  43084. }
  43085. if (this._specularTexture === texture) {
  43086. return true;
  43087. }
  43088. if (this._bumpTexture === texture) {
  43089. return true;
  43090. }
  43091. if (this._lightmapTexture === texture) {
  43092. return true;
  43093. }
  43094. if (this._refractionTexture === texture) {
  43095. return true;
  43096. }
  43097. return false;
  43098. };
  43099. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43100. if (forceDisposeTextures) {
  43101. if (this._diffuseTexture) {
  43102. this._diffuseTexture.dispose();
  43103. }
  43104. if (this._ambientTexture) {
  43105. this._ambientTexture.dispose();
  43106. }
  43107. if (this._opacityTexture) {
  43108. this._opacityTexture.dispose();
  43109. }
  43110. if (this._reflectionTexture) {
  43111. this._reflectionTexture.dispose();
  43112. }
  43113. if (this._emissiveTexture) {
  43114. this._emissiveTexture.dispose();
  43115. }
  43116. if (this._specularTexture) {
  43117. this._specularTexture.dispose();
  43118. }
  43119. if (this._bumpTexture) {
  43120. this._bumpTexture.dispose();
  43121. }
  43122. if (this._lightmapTexture) {
  43123. this._lightmapTexture.dispose();
  43124. }
  43125. if (this._refractionTexture) {
  43126. this._refractionTexture.dispose();
  43127. }
  43128. }
  43129. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43130. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43131. }
  43132. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43133. };
  43134. StandardMaterial.prototype.clone = function (name) {
  43135. var _this = this;
  43136. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43137. result.name = name;
  43138. result.id = name;
  43139. return result;
  43140. };
  43141. StandardMaterial.prototype.serialize = function () {
  43142. return BABYLON.SerializationHelper.Serialize(this);
  43143. };
  43144. // Statics
  43145. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43146. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43147. };
  43148. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43149. get: function () {
  43150. return StandardMaterial._DiffuseTextureEnabled;
  43151. },
  43152. set: function (value) {
  43153. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43154. return;
  43155. }
  43156. StandardMaterial._DiffuseTextureEnabled = value;
  43157. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43158. },
  43159. enumerable: true,
  43160. configurable: true
  43161. });
  43162. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43163. get: function () {
  43164. return StandardMaterial._AmbientTextureEnabled;
  43165. },
  43166. set: function (value) {
  43167. if (StandardMaterial._AmbientTextureEnabled === value) {
  43168. return;
  43169. }
  43170. StandardMaterial._AmbientTextureEnabled = value;
  43171. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43172. },
  43173. enumerable: true,
  43174. configurable: true
  43175. });
  43176. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43177. get: function () {
  43178. return StandardMaterial._OpacityTextureEnabled;
  43179. },
  43180. set: function (value) {
  43181. if (StandardMaterial._OpacityTextureEnabled === value) {
  43182. return;
  43183. }
  43184. StandardMaterial._OpacityTextureEnabled = value;
  43185. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43186. },
  43187. enumerable: true,
  43188. configurable: true
  43189. });
  43190. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43191. get: function () {
  43192. return StandardMaterial._ReflectionTextureEnabled;
  43193. },
  43194. set: function (value) {
  43195. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43196. return;
  43197. }
  43198. StandardMaterial._ReflectionTextureEnabled = value;
  43199. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43200. },
  43201. enumerable: true,
  43202. configurable: true
  43203. });
  43204. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43205. get: function () {
  43206. return StandardMaterial._EmissiveTextureEnabled;
  43207. },
  43208. set: function (value) {
  43209. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43210. return;
  43211. }
  43212. StandardMaterial._EmissiveTextureEnabled = value;
  43213. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43214. },
  43215. enumerable: true,
  43216. configurable: true
  43217. });
  43218. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43219. get: function () {
  43220. return StandardMaterial._SpecularTextureEnabled;
  43221. },
  43222. set: function (value) {
  43223. if (StandardMaterial._SpecularTextureEnabled === value) {
  43224. return;
  43225. }
  43226. StandardMaterial._SpecularTextureEnabled = value;
  43227. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43228. },
  43229. enumerable: true,
  43230. configurable: true
  43231. });
  43232. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43233. get: function () {
  43234. return StandardMaterial._BumpTextureEnabled;
  43235. },
  43236. set: function (value) {
  43237. if (StandardMaterial._BumpTextureEnabled === value) {
  43238. return;
  43239. }
  43240. StandardMaterial._BumpTextureEnabled = value;
  43241. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43242. },
  43243. enumerable: true,
  43244. configurable: true
  43245. });
  43246. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43247. get: function () {
  43248. return StandardMaterial._LightmapTextureEnabled;
  43249. },
  43250. set: function (value) {
  43251. if (StandardMaterial._LightmapTextureEnabled === value) {
  43252. return;
  43253. }
  43254. StandardMaterial._LightmapTextureEnabled = value;
  43255. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43256. },
  43257. enumerable: true,
  43258. configurable: true
  43259. });
  43260. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43261. get: function () {
  43262. return StandardMaterial._RefractionTextureEnabled;
  43263. },
  43264. set: function (value) {
  43265. if (StandardMaterial._RefractionTextureEnabled === value) {
  43266. return;
  43267. }
  43268. StandardMaterial._RefractionTextureEnabled = value;
  43269. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43270. },
  43271. enumerable: true,
  43272. configurable: true
  43273. });
  43274. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43275. get: function () {
  43276. return StandardMaterial._ColorGradingTextureEnabled;
  43277. },
  43278. set: function (value) {
  43279. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43280. return;
  43281. }
  43282. StandardMaterial._ColorGradingTextureEnabled = value;
  43283. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43284. },
  43285. enumerable: true,
  43286. configurable: true
  43287. });
  43288. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43289. get: function () {
  43290. return StandardMaterial._FresnelEnabled;
  43291. },
  43292. set: function (value) {
  43293. if (StandardMaterial._FresnelEnabled === value) {
  43294. return;
  43295. }
  43296. StandardMaterial._FresnelEnabled = value;
  43297. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43298. },
  43299. enumerable: true,
  43300. configurable: true
  43301. });
  43302. // Flags used to enable or disable a type of texture for all Standard Materials
  43303. StandardMaterial._DiffuseTextureEnabled = true;
  43304. StandardMaterial._AmbientTextureEnabled = true;
  43305. StandardMaterial._OpacityTextureEnabled = true;
  43306. StandardMaterial._ReflectionTextureEnabled = true;
  43307. StandardMaterial._EmissiveTextureEnabled = true;
  43308. StandardMaterial._SpecularTextureEnabled = true;
  43309. StandardMaterial._BumpTextureEnabled = true;
  43310. StandardMaterial._LightmapTextureEnabled = true;
  43311. StandardMaterial._RefractionTextureEnabled = true;
  43312. StandardMaterial._ColorGradingTextureEnabled = true;
  43313. StandardMaterial._FresnelEnabled = true;
  43314. __decorate([
  43315. BABYLON.serializeAsTexture("diffuseTexture")
  43316. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43317. __decorate([
  43318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43319. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43320. __decorate([
  43321. BABYLON.serializeAsTexture("ambientTexture")
  43322. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43323. __decorate([
  43324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43325. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43326. __decorate([
  43327. BABYLON.serializeAsTexture("opacityTexture")
  43328. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43329. __decorate([
  43330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43331. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43332. __decorate([
  43333. BABYLON.serializeAsTexture("reflectionTexture")
  43334. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43335. __decorate([
  43336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43337. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43338. __decorate([
  43339. BABYLON.serializeAsTexture("emissiveTexture")
  43340. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43341. __decorate([
  43342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43343. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43344. __decorate([
  43345. BABYLON.serializeAsTexture("specularTexture")
  43346. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43347. __decorate([
  43348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43349. ], StandardMaterial.prototype, "specularTexture", void 0);
  43350. __decorate([
  43351. BABYLON.serializeAsTexture("bumpTexture")
  43352. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43353. __decorate([
  43354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43355. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43356. __decorate([
  43357. BABYLON.serializeAsTexture("lightmapTexture")
  43358. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43359. __decorate([
  43360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43361. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43362. __decorate([
  43363. BABYLON.serializeAsTexture("refractionTexture")
  43364. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43365. __decorate([
  43366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43367. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43368. __decorate([
  43369. BABYLON.serializeAsColor3("ambient")
  43370. ], StandardMaterial.prototype, "ambientColor", void 0);
  43371. __decorate([
  43372. BABYLON.serializeAsColor3("diffuse")
  43373. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43374. __decorate([
  43375. BABYLON.serializeAsColor3("specular")
  43376. ], StandardMaterial.prototype, "specularColor", void 0);
  43377. __decorate([
  43378. BABYLON.serializeAsColor3("emissive")
  43379. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43380. __decorate([
  43381. BABYLON.serialize()
  43382. ], StandardMaterial.prototype, "specularPower", void 0);
  43383. __decorate([
  43384. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43385. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43386. __decorate([
  43387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43388. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43389. __decorate([
  43390. BABYLON.serialize("useEmissiveAsIllumination")
  43391. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43392. __decorate([
  43393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43394. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43395. __decorate([
  43396. BABYLON.serialize("linkEmissiveWithDiffuse")
  43397. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43398. __decorate([
  43399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43400. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43401. __decorate([
  43402. BABYLON.serialize("useSpecularOverAlpha")
  43403. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43404. __decorate([
  43405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43406. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43407. __decorate([
  43408. BABYLON.serialize("useReflectionOverAlpha")
  43409. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43410. __decorate([
  43411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43412. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43413. __decorate([
  43414. BABYLON.serialize("disableLighting")
  43415. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43416. __decorate([
  43417. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43418. ], StandardMaterial.prototype, "disableLighting", void 0);
  43419. __decorate([
  43420. BABYLON.serialize("useObjectSpaceNormalMap")
  43421. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43422. __decorate([
  43423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43424. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43425. __decorate([
  43426. BABYLON.serialize("useParallax")
  43427. ], StandardMaterial.prototype, "_useParallax", void 0);
  43428. __decorate([
  43429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43430. ], StandardMaterial.prototype, "useParallax", void 0);
  43431. __decorate([
  43432. BABYLON.serialize("useParallaxOcclusion")
  43433. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43434. __decorate([
  43435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43436. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43437. __decorate([
  43438. BABYLON.serialize()
  43439. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43440. __decorate([
  43441. BABYLON.serialize("roughness")
  43442. ], StandardMaterial.prototype, "_roughness", void 0);
  43443. __decorate([
  43444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43445. ], StandardMaterial.prototype, "roughness", void 0);
  43446. __decorate([
  43447. BABYLON.serialize()
  43448. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43449. __decorate([
  43450. BABYLON.serialize()
  43451. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43452. __decorate([
  43453. BABYLON.serialize("useLightmapAsShadowmap")
  43454. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43455. __decorate([
  43456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43457. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43458. __decorate([
  43459. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43460. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43461. __decorate([
  43462. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43463. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43464. __decorate([
  43465. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43466. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43467. __decorate([
  43468. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43469. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43470. __decorate([
  43471. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43472. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43473. __decorate([
  43474. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43475. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43476. __decorate([
  43477. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43478. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43479. __decorate([
  43480. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43481. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43482. __decorate([
  43483. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43484. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43485. __decorate([
  43486. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43487. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43488. __decorate([
  43489. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43490. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43491. __decorate([
  43492. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43493. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43494. __decorate([
  43495. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43496. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43497. __decorate([
  43498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43499. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43500. __decorate([
  43501. BABYLON.serialize("maxSimultaneousLights")
  43502. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43503. __decorate([
  43504. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43505. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43506. __decorate([
  43507. BABYLON.serialize("invertNormalMapX")
  43508. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43509. __decorate([
  43510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43511. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43512. __decorate([
  43513. BABYLON.serialize("invertNormalMapY")
  43514. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43515. __decorate([
  43516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43517. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43518. __decorate([
  43519. BABYLON.serialize("twoSidedLighting")
  43520. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43521. __decorate([
  43522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43523. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43524. __decorate([
  43525. BABYLON.serialize()
  43526. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43527. return StandardMaterial;
  43528. }(BABYLON.PushMaterial));
  43529. BABYLON.StandardMaterial = StandardMaterial;
  43530. })(BABYLON || (BABYLON = {}));
  43531. //# sourceMappingURL=babylon.standardMaterial.js.map
  43532. "use strict";
  43533. var BABYLON;
  43534. (function (BABYLON) {
  43535. /**
  43536. * Manages the defines for the PBR Material.
  43537. * @ignoreChildren
  43538. */
  43539. var PBRMaterialDefines = /** @class */ (function (_super) {
  43540. __extends(PBRMaterialDefines, _super);
  43541. /**
  43542. * Initializes the PBR Material defines.
  43543. */
  43544. function PBRMaterialDefines() {
  43545. var _this = _super.call(this) || this;
  43546. _this.PBR = true;
  43547. _this.MAINUV1 = false;
  43548. _this.MAINUV2 = false;
  43549. _this.UV1 = false;
  43550. _this.UV2 = false;
  43551. _this.ALBEDO = false;
  43552. _this.ALBEDODIRECTUV = 0;
  43553. _this.VERTEXCOLOR = false;
  43554. _this.AMBIENT = false;
  43555. _this.AMBIENTDIRECTUV = 0;
  43556. _this.AMBIENTINGRAYSCALE = false;
  43557. _this.OPACITY = false;
  43558. _this.VERTEXALPHA = false;
  43559. _this.OPACITYDIRECTUV = 0;
  43560. _this.OPACITYRGB = false;
  43561. _this.ALPHATEST = false;
  43562. _this.DEPTHPREPASS = false;
  43563. _this.ALPHABLEND = false;
  43564. _this.ALPHAFROMALBEDO = false;
  43565. _this.ALPHATESTVALUE = "0.5";
  43566. _this.SPECULAROVERALPHA = false;
  43567. _this.RADIANCEOVERALPHA = false;
  43568. _this.ALPHAFRESNEL = false;
  43569. _this.LINEARALPHAFRESNEL = false;
  43570. _this.PREMULTIPLYALPHA = false;
  43571. _this.EMISSIVE = false;
  43572. _this.EMISSIVEDIRECTUV = 0;
  43573. _this.REFLECTIVITY = false;
  43574. _this.REFLECTIVITYDIRECTUV = 0;
  43575. _this.SPECULARTERM = false;
  43576. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43577. _this.MICROSURFACEAUTOMATIC = false;
  43578. _this.LODBASEDMICROSFURACE = false;
  43579. _this.MICROSURFACEMAP = false;
  43580. _this.MICROSURFACEMAPDIRECTUV = 0;
  43581. _this.METALLICWORKFLOW = false;
  43582. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43583. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43584. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43585. _this.AOSTOREINMETALMAPRED = false;
  43586. _this.ENVIRONMENTBRDF = false;
  43587. _this.NORMAL = false;
  43588. _this.TANGENT = false;
  43589. _this.BUMP = false;
  43590. _this.BUMPDIRECTUV = 0;
  43591. _this.OBJECTSPACE_NORMALMAP = false;
  43592. _this.PARALLAX = false;
  43593. _this.PARALLAXOCCLUSION = false;
  43594. _this.NORMALXYSCALE = true;
  43595. _this.LIGHTMAP = false;
  43596. _this.LIGHTMAPDIRECTUV = 0;
  43597. _this.USELIGHTMAPASSHADOWMAP = false;
  43598. _this.GAMMALIGHTMAP = false;
  43599. _this.REFLECTION = false;
  43600. _this.REFLECTIONMAP_3D = false;
  43601. _this.REFLECTIONMAP_SPHERICAL = false;
  43602. _this.REFLECTIONMAP_PLANAR = false;
  43603. _this.REFLECTIONMAP_CUBIC = false;
  43604. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43605. _this.REFLECTIONMAP_PROJECTION = false;
  43606. _this.REFLECTIONMAP_SKYBOX = false;
  43607. _this.REFLECTIONMAP_EXPLICIT = false;
  43608. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43609. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43610. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43611. _this.INVERTCUBICMAP = false;
  43612. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43613. _this.USESPHERICALINVERTEX = false;
  43614. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43615. _this.LODINREFLECTIONALPHA = false;
  43616. _this.GAMMAREFLECTION = false;
  43617. _this.RADIANCEOCCLUSION = false;
  43618. _this.HORIZONOCCLUSION = false;
  43619. _this.REFRACTION = false;
  43620. _this.REFRACTIONMAP_3D = false;
  43621. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43622. _this.LODINREFRACTIONALPHA = false;
  43623. _this.GAMMAREFRACTION = false;
  43624. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43625. _this.INSTANCES = false;
  43626. _this.NUM_BONE_INFLUENCERS = 0;
  43627. _this.BonesPerMesh = 0;
  43628. _this.NONUNIFORMSCALING = false;
  43629. _this.MORPHTARGETS = false;
  43630. _this.MORPHTARGETS_NORMAL = false;
  43631. _this.MORPHTARGETS_TANGENT = false;
  43632. _this.NUM_MORPH_INFLUENCERS = 0;
  43633. _this.IMAGEPROCESSING = false;
  43634. _this.VIGNETTE = false;
  43635. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43636. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43637. _this.TONEMAPPING = false;
  43638. _this.CONTRAST = false;
  43639. _this.COLORCURVES = false;
  43640. _this.COLORGRADING = false;
  43641. _this.COLORGRADING3D = false;
  43642. _this.SAMPLER3DGREENDEPTH = false;
  43643. _this.SAMPLER3DBGRMAP = false;
  43644. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43645. _this.EXPOSURE = false;
  43646. _this.USEPHYSICALLIGHTFALLOFF = false;
  43647. _this.TWOSIDEDLIGHTING = false;
  43648. _this.SHADOWFLOAT = false;
  43649. _this.CLIPPLANE = false;
  43650. _this.POINTSIZE = false;
  43651. _this.FOG = false;
  43652. _this.LOGARITHMICDEPTH = false;
  43653. _this.FORCENORMALFORWARD = false;
  43654. _this.GEOMETRYAA = false;
  43655. _this.UNLIT = false;
  43656. _this.rebuild();
  43657. return _this;
  43658. }
  43659. /**
  43660. * Resets the PBR Material defines.
  43661. */
  43662. PBRMaterialDefines.prototype.reset = function () {
  43663. _super.prototype.reset.call(this);
  43664. this.ALPHATESTVALUE = "0.5";
  43665. this.PBR = true;
  43666. };
  43667. return PBRMaterialDefines;
  43668. }(BABYLON.MaterialDefines));
  43669. /**
  43670. * The Physically based material base class of BJS.
  43671. *
  43672. * This offers the main features of a standard PBR material.
  43673. * For more information, please refer to the documentation :
  43674. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43675. */
  43676. var PBRBaseMaterial = /** @class */ (function (_super) {
  43677. __extends(PBRBaseMaterial, _super);
  43678. /**
  43679. * Instantiates a new PBRMaterial instance.
  43680. *
  43681. * @param name The material name
  43682. * @param scene The scene the material will be use in.
  43683. */
  43684. function PBRBaseMaterial(name, scene) {
  43685. var _this = _super.call(this, name, scene) || this;
  43686. /**
  43687. * Intensity of the direct lights e.g. the four lights available in your scene.
  43688. * This impacts both the direct diffuse and specular highlights.
  43689. */
  43690. _this._directIntensity = 1.0;
  43691. /**
  43692. * Intensity of the emissive part of the material.
  43693. * This helps controlling the emissive effect without modifying the emissive color.
  43694. */
  43695. _this._emissiveIntensity = 1.0;
  43696. /**
  43697. * Intensity of the environment e.g. how much the environment will light the object
  43698. * either through harmonics for rough material or through the refelction for shiny ones.
  43699. */
  43700. _this._environmentIntensity = 1.0;
  43701. /**
  43702. * This is a special control allowing the reduction of the specular highlights coming from the
  43703. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43704. */
  43705. _this._specularIntensity = 1.0;
  43706. /**
  43707. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43708. */
  43709. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43710. /**
  43711. * Debug Control allowing disabling the bump map on this material.
  43712. */
  43713. _this._disableBumpMap = false;
  43714. /**
  43715. * AKA Occlusion Texture Intensity in other nomenclature.
  43716. */
  43717. _this._ambientTextureStrength = 1.0;
  43718. /**
  43719. * The color of a material in ambient lighting.
  43720. */
  43721. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43722. /**
  43723. * AKA Diffuse Color in other nomenclature.
  43724. */
  43725. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43726. /**
  43727. * AKA Specular Color in other nomenclature.
  43728. */
  43729. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43730. /**
  43731. * The color applied when light is reflected from a material.
  43732. */
  43733. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43734. /**
  43735. * The color applied when light is emitted from a material.
  43736. */
  43737. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43738. /**
  43739. * AKA Glossiness in other nomenclature.
  43740. */
  43741. _this._microSurface = 0.9;
  43742. /**
  43743. * source material index of refraction (IOR)' / 'destination material IOR.
  43744. */
  43745. _this._indexOfRefraction = 0.66;
  43746. /**
  43747. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43748. */
  43749. _this._invertRefractionY = false;
  43750. /**
  43751. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43752. * Materials half opaque for instance using refraction could benefit from this control.
  43753. */
  43754. _this._linkRefractionWithTransparency = false;
  43755. /**
  43756. * Specifies that the material will use the light map as a show map.
  43757. */
  43758. _this._useLightmapAsShadowmap = false;
  43759. /**
  43760. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43761. * makes the reflect vector face the model (under horizon).
  43762. */
  43763. _this._useHorizonOcclusion = true;
  43764. /**
  43765. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43766. * too much the area relying on ambient texture to define their ambient occlusion.
  43767. */
  43768. _this._useRadianceOcclusion = true;
  43769. /**
  43770. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43771. */
  43772. _this._useAlphaFromAlbedoTexture = false;
  43773. /**
  43774. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43775. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43776. */
  43777. _this._useSpecularOverAlpha = true;
  43778. /**
  43779. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43780. */
  43781. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43782. /**
  43783. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43784. */
  43785. _this._useRoughnessFromMetallicTextureAlpha = true;
  43786. /**
  43787. * Specifies if the metallic texture contains the roughness information in its green channel.
  43788. */
  43789. _this._useRoughnessFromMetallicTextureGreen = false;
  43790. /**
  43791. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43792. */
  43793. _this._useMetallnessFromMetallicTextureBlue = false;
  43794. /**
  43795. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43796. */
  43797. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43798. /**
  43799. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43800. */
  43801. _this._useAmbientInGrayScale = false;
  43802. /**
  43803. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43804. * The material will try to infer what glossiness each pixel should be.
  43805. */
  43806. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43807. /**
  43808. * BJS is using an harcoded light falloff based on a manually sets up range.
  43809. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43810. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43811. */
  43812. _this._usePhysicalLightFalloff = true;
  43813. /**
  43814. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43815. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43816. */
  43817. _this._useRadianceOverAlpha = true;
  43818. /**
  43819. * Allows using an object space normal map (instead of tangent space).
  43820. */
  43821. _this._useObjectSpaceNormalMap = false;
  43822. /**
  43823. * Allows using the bump map in parallax mode.
  43824. */
  43825. _this._useParallax = false;
  43826. /**
  43827. * Allows using the bump map in parallax occlusion mode.
  43828. */
  43829. _this._useParallaxOcclusion = false;
  43830. /**
  43831. * Controls the scale bias of the parallax mode.
  43832. */
  43833. _this._parallaxScaleBias = 0.05;
  43834. /**
  43835. * If sets to true, disables all the lights affecting the material.
  43836. */
  43837. _this._disableLighting = false;
  43838. /**
  43839. * Number of Simultaneous lights allowed on the material.
  43840. */
  43841. _this._maxSimultaneousLights = 4;
  43842. /**
  43843. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43844. */
  43845. _this._invertNormalMapX = false;
  43846. /**
  43847. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43848. */
  43849. _this._invertNormalMapY = false;
  43850. /**
  43851. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43852. */
  43853. _this._twoSidedLighting = false;
  43854. /**
  43855. * Defines the alpha limits in alpha test mode.
  43856. */
  43857. _this._alphaCutOff = 0.4;
  43858. /**
  43859. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43860. */
  43861. _this._forceAlphaTest = false;
  43862. /**
  43863. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43864. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43865. */
  43866. _this._useAlphaFresnel = false;
  43867. /**
  43868. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43869. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43870. */
  43871. _this._useLinearAlphaFresnel = false;
  43872. /**
  43873. * The transparency mode of the material.
  43874. */
  43875. _this._transparencyMode = null;
  43876. /**
  43877. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43878. * from cos thetav and roughness:
  43879. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43880. */
  43881. _this._environmentBRDFTexture = null;
  43882. /**
  43883. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43884. */
  43885. _this._forceIrradianceInFragment = false;
  43886. /**
  43887. * Force normal to face away from face.
  43888. */
  43889. _this._forceNormalForward = false;
  43890. /**
  43891. * Enables specular anti aliasing in the PBR shader.
  43892. * It will both interacts on the Geometry for analytical and IBL lighting.
  43893. * It also prefilter the roughness map based on the bump values.
  43894. */
  43895. _this._enableSpecularAntiAliasing = false;
  43896. /**
  43897. * Stores the available render targets.
  43898. */
  43899. _this._renderTargets = new BABYLON.SmartArray(16);
  43900. /**
  43901. * Sets the global ambient color for the material used in lighting calculations.
  43902. */
  43903. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43904. /**
  43905. * If set to true, no lighting calculations will be applied.
  43906. */
  43907. _this._unlit = false;
  43908. // Setup the default processing configuration to the scene.
  43909. _this._attachImageProcessingConfiguration(null);
  43910. _this.getRenderTargetTextures = function () {
  43911. _this._renderTargets.reset();
  43912. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43913. _this._renderTargets.push(_this._reflectionTexture);
  43914. }
  43915. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43916. _this._renderTargets.push(_this._refractionTexture);
  43917. }
  43918. return _this._renderTargets;
  43919. };
  43920. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43921. return _this;
  43922. }
  43923. /**
  43924. * Attaches a new image processing configuration to the PBR Material.
  43925. * @param configuration
  43926. */
  43927. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43928. var _this = this;
  43929. if (configuration === this._imageProcessingConfiguration) {
  43930. return;
  43931. }
  43932. // Detaches observer.
  43933. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43934. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43935. }
  43936. // Pick the scene configuration if needed.
  43937. if (!configuration) {
  43938. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43939. }
  43940. else {
  43941. this._imageProcessingConfiguration = configuration;
  43942. }
  43943. // Attaches observer.
  43944. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43945. _this._markAllSubMeshesAsImageProcessingDirty();
  43946. });
  43947. };
  43948. /**
  43949. * Gets the name of the material class.
  43950. */
  43951. PBRBaseMaterial.prototype.getClassName = function () {
  43952. return "PBRBaseMaterial";
  43953. };
  43954. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43955. /**
  43956. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43957. */
  43958. get: function () {
  43959. return this._useLogarithmicDepth;
  43960. },
  43961. /**
  43962. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43963. */
  43964. set: function (value) {
  43965. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43966. },
  43967. enumerable: true,
  43968. configurable: true
  43969. });
  43970. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43971. /**
  43972. * Gets the current transparency mode.
  43973. */
  43974. get: function () {
  43975. return this._transparencyMode;
  43976. },
  43977. /**
  43978. * Sets the transparency mode of the material.
  43979. */
  43980. set: function (value) {
  43981. if (this._transparencyMode === value) {
  43982. return;
  43983. }
  43984. this._transparencyMode = value;
  43985. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43986. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43987. },
  43988. enumerable: true,
  43989. configurable: true
  43990. });
  43991. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43992. /**
  43993. * Returns true if alpha blending should be disabled.
  43994. */
  43995. get: function () {
  43996. return (this._linkRefractionWithTransparency ||
  43997. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43998. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43999. },
  44000. enumerable: true,
  44001. configurable: true
  44002. });
  44003. /**
  44004. * Specifies whether or not this material should be rendered in alpha blend mode.
  44005. */
  44006. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44007. if (this._disableAlphaBlending) {
  44008. return false;
  44009. }
  44010. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44011. };
  44012. /**
  44013. * Specifies if the mesh will require alpha blending.
  44014. * @param mesh - BJS mesh.
  44015. */
  44016. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44017. if (this._disableAlphaBlending) {
  44018. return false;
  44019. }
  44020. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44021. };
  44022. /**
  44023. * Specifies whether or not this material should be rendered in alpha test mode.
  44024. */
  44025. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44026. if (this._forceAlphaTest) {
  44027. return true;
  44028. }
  44029. if (this._linkRefractionWithTransparency) {
  44030. return false;
  44031. }
  44032. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44033. };
  44034. /**
  44035. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44036. */
  44037. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44038. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44039. };
  44040. /**
  44041. * Gets the texture used for the alpha test.
  44042. */
  44043. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44044. return this._albedoTexture;
  44045. };
  44046. /**
  44047. * Specifies that the submesh is ready to be used.
  44048. * @param mesh - BJS mesh.
  44049. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44050. * @param useInstances - Specifies that instances should be used.
  44051. * @returns - boolean indicating that the submesh is ready or not.
  44052. */
  44053. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44054. if (subMesh.effect && this.isFrozen) {
  44055. if (this._wasPreviouslyReady) {
  44056. return true;
  44057. }
  44058. }
  44059. if (!subMesh._materialDefines) {
  44060. subMesh._materialDefines = new PBRMaterialDefines();
  44061. }
  44062. var defines = subMesh._materialDefines;
  44063. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44064. if (defines._renderId === this.getScene().getRenderId()) {
  44065. return true;
  44066. }
  44067. }
  44068. var scene = this.getScene();
  44069. var engine = scene.getEngine();
  44070. if (defines._areTexturesDirty) {
  44071. if (scene.texturesEnabled) {
  44072. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44073. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44074. return false;
  44075. }
  44076. }
  44077. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44078. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44079. return false;
  44080. }
  44081. }
  44082. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44083. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44084. return false;
  44085. }
  44086. }
  44087. var reflectionTexture = this._getReflectionTexture();
  44088. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44089. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44090. return false;
  44091. }
  44092. }
  44093. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44094. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44095. return false;
  44096. }
  44097. }
  44098. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44099. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44100. return false;
  44101. }
  44102. }
  44103. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44104. if (this._metallicTexture) {
  44105. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44106. return false;
  44107. }
  44108. }
  44109. else if (this._reflectivityTexture) {
  44110. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44111. return false;
  44112. }
  44113. }
  44114. if (this._microSurfaceTexture) {
  44115. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44116. return false;
  44117. }
  44118. }
  44119. }
  44120. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44121. // Bump texture cannot be not blocking.
  44122. if (!this._bumpTexture.isReady()) {
  44123. return false;
  44124. }
  44125. }
  44126. var refractionTexture = this._getRefractionTexture();
  44127. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44128. if (!refractionTexture.isReadyOrNotBlocking()) {
  44129. return false;
  44130. }
  44131. }
  44132. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44133. // This is blocking.
  44134. if (!this._environmentBRDFTexture.isReady()) {
  44135. return false;
  44136. }
  44137. }
  44138. }
  44139. }
  44140. if (defines._areImageProcessingDirty) {
  44141. if (!this._imageProcessingConfiguration.isReady()) {
  44142. return false;
  44143. }
  44144. }
  44145. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44146. mesh.createNormals(true);
  44147. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44148. }
  44149. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44150. if (effect) {
  44151. scene.resetCachedMaterial();
  44152. subMesh.setEffect(effect, defines);
  44153. this.buildUniformLayout();
  44154. }
  44155. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44156. return false;
  44157. }
  44158. defines._renderId = scene.getRenderId();
  44159. this._wasPreviouslyReady = true;
  44160. return true;
  44161. };
  44162. /**
  44163. * Specifies if the material uses metallic roughness workflow.
  44164. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44165. */
  44166. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44167. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44168. return true;
  44169. }
  44170. return false;
  44171. };
  44172. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44173. if (onCompiled === void 0) { onCompiled = null; }
  44174. if (onError === void 0) { onError = null; }
  44175. if (useInstances === void 0) { useInstances = null; }
  44176. if (useClipPlane === void 0) { useClipPlane = null; }
  44177. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44178. if (!defines.isDirty) {
  44179. return null;
  44180. }
  44181. defines.markAsProcessed();
  44182. var scene = this.getScene();
  44183. var engine = scene.getEngine();
  44184. // Fallbacks
  44185. var fallbacks = new BABYLON.EffectFallbacks();
  44186. var fallbackRank = 0;
  44187. if (defines.USESPHERICALINVERTEX) {
  44188. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44189. }
  44190. if (defines.FOG) {
  44191. fallbacks.addFallback(fallbackRank, "FOG");
  44192. }
  44193. if (defines.POINTSIZE) {
  44194. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44195. }
  44196. if (defines.LOGARITHMICDEPTH) {
  44197. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44198. }
  44199. if (defines.PARALLAX) {
  44200. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44201. }
  44202. if (defines.PARALLAXOCCLUSION) {
  44203. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44204. }
  44205. if (defines.ENVIRONMENTBRDF) {
  44206. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44207. }
  44208. if (defines.TANGENT) {
  44209. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44210. }
  44211. if (defines.BUMP) {
  44212. fallbacks.addFallback(fallbackRank++, "BUMP");
  44213. }
  44214. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44215. if (defines.SPECULARTERM) {
  44216. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44217. }
  44218. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44219. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44220. }
  44221. if (defines.LIGHTMAP) {
  44222. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44223. }
  44224. if (defines.NORMAL) {
  44225. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44226. }
  44227. if (defines.AMBIENT) {
  44228. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44229. }
  44230. if (defines.EMISSIVE) {
  44231. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44232. }
  44233. if (defines.VERTEXCOLOR) {
  44234. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44235. }
  44236. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44237. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44238. }
  44239. if (defines.MORPHTARGETS) {
  44240. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44241. }
  44242. //Attributes
  44243. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44244. if (defines.NORMAL) {
  44245. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44246. }
  44247. if (defines.TANGENT) {
  44248. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44249. }
  44250. if (defines.UV1) {
  44251. attribs.push(BABYLON.VertexBuffer.UVKind);
  44252. }
  44253. if (defines.UV2) {
  44254. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44255. }
  44256. if (defines.VERTEXCOLOR) {
  44257. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44258. }
  44259. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44260. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44261. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44262. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44263. "vFogInfos", "vFogColor", "pointSize",
  44264. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44265. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44266. "mBones",
  44267. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44268. "vLightingIntensity",
  44269. "logarithmicDepthConstant",
  44270. "vSphericalX", "vSphericalY", "vSphericalZ",
  44271. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44272. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44273. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44274. "vTangentSpaceParams"
  44275. ];
  44276. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44277. "bumpSampler", "lightmapSampler", "opacitySampler",
  44278. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44279. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44280. "microSurfaceSampler", "environmentBrdfSampler"];
  44281. var uniformBuffers = ["Material", "Scene"];
  44282. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44283. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44284. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44285. uniformsNames: uniforms,
  44286. uniformBuffersNames: uniformBuffers,
  44287. samplers: samplers,
  44288. defines: defines,
  44289. maxSimultaneousLights: this._maxSimultaneousLights
  44290. });
  44291. var join = defines.toString();
  44292. return engine.createEffect("pbr", {
  44293. attributes: attribs,
  44294. uniformsNames: uniforms,
  44295. uniformBuffersNames: uniformBuffers,
  44296. samplers: samplers,
  44297. defines: join,
  44298. fallbacks: fallbacks,
  44299. onCompiled: onCompiled,
  44300. onError: onError,
  44301. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44302. }, engine);
  44303. };
  44304. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44305. if (useInstances === void 0) { useInstances = null; }
  44306. if (useClipPlane === void 0) { useClipPlane = null; }
  44307. var scene = this.getScene();
  44308. var engine = scene.getEngine();
  44309. // Lights
  44310. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44311. defines._needNormals = true;
  44312. // Textures
  44313. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44314. if (defines._areTexturesDirty) {
  44315. defines._needUVs = false;
  44316. if (scene.texturesEnabled) {
  44317. if (scene.getEngine().getCaps().textureLOD) {
  44318. defines.LODBASEDMICROSFURACE = true;
  44319. }
  44320. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44321. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44322. }
  44323. else {
  44324. defines.ALBEDO = false;
  44325. }
  44326. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44327. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44328. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44329. }
  44330. else {
  44331. defines.AMBIENT = false;
  44332. }
  44333. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44334. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44335. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44336. }
  44337. else {
  44338. defines.OPACITY = false;
  44339. }
  44340. var reflectionTexture = this._getReflectionTexture();
  44341. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44342. defines.REFLECTION = true;
  44343. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44344. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44345. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44346. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44347. defines.INVERTCUBICMAP = true;
  44348. }
  44349. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44350. switch (reflectionTexture.coordinatesMode) {
  44351. case BABYLON.Texture.CUBIC_MODE:
  44352. case BABYLON.Texture.INVCUBIC_MODE:
  44353. defines.REFLECTIONMAP_CUBIC = true;
  44354. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44355. break;
  44356. case BABYLON.Texture.EXPLICIT_MODE:
  44357. defines.REFLECTIONMAP_EXPLICIT = true;
  44358. break;
  44359. case BABYLON.Texture.PLANAR_MODE:
  44360. defines.REFLECTIONMAP_PLANAR = true;
  44361. break;
  44362. case BABYLON.Texture.PROJECTION_MODE:
  44363. defines.REFLECTIONMAP_PROJECTION = true;
  44364. break;
  44365. case BABYLON.Texture.SKYBOX_MODE:
  44366. defines.REFLECTIONMAP_SKYBOX = true;
  44367. break;
  44368. case BABYLON.Texture.SPHERICAL_MODE:
  44369. defines.REFLECTIONMAP_SPHERICAL = true;
  44370. break;
  44371. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44372. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44373. break;
  44374. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44375. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44376. break;
  44377. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44378. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44379. break;
  44380. }
  44381. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44382. if (reflectionTexture.sphericalPolynomial) {
  44383. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44384. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44385. defines.USESPHERICALINVERTEX = false;
  44386. }
  44387. else {
  44388. defines.USESPHERICALINVERTEX = true;
  44389. }
  44390. }
  44391. }
  44392. }
  44393. else {
  44394. defines.REFLECTION = false;
  44395. defines.REFLECTIONMAP_3D = false;
  44396. defines.REFLECTIONMAP_SPHERICAL = false;
  44397. defines.REFLECTIONMAP_PLANAR = false;
  44398. defines.REFLECTIONMAP_CUBIC = false;
  44399. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44400. defines.REFLECTIONMAP_PROJECTION = false;
  44401. defines.REFLECTIONMAP_SKYBOX = false;
  44402. defines.REFLECTIONMAP_EXPLICIT = false;
  44403. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44404. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44405. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44406. defines.INVERTCUBICMAP = false;
  44407. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44408. defines.USESPHERICALINVERTEX = false;
  44409. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44410. defines.LODINREFLECTIONALPHA = false;
  44411. defines.GAMMAREFLECTION = false;
  44412. }
  44413. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44414. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44415. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44416. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44417. }
  44418. else {
  44419. defines.LIGHTMAP = false;
  44420. }
  44421. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44422. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44423. }
  44424. else {
  44425. defines.EMISSIVE = false;
  44426. }
  44427. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44428. if (this._metallicTexture) {
  44429. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44430. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44431. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44432. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44433. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44434. }
  44435. else if (this._reflectivityTexture) {
  44436. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44437. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44438. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44439. }
  44440. else {
  44441. defines.REFLECTIVITY = false;
  44442. }
  44443. if (this._microSurfaceTexture) {
  44444. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44445. }
  44446. else {
  44447. defines.MICROSURFACEMAP = false;
  44448. }
  44449. }
  44450. else {
  44451. defines.REFLECTIVITY = false;
  44452. defines.MICROSURFACEMAP = false;
  44453. }
  44454. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44455. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44456. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44457. defines.PARALLAX = true;
  44458. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44459. }
  44460. else {
  44461. defines.PARALLAX = false;
  44462. }
  44463. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44464. }
  44465. else {
  44466. defines.BUMP = false;
  44467. }
  44468. var refractionTexture = this._getRefractionTexture();
  44469. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44470. defines.REFRACTION = true;
  44471. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44472. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44473. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44474. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44475. if (this._linkRefractionWithTransparency) {
  44476. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44477. }
  44478. }
  44479. else {
  44480. defines.REFRACTION = false;
  44481. }
  44482. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44483. defines.ENVIRONMENTBRDF = true;
  44484. }
  44485. else {
  44486. defines.ENVIRONMENTBRDF = false;
  44487. }
  44488. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44489. defines.ALPHAFROMALBEDO = true;
  44490. }
  44491. else {
  44492. defines.ALPHAFROMALBEDO = false;
  44493. }
  44494. }
  44495. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44496. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44497. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44498. if (!this.backFaceCulling && this._twoSidedLighting) {
  44499. defines.TWOSIDEDLIGHTING = true;
  44500. }
  44501. else {
  44502. defines.TWOSIDEDLIGHTING = false;
  44503. }
  44504. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44505. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44506. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44507. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44508. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44509. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44510. }
  44511. if (defines._areImageProcessingDirty) {
  44512. this._imageProcessingConfiguration.prepareDefines(defines);
  44513. }
  44514. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44515. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44516. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44517. // Misc.
  44518. if (defines._areMiscDirty) {
  44519. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44520. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44521. }
  44522. // Values that need to be evaluated on every frame
  44523. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44524. // Attribs
  44525. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44526. };
  44527. /**
  44528. * Force shader compilation
  44529. */
  44530. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44531. var _this = this;
  44532. var localOptions = __assign({ clipPlane: false }, options);
  44533. var defines = new PBRMaterialDefines();
  44534. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44535. if (effect.isReady()) {
  44536. if (onCompiled) {
  44537. onCompiled(this);
  44538. }
  44539. }
  44540. else {
  44541. effect.onCompileObservable.add(function () {
  44542. if (onCompiled) {
  44543. onCompiled(_this);
  44544. }
  44545. });
  44546. }
  44547. };
  44548. /**
  44549. * Initializes the uniform buffer layout for the shader.
  44550. */
  44551. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44552. // Order is important !
  44553. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44554. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44555. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44556. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44557. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44558. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44559. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44560. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44561. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44562. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44563. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44564. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44565. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44566. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44567. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44568. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44569. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44570. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44571. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44572. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44573. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44574. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44575. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44576. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44577. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44578. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44579. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44580. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44581. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44582. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44583. this._uniformBuffer.addUniform("pointSize", 1);
  44584. this._uniformBuffer.create();
  44585. };
  44586. /**
  44587. * Unbinds the textures.
  44588. */
  44589. PBRBaseMaterial.prototype.unbind = function () {
  44590. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44591. this._uniformBuffer.setTexture("reflectionSampler", null);
  44592. }
  44593. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44594. this._uniformBuffer.setTexture("refractionSampler", null);
  44595. }
  44596. _super.prototype.unbind.call(this);
  44597. };
  44598. /**
  44599. * Binds the submesh data.
  44600. * @param world - The world matrix.
  44601. * @param mesh - The BJS mesh.
  44602. * @param subMesh - A submesh of the BJS mesh.
  44603. */
  44604. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44605. var scene = this.getScene();
  44606. var defines = subMesh._materialDefines;
  44607. if (!defines) {
  44608. return;
  44609. }
  44610. var effect = subMesh.effect;
  44611. if (!effect) {
  44612. return;
  44613. }
  44614. this._activeEffect = effect;
  44615. // Matrices
  44616. this.bindOnlyWorldMatrix(world);
  44617. // Normal Matrix
  44618. if (defines.OBJECTSPACE_NORMALMAP) {
  44619. world.toNormalMatrix(this._normalMatrix);
  44620. this.bindOnlyNormalMatrix(this._normalMatrix);
  44621. }
  44622. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44623. // Bones
  44624. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44625. var reflectionTexture = null;
  44626. if (mustRebind) {
  44627. this._uniformBuffer.bindToEffect(effect, "Material");
  44628. this.bindViewProjection(effect);
  44629. reflectionTexture = this._getReflectionTexture();
  44630. var refractionTexture = this._getRefractionTexture();
  44631. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44632. // Texture uniforms
  44633. if (scene.texturesEnabled) {
  44634. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44635. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44636. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44637. }
  44638. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44639. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44640. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44641. }
  44642. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44643. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44644. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44645. }
  44646. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44647. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44648. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44649. if (reflectionTexture.boundingBoxSize) {
  44650. var cubeTexture = reflectionTexture;
  44651. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44652. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44653. }
  44654. var polynomials = reflectionTexture.sphericalPolynomial;
  44655. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44656. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44657. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44658. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44659. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44660. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44661. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44662. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44663. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44664. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44665. }
  44666. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44667. }
  44668. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44669. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44670. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44671. }
  44672. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44673. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44674. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44675. }
  44676. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44677. if (this._metallicTexture) {
  44678. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44679. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44680. }
  44681. else if (this._reflectivityTexture) {
  44682. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44683. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44684. }
  44685. if (this._microSurfaceTexture) {
  44686. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44687. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44688. }
  44689. }
  44690. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44691. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44692. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44693. if (scene._mirroredCameraPosition) {
  44694. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44695. }
  44696. else {
  44697. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44698. }
  44699. }
  44700. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44701. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44702. var depth = 1.0;
  44703. if (!refractionTexture.isCube) {
  44704. if (refractionTexture.depth) {
  44705. depth = refractionTexture.depth;
  44706. }
  44707. }
  44708. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44709. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44710. }
  44711. }
  44712. // Point size
  44713. if (this.pointsCloud) {
  44714. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44715. }
  44716. // Colors
  44717. if (defines.METALLICWORKFLOW) {
  44718. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44719. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44720. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44721. }
  44722. else {
  44723. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44724. }
  44725. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44726. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44727. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44728. // Misc
  44729. this._lightingInfos.x = this._directIntensity;
  44730. this._lightingInfos.y = this._emissiveIntensity;
  44731. this._lightingInfos.z = this._environmentIntensity;
  44732. this._lightingInfos.w = this._specularIntensity;
  44733. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44734. }
  44735. // Textures
  44736. if (scene.texturesEnabled) {
  44737. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44738. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44739. }
  44740. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44741. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44742. }
  44743. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44744. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44745. }
  44746. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44747. if (defines.LODBASEDMICROSFURACE) {
  44748. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44749. }
  44750. else {
  44751. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44752. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44753. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44754. }
  44755. }
  44756. if (defines.ENVIRONMENTBRDF) {
  44757. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44758. }
  44759. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44760. if (defines.LODBASEDMICROSFURACE) {
  44761. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44762. }
  44763. else {
  44764. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44765. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44766. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44767. }
  44768. }
  44769. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44770. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44771. }
  44772. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44773. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44774. }
  44775. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44776. if (this._metallicTexture) {
  44777. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44778. }
  44779. else if (this._reflectivityTexture) {
  44780. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44781. }
  44782. if (this._microSurfaceTexture) {
  44783. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44784. }
  44785. }
  44786. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44787. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44788. }
  44789. }
  44790. // Clip plane
  44791. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44792. // Colors
  44793. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44794. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44795. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44796. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44797. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44798. }
  44799. if (mustRebind || !this.isFrozen) {
  44800. // Lights
  44801. if (scene.lightsEnabled && !this._disableLighting) {
  44802. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44803. }
  44804. // View
  44805. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44806. this.bindView(effect);
  44807. }
  44808. // Fog
  44809. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44810. // Morph targets
  44811. if (defines.NUM_MORPH_INFLUENCERS) {
  44812. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44813. }
  44814. // image processing
  44815. this._imageProcessingConfiguration.bind(this._activeEffect);
  44816. // Log. depth
  44817. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44818. }
  44819. this._uniformBuffer.update();
  44820. this._afterBind(mesh);
  44821. };
  44822. /**
  44823. * Returns the animatable textures.
  44824. * @returns - Array of animatable textures.
  44825. */
  44826. PBRBaseMaterial.prototype.getAnimatables = function () {
  44827. var results = [];
  44828. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44829. results.push(this._albedoTexture);
  44830. }
  44831. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44832. results.push(this._ambientTexture);
  44833. }
  44834. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44835. results.push(this._opacityTexture);
  44836. }
  44837. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44838. results.push(this._reflectionTexture);
  44839. }
  44840. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44841. results.push(this._emissiveTexture);
  44842. }
  44843. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44844. results.push(this._metallicTexture);
  44845. }
  44846. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44847. results.push(this._reflectivityTexture);
  44848. }
  44849. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44850. results.push(this._bumpTexture);
  44851. }
  44852. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44853. results.push(this._lightmapTexture);
  44854. }
  44855. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44856. results.push(this._refractionTexture);
  44857. }
  44858. return results;
  44859. };
  44860. /**
  44861. * Returns the texture used for reflections.
  44862. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44863. */
  44864. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44865. if (this._reflectionTexture) {
  44866. return this._reflectionTexture;
  44867. }
  44868. return this.getScene().environmentTexture;
  44869. };
  44870. /**
  44871. * Returns the texture used for refraction or null if none is used.
  44872. * @returns - Refection texture if present. If no refraction texture and refraction
  44873. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44874. */
  44875. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44876. if (this._refractionTexture) {
  44877. return this._refractionTexture;
  44878. }
  44879. if (this._linkRefractionWithTransparency) {
  44880. return this.getScene().environmentTexture;
  44881. }
  44882. return null;
  44883. };
  44884. /**
  44885. * Disposes the resources of the material.
  44886. * @param forceDisposeEffect - Forces the disposal of effects.
  44887. * @param forceDisposeTextures - Forces the disposal of all textures.
  44888. */
  44889. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44890. if (forceDisposeTextures) {
  44891. if (this._albedoTexture) {
  44892. this._albedoTexture.dispose();
  44893. }
  44894. if (this._ambientTexture) {
  44895. this._ambientTexture.dispose();
  44896. }
  44897. if (this._opacityTexture) {
  44898. this._opacityTexture.dispose();
  44899. }
  44900. if (this._reflectionTexture) {
  44901. this._reflectionTexture.dispose();
  44902. }
  44903. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44904. this._environmentBRDFTexture.dispose();
  44905. }
  44906. if (this._emissiveTexture) {
  44907. this._emissiveTexture.dispose();
  44908. }
  44909. if (this._metallicTexture) {
  44910. this._metallicTexture.dispose();
  44911. }
  44912. if (this._reflectivityTexture) {
  44913. this._reflectivityTexture.dispose();
  44914. }
  44915. if (this._bumpTexture) {
  44916. this._bumpTexture.dispose();
  44917. }
  44918. if (this._lightmapTexture) {
  44919. this._lightmapTexture.dispose();
  44920. }
  44921. if (this._refractionTexture) {
  44922. this._refractionTexture.dispose();
  44923. }
  44924. }
  44925. this._renderTargets.dispose();
  44926. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44927. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44928. }
  44929. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44930. };
  44931. /**
  44932. * Stores the reflectivity values based on metallic roughness workflow.
  44933. */
  44934. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44935. __decorate([
  44936. BABYLON.serializeAsImageProcessingConfiguration()
  44937. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44938. __decorate([
  44939. BABYLON.serialize()
  44940. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44941. __decorate([
  44942. BABYLON.serialize()
  44943. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44944. return PBRBaseMaterial;
  44945. }(BABYLON.PushMaterial));
  44946. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44947. })(BABYLON || (BABYLON = {}));
  44948. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44949. "use strict";
  44950. var BABYLON;
  44951. (function (BABYLON) {
  44952. /**
  44953. * The Physically based simple base material of BJS.
  44954. *
  44955. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44956. * It is used as the base class for both the specGloss and metalRough conventions.
  44957. */
  44958. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44959. __extends(PBRBaseSimpleMaterial, _super);
  44960. /**
  44961. * Instantiates a new PBRMaterial instance.
  44962. *
  44963. * @param name The material name
  44964. * @param scene The scene the material will be use in.
  44965. */
  44966. function PBRBaseSimpleMaterial(name, scene) {
  44967. var _this = _super.call(this, name, scene) || this;
  44968. /**
  44969. * Number of Simultaneous lights allowed on the material.
  44970. */
  44971. _this.maxSimultaneousLights = 4;
  44972. /**
  44973. * If sets to true, disables all the lights affecting the material.
  44974. */
  44975. _this.disableLighting = false;
  44976. /**
  44977. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44978. */
  44979. _this.invertNormalMapX = false;
  44980. /**
  44981. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44982. */
  44983. _this.invertNormalMapY = false;
  44984. /**
  44985. * Emissivie color used to self-illuminate the model.
  44986. */
  44987. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44988. /**
  44989. * Occlusion Channel Strenght.
  44990. */
  44991. _this.occlusionStrength = 1.0;
  44992. _this.useLightmapAsShadowmap = false;
  44993. _this._useAlphaFromAlbedoTexture = true;
  44994. _this._useAmbientInGrayScale = true;
  44995. return _this;
  44996. }
  44997. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44998. /**
  44999. * Gets the current double sided mode.
  45000. */
  45001. get: function () {
  45002. return this._twoSidedLighting;
  45003. },
  45004. /**
  45005. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45006. */
  45007. set: function (value) {
  45008. if (this._twoSidedLighting === value) {
  45009. return;
  45010. }
  45011. this._twoSidedLighting = value;
  45012. this.backFaceCulling = !value;
  45013. this._markAllSubMeshesAsTexturesDirty();
  45014. },
  45015. enumerable: true,
  45016. configurable: true
  45017. });
  45018. /**
  45019. * Return the active textures of the material.
  45020. */
  45021. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45022. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45023. if (this.environmentTexture) {
  45024. activeTextures.push(this.environmentTexture);
  45025. }
  45026. if (this.normalTexture) {
  45027. activeTextures.push(this.normalTexture);
  45028. }
  45029. if (this.emissiveTexture) {
  45030. activeTextures.push(this.emissiveTexture);
  45031. }
  45032. if (this.occlusionTexture) {
  45033. activeTextures.push(this.occlusionTexture);
  45034. }
  45035. if (this.lightmapTexture) {
  45036. activeTextures.push(this.lightmapTexture);
  45037. }
  45038. return activeTextures;
  45039. };
  45040. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45041. if (_super.prototype.hasTexture.call(this, texture)) {
  45042. return true;
  45043. }
  45044. if (this.lightmapTexture === texture) {
  45045. return true;
  45046. }
  45047. return false;
  45048. };
  45049. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45050. return "PBRBaseSimpleMaterial";
  45051. };
  45052. __decorate([
  45053. BABYLON.serialize(),
  45054. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45055. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45056. __decorate([
  45057. BABYLON.serialize(),
  45058. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45059. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45060. __decorate([
  45061. BABYLON.serializeAsTexture(),
  45062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45063. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45064. __decorate([
  45065. BABYLON.serialize(),
  45066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45067. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45068. __decorate([
  45069. BABYLON.serialize(),
  45070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45071. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45072. __decorate([
  45073. BABYLON.serializeAsTexture(),
  45074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45075. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45076. __decorate([
  45077. BABYLON.serializeAsColor3("emissive"),
  45078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45079. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45080. __decorate([
  45081. BABYLON.serializeAsTexture(),
  45082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45083. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45084. __decorate([
  45085. BABYLON.serialize(),
  45086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45087. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45088. __decorate([
  45089. BABYLON.serializeAsTexture(),
  45090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45091. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45092. __decorate([
  45093. BABYLON.serialize(),
  45094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45095. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45096. __decorate([
  45097. BABYLON.serialize()
  45098. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45099. __decorate([
  45100. BABYLON.serializeAsTexture(),
  45101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45102. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45103. __decorate([
  45104. BABYLON.serialize(),
  45105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45106. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45107. return PBRBaseSimpleMaterial;
  45108. }(BABYLON.PBRBaseMaterial));
  45109. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45110. })(BABYLON || (BABYLON = {}));
  45111. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45112. "use strict";
  45113. var BABYLON;
  45114. (function (BABYLON) {
  45115. /**
  45116. * The Physically based material of BJS.
  45117. *
  45118. * This offers the main features of a standard PBR material.
  45119. * For more information, please refer to the documentation :
  45120. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45121. */
  45122. var PBRMaterial = /** @class */ (function (_super) {
  45123. __extends(PBRMaterial, _super);
  45124. /**
  45125. * Instantiates a new PBRMaterial instance.
  45126. *
  45127. * @param name The material name
  45128. * @param scene The scene the material will be use in.
  45129. */
  45130. function PBRMaterial(name, scene) {
  45131. var _this = _super.call(this, name, scene) || this;
  45132. /**
  45133. * Intensity of the direct lights e.g. the four lights available in your scene.
  45134. * This impacts both the direct diffuse and specular highlights.
  45135. */
  45136. _this.directIntensity = 1.0;
  45137. /**
  45138. * Intensity of the emissive part of the material.
  45139. * This helps controlling the emissive effect without modifying the emissive color.
  45140. */
  45141. _this.emissiveIntensity = 1.0;
  45142. /**
  45143. * Intensity of the environment e.g. how much the environment will light the object
  45144. * either through harmonics for rough material or through the refelction for shiny ones.
  45145. */
  45146. _this.environmentIntensity = 1.0;
  45147. /**
  45148. * This is a special control allowing the reduction of the specular highlights coming from the
  45149. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45150. */
  45151. _this.specularIntensity = 1.0;
  45152. /**
  45153. * Debug Control allowing disabling the bump map on this material.
  45154. */
  45155. _this.disableBumpMap = false;
  45156. /**
  45157. * AKA Occlusion Texture Intensity in other nomenclature.
  45158. */
  45159. _this.ambientTextureStrength = 1.0;
  45160. /**
  45161. * The color of a material in ambient lighting.
  45162. */
  45163. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45164. /**
  45165. * AKA Diffuse Color in other nomenclature.
  45166. */
  45167. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45168. /**
  45169. * AKA Specular Color in other nomenclature.
  45170. */
  45171. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45172. /**
  45173. * The color reflected from the material.
  45174. */
  45175. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45176. /**
  45177. * The color emitted from the material.
  45178. */
  45179. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45180. /**
  45181. * AKA Glossiness in other nomenclature.
  45182. */
  45183. _this.microSurface = 1.0;
  45184. /**
  45185. * source material index of refraction (IOR)' / 'destination material IOR.
  45186. */
  45187. _this.indexOfRefraction = 0.66;
  45188. /**
  45189. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45190. */
  45191. _this.invertRefractionY = false;
  45192. /**
  45193. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45194. * Materials half opaque for instance using refraction could benefit from this control.
  45195. */
  45196. _this.linkRefractionWithTransparency = false;
  45197. _this.useLightmapAsShadowmap = false;
  45198. /**
  45199. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45200. */
  45201. _this.useAlphaFromAlbedoTexture = false;
  45202. /**
  45203. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45204. */
  45205. _this.forceAlphaTest = false;
  45206. /**
  45207. * Defines the alpha limits in alpha test mode.
  45208. */
  45209. _this.alphaCutOff = 0.4;
  45210. /**
  45211. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45212. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45213. */
  45214. _this.useSpecularOverAlpha = true;
  45215. /**
  45216. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45217. */
  45218. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45219. /**
  45220. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45221. */
  45222. _this.useRoughnessFromMetallicTextureAlpha = true;
  45223. /**
  45224. * Specifies if the metallic texture contains the roughness information in its green channel.
  45225. */
  45226. _this.useRoughnessFromMetallicTextureGreen = false;
  45227. /**
  45228. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45229. */
  45230. _this.useMetallnessFromMetallicTextureBlue = false;
  45231. /**
  45232. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45233. */
  45234. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45235. /**
  45236. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45237. */
  45238. _this.useAmbientInGrayScale = false;
  45239. /**
  45240. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45241. * The material will try to infer what glossiness each pixel should be.
  45242. */
  45243. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45244. /**
  45245. * BJS is using an harcoded light falloff based on a manually sets up range.
  45246. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45247. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45248. */
  45249. _this.usePhysicalLightFalloff = true;
  45250. /**
  45251. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45252. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45253. */
  45254. _this.useRadianceOverAlpha = true;
  45255. /**
  45256. * Allows using an object space normal map (instead of tangent space).
  45257. */
  45258. _this.useObjectSpaceNormalMap = false;
  45259. /**
  45260. * Allows using the bump map in parallax mode.
  45261. */
  45262. _this.useParallax = false;
  45263. /**
  45264. * Allows using the bump map in parallax occlusion mode.
  45265. */
  45266. _this.useParallaxOcclusion = false;
  45267. /**
  45268. * Controls the scale bias of the parallax mode.
  45269. */
  45270. _this.parallaxScaleBias = 0.05;
  45271. /**
  45272. * If sets to true, disables all the lights affecting the material.
  45273. */
  45274. _this.disableLighting = false;
  45275. /**
  45276. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45277. */
  45278. _this.forceIrradianceInFragment = false;
  45279. /**
  45280. * Number of Simultaneous lights allowed on the material.
  45281. */
  45282. _this.maxSimultaneousLights = 4;
  45283. /**
  45284. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45285. */
  45286. _this.invertNormalMapX = false;
  45287. /**
  45288. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45289. */
  45290. _this.invertNormalMapY = false;
  45291. /**
  45292. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45293. */
  45294. _this.twoSidedLighting = false;
  45295. /**
  45296. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45297. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45298. */
  45299. _this.useAlphaFresnel = false;
  45300. /**
  45301. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45302. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45303. */
  45304. _this.useLinearAlphaFresnel = false;
  45305. /**
  45306. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45307. * And/Or occlude the blended part.
  45308. */
  45309. _this.environmentBRDFTexture = null;
  45310. /**
  45311. * Force normal to face away from face.
  45312. */
  45313. _this.forceNormalForward = false;
  45314. /**
  45315. * Enables specular anti aliasing in the PBR shader.
  45316. * It will both interacts on the Geometry for analytical and IBL lighting.
  45317. * It also prefilter the roughness map based on the bump values.
  45318. */
  45319. _this.enableSpecularAntiAliasing = false;
  45320. /**
  45321. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45322. * makes the reflect vector face the model (under horizon).
  45323. */
  45324. _this.useHorizonOcclusion = true;
  45325. /**
  45326. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45327. * too much the area relying on ambient texture to define their ambient occlusion.
  45328. */
  45329. _this.useRadianceOcclusion = true;
  45330. /**
  45331. * If set to true, no lighting calculations will be applied.
  45332. */
  45333. _this.unlit = false;
  45334. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45335. return _this;
  45336. }
  45337. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45338. /**
  45339. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45340. */
  45341. get: function () {
  45342. return this._PBRMATERIAL_OPAQUE;
  45343. },
  45344. enumerable: true,
  45345. configurable: true
  45346. });
  45347. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45348. /**
  45349. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45350. */
  45351. get: function () {
  45352. return this._PBRMATERIAL_ALPHATEST;
  45353. },
  45354. enumerable: true,
  45355. configurable: true
  45356. });
  45357. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45358. /**
  45359. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45360. */
  45361. get: function () {
  45362. return this._PBRMATERIAL_ALPHABLEND;
  45363. },
  45364. enumerable: true,
  45365. configurable: true
  45366. });
  45367. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45368. /**
  45369. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45370. * They are also discarded below the alpha cutoff threshold to improve performances.
  45371. */
  45372. get: function () {
  45373. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45374. },
  45375. enumerable: true,
  45376. configurable: true
  45377. });
  45378. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45379. /**
  45380. * Gets the image processing configuration used either in this material.
  45381. */
  45382. get: function () {
  45383. return this._imageProcessingConfiguration;
  45384. },
  45385. /**
  45386. * Sets the Default image processing configuration used either in the this material.
  45387. *
  45388. * If sets to null, the scene one is in use.
  45389. */
  45390. set: function (value) {
  45391. this._attachImageProcessingConfiguration(value);
  45392. // Ensure the effect will be rebuilt.
  45393. this._markAllSubMeshesAsTexturesDirty();
  45394. },
  45395. enumerable: true,
  45396. configurable: true
  45397. });
  45398. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45399. /**
  45400. * Gets wether the color curves effect is enabled.
  45401. */
  45402. get: function () {
  45403. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45404. },
  45405. /**
  45406. * Sets wether the color curves effect is enabled.
  45407. */
  45408. set: function (value) {
  45409. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45410. },
  45411. enumerable: true,
  45412. configurable: true
  45413. });
  45414. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45415. /**
  45416. * Gets wether the color grading effect is enabled.
  45417. */
  45418. get: function () {
  45419. return this.imageProcessingConfiguration.colorGradingEnabled;
  45420. },
  45421. /**
  45422. * Gets wether the color grading effect is enabled.
  45423. */
  45424. set: function (value) {
  45425. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45426. },
  45427. enumerable: true,
  45428. configurable: true
  45429. });
  45430. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45431. /**
  45432. * Gets wether tonemapping is enabled or not.
  45433. */
  45434. get: function () {
  45435. return this._imageProcessingConfiguration.toneMappingEnabled;
  45436. },
  45437. /**
  45438. * Sets wether tonemapping is enabled or not
  45439. */
  45440. set: function (value) {
  45441. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45442. },
  45443. enumerable: true,
  45444. configurable: true
  45445. });
  45446. ;
  45447. ;
  45448. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45449. /**
  45450. * The camera exposure used on this material.
  45451. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45452. * This corresponds to a photographic exposure.
  45453. */
  45454. get: function () {
  45455. return this._imageProcessingConfiguration.exposure;
  45456. },
  45457. /**
  45458. * The camera exposure used on this material.
  45459. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45460. * This corresponds to a photographic exposure.
  45461. */
  45462. set: function (value) {
  45463. this._imageProcessingConfiguration.exposure = value;
  45464. },
  45465. enumerable: true,
  45466. configurable: true
  45467. });
  45468. ;
  45469. ;
  45470. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45471. /**
  45472. * Gets The camera contrast used on this material.
  45473. */
  45474. get: function () {
  45475. return this._imageProcessingConfiguration.contrast;
  45476. },
  45477. /**
  45478. * Sets The camera contrast used on this material.
  45479. */
  45480. set: function (value) {
  45481. this._imageProcessingConfiguration.contrast = value;
  45482. },
  45483. enumerable: true,
  45484. configurable: true
  45485. });
  45486. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45487. /**
  45488. * Gets the Color Grading 2D Lookup Texture.
  45489. */
  45490. get: function () {
  45491. return this._imageProcessingConfiguration.colorGradingTexture;
  45492. },
  45493. /**
  45494. * Sets the Color Grading 2D Lookup Texture.
  45495. */
  45496. set: function (value) {
  45497. this._imageProcessingConfiguration.colorGradingTexture = value;
  45498. },
  45499. enumerable: true,
  45500. configurable: true
  45501. });
  45502. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45503. /**
  45504. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45505. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45506. * 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;
  45507. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45508. */
  45509. get: function () {
  45510. return this._imageProcessingConfiguration.colorCurves;
  45511. },
  45512. /**
  45513. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45514. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45515. * 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;
  45516. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45517. */
  45518. set: function (value) {
  45519. this._imageProcessingConfiguration.colorCurves = value;
  45520. },
  45521. enumerable: true,
  45522. configurable: true
  45523. });
  45524. /**
  45525. * Returns the name of this material class.
  45526. */
  45527. PBRMaterial.prototype.getClassName = function () {
  45528. return "PBRMaterial";
  45529. };
  45530. /**
  45531. * Returns an array of the actively used textures.
  45532. * @returns - Array of BaseTextures
  45533. */
  45534. PBRMaterial.prototype.getActiveTextures = function () {
  45535. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45536. if (this._albedoTexture) {
  45537. activeTextures.push(this._albedoTexture);
  45538. }
  45539. if (this._ambientTexture) {
  45540. activeTextures.push(this._ambientTexture);
  45541. }
  45542. if (this._opacityTexture) {
  45543. activeTextures.push(this._opacityTexture);
  45544. }
  45545. if (this._reflectionTexture) {
  45546. activeTextures.push(this._reflectionTexture);
  45547. }
  45548. if (this._emissiveTexture) {
  45549. activeTextures.push(this._emissiveTexture);
  45550. }
  45551. if (this._reflectivityTexture) {
  45552. activeTextures.push(this._reflectivityTexture);
  45553. }
  45554. if (this._metallicTexture) {
  45555. activeTextures.push(this._metallicTexture);
  45556. }
  45557. if (this._microSurfaceTexture) {
  45558. activeTextures.push(this._microSurfaceTexture);
  45559. }
  45560. if (this._bumpTexture) {
  45561. activeTextures.push(this._bumpTexture);
  45562. }
  45563. if (this._lightmapTexture) {
  45564. activeTextures.push(this._lightmapTexture);
  45565. }
  45566. if (this._refractionTexture) {
  45567. activeTextures.push(this._refractionTexture);
  45568. }
  45569. return activeTextures;
  45570. };
  45571. /**
  45572. * Checks to see if a texture is used in the material.
  45573. * @param texture - Base texture to use.
  45574. * @returns - Boolean specifying if a texture is used in the material.
  45575. */
  45576. PBRMaterial.prototype.hasTexture = function (texture) {
  45577. if (_super.prototype.hasTexture.call(this, texture)) {
  45578. return true;
  45579. }
  45580. if (this._albedoTexture === texture) {
  45581. return true;
  45582. }
  45583. if (this._ambientTexture === texture) {
  45584. return true;
  45585. }
  45586. if (this._opacityTexture === texture) {
  45587. return true;
  45588. }
  45589. if (this._reflectionTexture === texture) {
  45590. return true;
  45591. }
  45592. if (this._reflectivityTexture === texture) {
  45593. return true;
  45594. }
  45595. if (this._metallicTexture === texture) {
  45596. return true;
  45597. }
  45598. if (this._microSurfaceTexture === texture) {
  45599. return true;
  45600. }
  45601. if (this._bumpTexture === texture) {
  45602. return true;
  45603. }
  45604. if (this._lightmapTexture === texture) {
  45605. return true;
  45606. }
  45607. if (this._refractionTexture === texture) {
  45608. return true;
  45609. }
  45610. return false;
  45611. };
  45612. /**
  45613. * Makes a duplicate of the current material.
  45614. * @param name - name to use for the new material.
  45615. */
  45616. PBRMaterial.prototype.clone = function (name) {
  45617. var _this = this;
  45618. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45619. clone.id = name;
  45620. clone.name = name;
  45621. return clone;
  45622. };
  45623. /**
  45624. * Serializes this PBR Material.
  45625. * @returns - An object with the serialized material.
  45626. */
  45627. PBRMaterial.prototype.serialize = function () {
  45628. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45629. serializationObject.customType = "BABYLON.PBRMaterial";
  45630. return serializationObject;
  45631. };
  45632. // Statics
  45633. /**
  45634. * Parses a PBR Material from a serialized object.
  45635. * @param source - Serialized object.
  45636. * @param scene - BJS scene instance.
  45637. * @param rootUrl - url for the scene object
  45638. * @returns - PBRMaterial
  45639. */
  45640. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45641. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45642. };
  45643. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45644. /**
  45645. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45646. */
  45647. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45648. /**
  45649. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45650. */
  45651. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45652. /**
  45653. * 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.
  45654. * They are also discarded below the alpha cutoff threshold to improve performances.
  45655. */
  45656. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45657. __decorate([
  45658. BABYLON.serialize(),
  45659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45660. ], PBRMaterial.prototype, "directIntensity", void 0);
  45661. __decorate([
  45662. BABYLON.serialize(),
  45663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45664. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45665. __decorate([
  45666. BABYLON.serialize(),
  45667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45668. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45669. __decorate([
  45670. BABYLON.serialize(),
  45671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45672. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45673. __decorate([
  45674. BABYLON.serialize(),
  45675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45676. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45677. __decorate([
  45678. BABYLON.serializeAsTexture(),
  45679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45680. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45681. __decorate([
  45682. BABYLON.serializeAsTexture(),
  45683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45684. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45685. __decorate([
  45686. BABYLON.serialize(),
  45687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45688. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45689. __decorate([
  45690. BABYLON.serializeAsTexture(),
  45691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45692. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45693. __decorate([
  45694. BABYLON.serializeAsTexture(),
  45695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45696. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45697. __decorate([
  45698. BABYLON.serializeAsTexture(),
  45699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45700. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45701. __decorate([
  45702. BABYLON.serializeAsTexture(),
  45703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45704. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45705. __decorate([
  45706. BABYLON.serializeAsTexture(),
  45707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45708. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45709. __decorate([
  45710. BABYLON.serialize(),
  45711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45712. ], PBRMaterial.prototype, "metallic", void 0);
  45713. __decorate([
  45714. BABYLON.serialize(),
  45715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45716. ], PBRMaterial.prototype, "roughness", void 0);
  45717. __decorate([
  45718. BABYLON.serializeAsTexture(),
  45719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45720. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45721. __decorate([
  45722. BABYLON.serializeAsTexture(),
  45723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45724. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45725. __decorate([
  45726. BABYLON.serializeAsTexture(),
  45727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45728. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45729. __decorate([
  45730. BABYLON.serializeAsTexture(),
  45731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45732. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45733. __decorate([
  45734. BABYLON.serializeAsColor3("ambient"),
  45735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45736. ], PBRMaterial.prototype, "ambientColor", void 0);
  45737. __decorate([
  45738. BABYLON.serializeAsColor3("albedo"),
  45739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45740. ], PBRMaterial.prototype, "albedoColor", void 0);
  45741. __decorate([
  45742. BABYLON.serializeAsColor3("reflectivity"),
  45743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45744. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45745. __decorate([
  45746. BABYLON.serializeAsColor3("reflection"),
  45747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45748. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45749. __decorate([
  45750. BABYLON.serializeAsColor3("emissive"),
  45751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45752. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45753. __decorate([
  45754. BABYLON.serialize(),
  45755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45756. ], PBRMaterial.prototype, "microSurface", void 0);
  45757. __decorate([
  45758. BABYLON.serialize(),
  45759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45760. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45761. __decorate([
  45762. BABYLON.serialize(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45764. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45765. __decorate([
  45766. BABYLON.serialize(),
  45767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45768. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45769. __decorate([
  45770. BABYLON.serialize(),
  45771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45772. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45773. __decorate([
  45774. BABYLON.serialize(),
  45775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45776. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45777. __decorate([
  45778. BABYLON.serialize(),
  45779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45780. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45781. __decorate([
  45782. BABYLON.serialize(),
  45783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45784. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45785. __decorate([
  45786. BABYLON.serialize(),
  45787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45788. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45789. __decorate([
  45790. BABYLON.serialize(),
  45791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45792. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45793. __decorate([
  45794. BABYLON.serialize(),
  45795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45796. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45797. __decorate([
  45798. BABYLON.serialize(),
  45799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45800. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45801. __decorate([
  45802. BABYLON.serialize(),
  45803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45804. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45805. __decorate([
  45806. BABYLON.serialize(),
  45807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45808. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45809. __decorate([
  45810. BABYLON.serialize(),
  45811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45812. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45813. __decorate([
  45814. BABYLON.serialize(),
  45815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45816. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45817. __decorate([
  45818. BABYLON.serialize(),
  45819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45820. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45821. __decorate([
  45822. BABYLON.serialize(),
  45823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45824. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45825. __decorate([
  45826. BABYLON.serialize(),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45828. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45829. __decorate([
  45830. BABYLON.serialize(),
  45831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45832. ], PBRMaterial.prototype, "useParallax", void 0);
  45833. __decorate([
  45834. BABYLON.serialize(),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45836. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45837. __decorate([
  45838. BABYLON.serialize(),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45840. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45841. __decorate([
  45842. BABYLON.serialize(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45844. ], PBRMaterial.prototype, "disableLighting", void 0);
  45845. __decorate([
  45846. BABYLON.serialize(),
  45847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45848. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45849. __decorate([
  45850. BABYLON.serialize(),
  45851. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45852. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45853. __decorate([
  45854. BABYLON.serialize(),
  45855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45856. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45857. __decorate([
  45858. BABYLON.serialize(),
  45859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45860. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45861. __decorate([
  45862. BABYLON.serialize(),
  45863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45864. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45865. __decorate([
  45866. BABYLON.serialize(),
  45867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45868. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45869. __decorate([
  45870. BABYLON.serialize(),
  45871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45872. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45873. __decorate([
  45874. BABYLON.serializeAsTexture(),
  45875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45876. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45877. __decorate([
  45878. BABYLON.serialize(),
  45879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45880. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45881. __decorate([
  45882. BABYLON.serialize(),
  45883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45884. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45885. __decorate([
  45886. BABYLON.serialize(),
  45887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45888. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45889. __decorate([
  45890. BABYLON.serialize(),
  45891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45892. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45893. __decorate([
  45894. BABYLON.serialize(),
  45895. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45896. ], PBRMaterial.prototype, "unlit", void 0);
  45897. return PBRMaterial;
  45898. }(BABYLON.PBRBaseMaterial));
  45899. BABYLON.PBRMaterial = PBRMaterial;
  45900. })(BABYLON || (BABYLON = {}));
  45901. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45902. "use strict";
  45903. var BABYLON;
  45904. (function (BABYLON) {
  45905. /**
  45906. * The PBR material of BJS following the metal roughness convention.
  45907. *
  45908. * This fits to the PBR convention in the GLTF definition:
  45909. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45910. */
  45911. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45912. __extends(PBRMetallicRoughnessMaterial, _super);
  45913. /**
  45914. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45915. *
  45916. * @param name The material name
  45917. * @param scene The scene the material will be use in.
  45918. */
  45919. function PBRMetallicRoughnessMaterial(name, scene) {
  45920. var _this = _super.call(this, name, scene) || this;
  45921. _this._useRoughnessFromMetallicTextureAlpha = false;
  45922. _this._useRoughnessFromMetallicTextureGreen = true;
  45923. _this._useMetallnessFromMetallicTextureBlue = true;
  45924. _this.metallic = 1.0;
  45925. _this.roughness = 1.0;
  45926. return _this;
  45927. }
  45928. /**
  45929. * Return the currrent class name of the material.
  45930. */
  45931. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45932. return "PBRMetallicRoughnessMaterial";
  45933. };
  45934. /**
  45935. * Return the active textures of the material.
  45936. */
  45937. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45938. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45939. if (this.baseTexture) {
  45940. activeTextures.push(this.baseTexture);
  45941. }
  45942. if (this.metallicRoughnessTexture) {
  45943. activeTextures.push(this.metallicRoughnessTexture);
  45944. }
  45945. return activeTextures;
  45946. };
  45947. /**
  45948. * Checks to see if a texture is used in the material.
  45949. * @param texture - Base texture to use.
  45950. * @returns - Boolean specifying if a texture is used in the material.
  45951. */
  45952. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45953. if (_super.prototype.hasTexture.call(this, texture)) {
  45954. return true;
  45955. }
  45956. if (this.baseTexture === texture) {
  45957. return true;
  45958. }
  45959. if (this.metallicRoughnessTexture === texture) {
  45960. return true;
  45961. }
  45962. return false;
  45963. };
  45964. /**
  45965. * Makes a duplicate of the current material.
  45966. * @param name - name to use for the new material.
  45967. */
  45968. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45969. var _this = this;
  45970. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45971. clone.id = name;
  45972. clone.name = name;
  45973. return clone;
  45974. };
  45975. /**
  45976. * Serialize the material to a parsable JSON object.
  45977. */
  45978. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45979. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45980. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45981. return serializationObject;
  45982. };
  45983. /**
  45984. * Parses a JSON object correponding to the serialize function.
  45985. */
  45986. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45987. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45988. };
  45989. __decorate([
  45990. BABYLON.serializeAsColor3(),
  45991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45992. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45993. __decorate([
  45994. BABYLON.serializeAsTexture(),
  45995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45996. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45997. __decorate([
  45998. BABYLON.serialize(),
  45999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46000. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46001. __decorate([
  46002. BABYLON.serialize(),
  46003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46004. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46005. __decorate([
  46006. BABYLON.serializeAsTexture(),
  46007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46008. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46009. return PBRMetallicRoughnessMaterial;
  46010. }(BABYLON.PBRBaseSimpleMaterial));
  46011. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46012. })(BABYLON || (BABYLON = {}));
  46013. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46014. "use strict";
  46015. var BABYLON;
  46016. (function (BABYLON) {
  46017. /**
  46018. * The PBR material of BJS following the specular glossiness convention.
  46019. *
  46020. * This fits to the PBR convention in the GLTF definition:
  46021. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46022. */
  46023. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46024. __extends(PBRSpecularGlossinessMaterial, _super);
  46025. /**
  46026. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46027. *
  46028. * @param name The material name
  46029. * @param scene The scene the material will be use in.
  46030. */
  46031. function PBRSpecularGlossinessMaterial(name, scene) {
  46032. var _this = _super.call(this, name, scene) || this;
  46033. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46034. return _this;
  46035. }
  46036. /**
  46037. * Return the currrent class name of the material.
  46038. */
  46039. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46040. return "PBRSpecularGlossinessMaterial";
  46041. };
  46042. /**
  46043. * Return the active textures of the material.
  46044. */
  46045. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46046. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46047. if (this.diffuseTexture) {
  46048. activeTextures.push(this.diffuseTexture);
  46049. }
  46050. if (this.specularGlossinessTexture) {
  46051. activeTextures.push(this.specularGlossinessTexture);
  46052. }
  46053. return activeTextures;
  46054. };
  46055. /**
  46056. * Checks to see if a texture is used in the material.
  46057. * @param texture - Base texture to use.
  46058. * @returns - Boolean specifying if a texture is used in the material.
  46059. */
  46060. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46061. if (_super.prototype.hasTexture.call(this, texture)) {
  46062. return true;
  46063. }
  46064. if (this.diffuseTexture === texture) {
  46065. return true;
  46066. }
  46067. if (this.specularGlossinessTexture === texture) {
  46068. return true;
  46069. }
  46070. return false;
  46071. };
  46072. /**
  46073. * Makes a duplicate of the current material.
  46074. * @param name - name to use for the new material.
  46075. */
  46076. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46077. var _this = this;
  46078. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46079. clone.id = name;
  46080. clone.name = name;
  46081. return clone;
  46082. };
  46083. /**
  46084. * Serialize the material to a parsable JSON object.
  46085. */
  46086. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46087. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46088. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46089. return serializationObject;
  46090. };
  46091. /**
  46092. * Parses a JSON object correponding to the serialize function.
  46093. */
  46094. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46095. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46096. };
  46097. __decorate([
  46098. BABYLON.serializeAsColor3("diffuse"),
  46099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46100. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46101. __decorate([
  46102. BABYLON.serializeAsTexture(),
  46103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46104. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46105. __decorate([
  46106. BABYLON.serializeAsColor3("specular"),
  46107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46108. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46109. __decorate([
  46110. BABYLON.serialize(),
  46111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46112. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46113. __decorate([
  46114. BABYLON.serializeAsTexture(),
  46115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46116. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46117. return PBRSpecularGlossinessMaterial;
  46118. }(BABYLON.PBRBaseSimpleMaterial));
  46119. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46120. })(BABYLON || (BABYLON = {}));
  46121. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46122. "use strict";
  46123. var BABYLON;
  46124. (function (BABYLON) {
  46125. BABYLON.CameraInputTypes = {};
  46126. var CameraInputsManager = /** @class */ (function () {
  46127. function CameraInputsManager(camera) {
  46128. this.attached = {};
  46129. this.camera = camera;
  46130. this.checkInputs = function () { };
  46131. }
  46132. /**
  46133. * Add an input method to a camera.
  46134. * builtin inputs example: camera.inputs.addGamepad();
  46135. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46136. * @param input camera input method
  46137. */
  46138. CameraInputsManager.prototype.add = function (input) {
  46139. var type = input.getSimpleName();
  46140. if (this.attached[type]) {
  46141. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46142. return;
  46143. }
  46144. this.attached[type] = input;
  46145. input.camera = this.camera;
  46146. //for checkInputs, we are dynamically creating a function
  46147. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46148. if (input.checkInputs) {
  46149. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46150. }
  46151. if (this.attachedElement) {
  46152. input.attachControl(this.attachedElement);
  46153. }
  46154. };
  46155. /**
  46156. * Remove a specific input method from a camera
  46157. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46158. * @param inputToRemove camera input method
  46159. */
  46160. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46161. for (var cam in this.attached) {
  46162. var input = this.attached[cam];
  46163. if (input === inputToRemove) {
  46164. input.detachControl(this.attachedElement);
  46165. input.camera = null;
  46166. delete this.attached[cam];
  46167. this.rebuildInputCheck();
  46168. }
  46169. }
  46170. };
  46171. CameraInputsManager.prototype.removeByType = function (inputType) {
  46172. for (var cam in this.attached) {
  46173. var input = this.attached[cam];
  46174. if (input.getClassName() === inputType) {
  46175. input.detachControl(this.attachedElement);
  46176. input.camera = null;
  46177. delete this.attached[cam];
  46178. this.rebuildInputCheck();
  46179. }
  46180. }
  46181. };
  46182. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46183. var current = this.checkInputs;
  46184. return function () {
  46185. current();
  46186. fn();
  46187. };
  46188. };
  46189. CameraInputsManager.prototype.attachInput = function (input) {
  46190. if (this.attachedElement) {
  46191. input.attachControl(this.attachedElement, this.noPreventDefault);
  46192. }
  46193. };
  46194. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46195. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46196. if (this.attachedElement) {
  46197. return;
  46198. }
  46199. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46200. this.attachedElement = element;
  46201. this.noPreventDefault = noPreventDefault;
  46202. for (var cam in this.attached) {
  46203. this.attached[cam].attachControl(element, noPreventDefault);
  46204. }
  46205. };
  46206. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46207. if (disconnect === void 0) { disconnect = false; }
  46208. if (this.attachedElement !== element) {
  46209. return;
  46210. }
  46211. for (var cam in this.attached) {
  46212. this.attached[cam].detachControl(element);
  46213. if (disconnect) {
  46214. this.attached[cam].camera = null;
  46215. }
  46216. }
  46217. this.attachedElement = null;
  46218. };
  46219. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46220. this.checkInputs = function () { };
  46221. for (var cam in this.attached) {
  46222. var input = this.attached[cam];
  46223. if (input.checkInputs) {
  46224. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46225. }
  46226. }
  46227. };
  46228. /**
  46229. * Remove all attached input methods from a camera
  46230. */
  46231. CameraInputsManager.prototype.clear = function () {
  46232. if (this.attachedElement) {
  46233. this.detachElement(this.attachedElement, true);
  46234. }
  46235. this.attached = {};
  46236. this.attachedElement = null;
  46237. this.checkInputs = function () { };
  46238. };
  46239. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46240. var inputs = {};
  46241. for (var cam in this.attached) {
  46242. var input = this.attached[cam];
  46243. var res = BABYLON.SerializationHelper.Serialize(input);
  46244. inputs[input.getClassName()] = res;
  46245. }
  46246. serializedCamera.inputsmgr = inputs;
  46247. };
  46248. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46249. var parsedInputs = parsedCamera.inputsmgr;
  46250. if (parsedInputs) {
  46251. this.clear();
  46252. for (var n in parsedInputs) {
  46253. var construct = BABYLON.CameraInputTypes[n];
  46254. if (construct) {
  46255. var parsedinput = parsedInputs[n];
  46256. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46257. this.add(input);
  46258. }
  46259. }
  46260. }
  46261. else {
  46262. //2016-03-08 this part is for managing backward compatibility
  46263. for (var n in this.attached) {
  46264. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46265. if (construct) {
  46266. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46267. this.remove(this.attached[n]);
  46268. this.add(input);
  46269. }
  46270. }
  46271. }
  46272. };
  46273. return CameraInputsManager;
  46274. }());
  46275. BABYLON.CameraInputsManager = CameraInputsManager;
  46276. })(BABYLON || (BABYLON = {}));
  46277. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46278. "use strict";
  46279. var BABYLON;
  46280. (function (BABYLON) {
  46281. var TargetCamera = /** @class */ (function (_super) {
  46282. __extends(TargetCamera, _super);
  46283. function TargetCamera(name, position, scene) {
  46284. var _this = _super.call(this, name, position, scene) || this;
  46285. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46286. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46287. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46288. _this.speed = 2.0;
  46289. _this.noRotationConstraint = false;
  46290. _this.lockedTarget = null;
  46291. _this._currentTarget = BABYLON.Vector3.Zero();
  46292. _this._viewMatrix = BABYLON.Matrix.Zero();
  46293. _this._camMatrix = BABYLON.Matrix.Zero();
  46294. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46295. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46296. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46297. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46298. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46299. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46300. _this._tempMatrix = BABYLON.Matrix.Zero();
  46301. return _this;
  46302. }
  46303. TargetCamera.prototype.getFrontPosition = function (distance) {
  46304. this.getWorldMatrix();
  46305. var direction = this.getTarget().subtract(this.position);
  46306. direction.normalize();
  46307. direction.scaleInPlace(distance);
  46308. return this.globalPosition.add(direction);
  46309. };
  46310. TargetCamera.prototype._getLockedTargetPosition = function () {
  46311. if (!this.lockedTarget) {
  46312. return null;
  46313. }
  46314. if (this.lockedTarget.absolutePosition) {
  46315. this.lockedTarget.computeWorldMatrix();
  46316. }
  46317. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46318. };
  46319. TargetCamera.prototype.storeState = function () {
  46320. this._storedPosition = this.position.clone();
  46321. this._storedRotation = this.rotation.clone();
  46322. if (this.rotationQuaternion) {
  46323. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46324. }
  46325. return _super.prototype.storeState.call(this);
  46326. };
  46327. /**
  46328. * Restored camera state. You must call storeState() first
  46329. */
  46330. TargetCamera.prototype._restoreStateValues = function () {
  46331. if (!_super.prototype._restoreStateValues.call(this)) {
  46332. return false;
  46333. }
  46334. this.position = this._storedPosition.clone();
  46335. this.rotation = this._storedRotation.clone();
  46336. if (this.rotationQuaternion) {
  46337. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46338. }
  46339. this.cameraDirection.copyFromFloats(0, 0, 0);
  46340. this.cameraRotation.copyFromFloats(0, 0);
  46341. return true;
  46342. };
  46343. // Cache
  46344. TargetCamera.prototype._initCache = function () {
  46345. _super.prototype._initCache.call(this);
  46346. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46347. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46348. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46349. };
  46350. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46351. if (!ignoreParentClass) {
  46352. _super.prototype._updateCache.call(this);
  46353. }
  46354. var lockedTargetPosition = this._getLockedTargetPosition();
  46355. if (!lockedTargetPosition) {
  46356. this._cache.lockedTarget = null;
  46357. }
  46358. else {
  46359. if (!this._cache.lockedTarget) {
  46360. this._cache.lockedTarget = lockedTargetPosition.clone();
  46361. }
  46362. else {
  46363. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46364. }
  46365. }
  46366. this._cache.rotation.copyFrom(this.rotation);
  46367. if (this.rotationQuaternion)
  46368. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46369. };
  46370. // Synchronized
  46371. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46372. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46373. return false;
  46374. }
  46375. var lockedTargetPosition = this._getLockedTargetPosition();
  46376. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46377. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46378. };
  46379. // Methods
  46380. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46381. var engine = this.getEngine();
  46382. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46383. };
  46384. // Target
  46385. TargetCamera.prototype.setTarget = function (target) {
  46386. this.upVector.normalize();
  46387. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46388. this._camMatrix.invert();
  46389. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46390. var vDir = target.subtract(this.position);
  46391. if (vDir.x >= 0.0) {
  46392. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46393. }
  46394. else {
  46395. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46396. }
  46397. this.rotation.z = 0;
  46398. if (isNaN(this.rotation.x)) {
  46399. this.rotation.x = 0;
  46400. }
  46401. if (isNaN(this.rotation.y)) {
  46402. this.rotation.y = 0;
  46403. }
  46404. if (isNaN(this.rotation.z)) {
  46405. this.rotation.z = 0;
  46406. }
  46407. if (this.rotationQuaternion) {
  46408. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46409. }
  46410. };
  46411. /**
  46412. * Return the current target position of the camera. This value is expressed in local space.
  46413. */
  46414. TargetCamera.prototype.getTarget = function () {
  46415. return this._currentTarget;
  46416. };
  46417. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46418. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46419. };
  46420. TargetCamera.prototype._updatePosition = function () {
  46421. if (this.parent) {
  46422. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46423. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46424. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46425. return;
  46426. }
  46427. this.position.addInPlace(this.cameraDirection);
  46428. };
  46429. TargetCamera.prototype._checkInputs = function () {
  46430. var needToMove = this._decideIfNeedsToMove();
  46431. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46432. // Move
  46433. if (needToMove) {
  46434. this._updatePosition();
  46435. }
  46436. // Rotate
  46437. if (needToRotate) {
  46438. this.rotation.x += this.cameraRotation.x;
  46439. this.rotation.y += this.cameraRotation.y;
  46440. //rotate, if quaternion is set and rotation was used
  46441. if (this.rotationQuaternion) {
  46442. var len = this.rotation.lengthSquared();
  46443. if (len) {
  46444. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46445. }
  46446. }
  46447. if (!this.noRotationConstraint) {
  46448. var limit = (Math.PI / 2) * 0.95;
  46449. if (this.rotation.x > limit)
  46450. this.rotation.x = limit;
  46451. if (this.rotation.x < -limit)
  46452. this.rotation.x = -limit;
  46453. }
  46454. }
  46455. // Inertia
  46456. if (needToMove) {
  46457. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46458. this.cameraDirection.x = 0;
  46459. }
  46460. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46461. this.cameraDirection.y = 0;
  46462. }
  46463. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46464. this.cameraDirection.z = 0;
  46465. }
  46466. this.cameraDirection.scaleInPlace(this.inertia);
  46467. }
  46468. if (needToRotate) {
  46469. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46470. this.cameraRotation.x = 0;
  46471. }
  46472. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46473. this.cameraRotation.y = 0;
  46474. }
  46475. this.cameraRotation.scaleInPlace(this.inertia);
  46476. }
  46477. _super.prototype._checkInputs.call(this);
  46478. };
  46479. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46480. if (this.rotationQuaternion) {
  46481. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46482. }
  46483. else {
  46484. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46485. }
  46486. //update the up vector!
  46487. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46488. };
  46489. TargetCamera.prototype._getViewMatrix = function () {
  46490. if (this.lockedTarget) {
  46491. this.setTarget(this._getLockedTargetPosition());
  46492. }
  46493. // Compute
  46494. this._updateCameraRotationMatrix();
  46495. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46496. // Computing target and final matrix
  46497. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46498. if (this.getScene().useRightHandedSystem) {
  46499. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46500. }
  46501. else {
  46502. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46503. }
  46504. return this._viewMatrix;
  46505. };
  46506. /**
  46507. * @override
  46508. * Override Camera.createRigCamera
  46509. */
  46510. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46511. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46512. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46513. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46514. if (!this.rotationQuaternion) {
  46515. this.rotationQuaternion = new BABYLON.Quaternion();
  46516. }
  46517. rigCamera._cameraRigParams = {};
  46518. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46519. }
  46520. return rigCamera;
  46521. }
  46522. return null;
  46523. };
  46524. /**
  46525. * @override
  46526. * Override Camera._updateRigCameras
  46527. */
  46528. TargetCamera.prototype._updateRigCameras = function () {
  46529. var camLeft = this._rigCameras[0];
  46530. var camRight = this._rigCameras[1];
  46531. switch (this.cameraRigMode) {
  46532. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46533. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46534. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46535. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46536. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46537. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46538. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46539. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46540. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46541. camLeft.setTarget(this.getTarget());
  46542. camRight.setTarget(this.getTarget());
  46543. break;
  46544. case BABYLON.Camera.RIG_MODE_VR:
  46545. if (camLeft.rotationQuaternion) {
  46546. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46547. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46548. }
  46549. else {
  46550. camLeft.rotation.copyFrom(this.rotation);
  46551. camRight.rotation.copyFrom(this.rotation);
  46552. }
  46553. camLeft.position.copyFrom(this.position);
  46554. camRight.position.copyFrom(this.position);
  46555. break;
  46556. }
  46557. _super.prototype._updateRigCameras.call(this);
  46558. };
  46559. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46560. if (!this._rigCamTransformMatrix) {
  46561. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46562. }
  46563. var target = this.getTarget();
  46564. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46565. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46566. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46567. };
  46568. TargetCamera.prototype.getClassName = function () {
  46569. return "TargetCamera";
  46570. };
  46571. __decorate([
  46572. BABYLON.serializeAsVector3()
  46573. ], TargetCamera.prototype, "rotation", void 0);
  46574. __decorate([
  46575. BABYLON.serialize()
  46576. ], TargetCamera.prototype, "speed", void 0);
  46577. __decorate([
  46578. BABYLON.serializeAsMeshReference("lockedTargetId")
  46579. ], TargetCamera.prototype, "lockedTarget", void 0);
  46580. return TargetCamera;
  46581. }(BABYLON.Camera));
  46582. BABYLON.TargetCamera = TargetCamera;
  46583. })(BABYLON || (BABYLON = {}));
  46584. //# sourceMappingURL=babylon.targetCamera.js.map
  46585. "use strict";
  46586. var BABYLON;
  46587. (function (BABYLON) {
  46588. var FreeCameraMouseInput = /** @class */ (function () {
  46589. function FreeCameraMouseInput(touchEnabled) {
  46590. if (touchEnabled === void 0) { touchEnabled = true; }
  46591. this.touchEnabled = touchEnabled;
  46592. this.buttons = [0, 1, 2];
  46593. this.angularSensibility = 2000.0;
  46594. this.previousPosition = null;
  46595. }
  46596. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46597. var _this = this;
  46598. var engine = this.camera.getEngine();
  46599. if (!this._pointerInput) {
  46600. this._pointerInput = function (p, s) {
  46601. var evt = p.event;
  46602. if (engine.isInVRExclusivePointerMode) {
  46603. return;
  46604. }
  46605. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46606. return;
  46607. }
  46608. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46609. return;
  46610. }
  46611. var srcElement = (evt.srcElement || evt.target);
  46612. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46613. try {
  46614. srcElement.setPointerCapture(evt.pointerId);
  46615. }
  46616. catch (e) {
  46617. //Nothing to do with the error. Execution will continue.
  46618. }
  46619. _this.previousPosition = {
  46620. x: evt.clientX,
  46621. y: evt.clientY
  46622. };
  46623. if (!noPreventDefault) {
  46624. evt.preventDefault();
  46625. element.focus();
  46626. }
  46627. }
  46628. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46629. try {
  46630. srcElement.releasePointerCapture(evt.pointerId);
  46631. }
  46632. catch (e) {
  46633. //Nothing to do with the error.
  46634. }
  46635. _this.previousPosition = null;
  46636. if (!noPreventDefault) {
  46637. evt.preventDefault();
  46638. }
  46639. }
  46640. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46641. if (!_this.previousPosition || engine.isPointerLock) {
  46642. return;
  46643. }
  46644. var offsetX = evt.clientX - _this.previousPosition.x;
  46645. var offsetY = evt.clientY - _this.previousPosition.y;
  46646. if (_this.camera.getScene().useRightHandedSystem) {
  46647. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46648. }
  46649. else {
  46650. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46651. }
  46652. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46653. _this.previousPosition = {
  46654. x: evt.clientX,
  46655. y: evt.clientY
  46656. };
  46657. if (!noPreventDefault) {
  46658. evt.preventDefault();
  46659. }
  46660. }
  46661. };
  46662. }
  46663. this._onMouseMove = function (evt) {
  46664. if (!engine.isPointerLock) {
  46665. return;
  46666. }
  46667. if (engine.isInVRExclusivePointerMode) {
  46668. return;
  46669. }
  46670. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46671. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46672. if (_this.camera.getScene().useRightHandedSystem) {
  46673. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46674. }
  46675. else {
  46676. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46677. }
  46678. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46679. _this.previousPosition = null;
  46680. if (!noPreventDefault) {
  46681. evt.preventDefault();
  46682. }
  46683. };
  46684. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46685. element.addEventListener("mousemove", this._onMouseMove, false);
  46686. };
  46687. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46688. if (this._observer && element) {
  46689. this.camera.getScene().onPointerObservable.remove(this._observer);
  46690. if (this._onMouseMove) {
  46691. element.removeEventListener("mousemove", this._onMouseMove);
  46692. }
  46693. this._observer = null;
  46694. this._onMouseMove = null;
  46695. this.previousPosition = null;
  46696. }
  46697. };
  46698. FreeCameraMouseInput.prototype.getClassName = function () {
  46699. return "FreeCameraMouseInput";
  46700. };
  46701. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46702. return "mouse";
  46703. };
  46704. __decorate([
  46705. BABYLON.serialize()
  46706. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46707. __decorate([
  46708. BABYLON.serialize()
  46709. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46710. return FreeCameraMouseInput;
  46711. }());
  46712. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46713. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46714. })(BABYLON || (BABYLON = {}));
  46715. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46716. "use strict";
  46717. var BABYLON;
  46718. (function (BABYLON) {
  46719. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46720. function FreeCameraKeyboardMoveInput() {
  46721. this._keys = new Array();
  46722. this.keysUp = [38];
  46723. this.keysDown = [40];
  46724. this.keysLeft = [37];
  46725. this.keysRight = [39];
  46726. }
  46727. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46728. var _this = this;
  46729. if (this._onCanvasBlurObserver) {
  46730. return;
  46731. }
  46732. this._scene = this.camera.getScene();
  46733. this._engine = this._scene.getEngine();
  46734. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46735. _this._keys = [];
  46736. });
  46737. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46738. var evt = info.event;
  46739. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46740. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46741. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46742. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46743. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46744. var index = _this._keys.indexOf(evt.keyCode);
  46745. if (index === -1) {
  46746. _this._keys.push(evt.keyCode);
  46747. }
  46748. if (!noPreventDefault) {
  46749. evt.preventDefault();
  46750. }
  46751. }
  46752. }
  46753. else {
  46754. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46755. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46756. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46757. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46758. var index = _this._keys.indexOf(evt.keyCode);
  46759. if (index >= 0) {
  46760. _this._keys.splice(index, 1);
  46761. }
  46762. if (!noPreventDefault) {
  46763. evt.preventDefault();
  46764. }
  46765. }
  46766. }
  46767. });
  46768. };
  46769. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46770. if (this._scene) {
  46771. if (this._onKeyboardObserver) {
  46772. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46773. }
  46774. if (this._onCanvasBlurObserver) {
  46775. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46776. }
  46777. this._onKeyboardObserver = null;
  46778. this._onCanvasBlurObserver = null;
  46779. }
  46780. this._keys = [];
  46781. };
  46782. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46783. if (this._onKeyboardObserver) {
  46784. var camera = this.camera;
  46785. // Keyboard
  46786. for (var index = 0; index < this._keys.length; index++) {
  46787. var keyCode = this._keys[index];
  46788. var speed = camera._computeLocalCameraSpeed();
  46789. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46790. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46791. }
  46792. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46793. camera._localDirection.copyFromFloats(0, 0, speed);
  46794. }
  46795. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46796. camera._localDirection.copyFromFloats(speed, 0, 0);
  46797. }
  46798. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46799. camera._localDirection.copyFromFloats(0, 0, -speed);
  46800. }
  46801. if (camera.getScene().useRightHandedSystem) {
  46802. camera._localDirection.z *= -1;
  46803. }
  46804. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46805. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46806. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46807. }
  46808. }
  46809. };
  46810. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46811. return "FreeCameraKeyboardMoveInput";
  46812. };
  46813. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46814. this._keys = [];
  46815. };
  46816. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46817. return "keyboard";
  46818. };
  46819. __decorate([
  46820. BABYLON.serialize()
  46821. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46822. __decorate([
  46823. BABYLON.serialize()
  46824. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46825. __decorate([
  46826. BABYLON.serialize()
  46827. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46828. __decorate([
  46829. BABYLON.serialize()
  46830. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46831. return FreeCameraKeyboardMoveInput;
  46832. }());
  46833. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46834. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46835. })(BABYLON || (BABYLON = {}));
  46836. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46837. "use strict";
  46838. var BABYLON;
  46839. (function (BABYLON) {
  46840. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46841. __extends(FreeCameraInputsManager, _super);
  46842. function FreeCameraInputsManager(camera) {
  46843. return _super.call(this, camera) || this;
  46844. }
  46845. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46846. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46847. return this;
  46848. };
  46849. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46850. if (touchEnabled === void 0) { touchEnabled = true; }
  46851. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46852. return this;
  46853. };
  46854. FreeCameraInputsManager.prototype.addGamepad = function () {
  46855. this.add(new BABYLON.FreeCameraGamepadInput());
  46856. return this;
  46857. };
  46858. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46859. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46860. return this;
  46861. };
  46862. FreeCameraInputsManager.prototype.addTouch = function () {
  46863. this.add(new BABYLON.FreeCameraTouchInput());
  46864. return this;
  46865. };
  46866. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46867. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46868. return this;
  46869. };
  46870. return FreeCameraInputsManager;
  46871. }(BABYLON.CameraInputsManager));
  46872. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46873. })(BABYLON || (BABYLON = {}));
  46874. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46875. "use strict";
  46876. var BABYLON;
  46877. (function (BABYLON) {
  46878. var FreeCamera = /** @class */ (function (_super) {
  46879. __extends(FreeCamera, _super);
  46880. function FreeCamera(name, position, scene) {
  46881. var _this = _super.call(this, name, position, scene) || this;
  46882. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46883. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46884. _this.checkCollisions = false;
  46885. _this.applyGravity = false;
  46886. _this._needMoveForGravity = false;
  46887. _this._oldPosition = BABYLON.Vector3.Zero();
  46888. _this._diffPosition = BABYLON.Vector3.Zero();
  46889. _this._newPosition = BABYLON.Vector3.Zero();
  46890. // Collisions
  46891. _this._collisionMask = -1;
  46892. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46893. if (collidedMesh === void 0) { collidedMesh = null; }
  46894. //TODO move this to the collision coordinator!
  46895. if (_this.getScene().workerCollisions)
  46896. newPosition.multiplyInPlace(_this._collider._radius);
  46897. var updatePosition = function (newPos) {
  46898. _this._newPosition.copyFrom(newPos);
  46899. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46900. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46901. _this.position.addInPlace(_this._diffPosition);
  46902. if (_this.onCollide && collidedMesh) {
  46903. _this.onCollide(collidedMesh);
  46904. }
  46905. }
  46906. };
  46907. updatePosition(newPosition);
  46908. };
  46909. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46910. _this.inputs.addKeyboard().addMouse();
  46911. return _this;
  46912. }
  46913. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46914. //-- begin properties for backward compatibility for inputs
  46915. /**
  46916. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46917. * Higher values reduce sensitivity.
  46918. */
  46919. get: function () {
  46920. var mouse = this.inputs.attached["mouse"];
  46921. if (mouse)
  46922. return mouse.angularSensibility;
  46923. return 0;
  46924. },
  46925. /**
  46926. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46927. * Higher values reduce sensitivity.
  46928. */
  46929. set: function (value) {
  46930. var mouse = this.inputs.attached["mouse"];
  46931. if (mouse)
  46932. mouse.angularSensibility = value;
  46933. },
  46934. enumerable: true,
  46935. configurable: true
  46936. });
  46937. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46938. get: function () {
  46939. var keyboard = this.inputs.attached["keyboard"];
  46940. if (keyboard)
  46941. return keyboard.keysUp;
  46942. return [];
  46943. },
  46944. set: function (value) {
  46945. var keyboard = this.inputs.attached["keyboard"];
  46946. if (keyboard)
  46947. keyboard.keysUp = value;
  46948. },
  46949. enumerable: true,
  46950. configurable: true
  46951. });
  46952. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46953. get: function () {
  46954. var keyboard = this.inputs.attached["keyboard"];
  46955. if (keyboard)
  46956. return keyboard.keysDown;
  46957. return [];
  46958. },
  46959. set: function (value) {
  46960. var keyboard = this.inputs.attached["keyboard"];
  46961. if (keyboard)
  46962. keyboard.keysDown = value;
  46963. },
  46964. enumerable: true,
  46965. configurable: true
  46966. });
  46967. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46968. get: function () {
  46969. var keyboard = this.inputs.attached["keyboard"];
  46970. if (keyboard)
  46971. return keyboard.keysLeft;
  46972. return [];
  46973. },
  46974. set: function (value) {
  46975. var keyboard = this.inputs.attached["keyboard"];
  46976. if (keyboard)
  46977. keyboard.keysLeft = value;
  46978. },
  46979. enumerable: true,
  46980. configurable: true
  46981. });
  46982. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46983. get: function () {
  46984. var keyboard = this.inputs.attached["keyboard"];
  46985. if (keyboard)
  46986. return keyboard.keysRight;
  46987. return [];
  46988. },
  46989. set: function (value) {
  46990. var keyboard = this.inputs.attached["keyboard"];
  46991. if (keyboard)
  46992. keyboard.keysRight = value;
  46993. },
  46994. enumerable: true,
  46995. configurable: true
  46996. });
  46997. // Controls
  46998. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46999. this.inputs.attachElement(element, noPreventDefault);
  47000. };
  47001. FreeCamera.prototype.detachControl = function (element) {
  47002. this.inputs.detachElement(element);
  47003. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47004. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47005. };
  47006. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47007. get: function () {
  47008. return this._collisionMask;
  47009. },
  47010. set: function (mask) {
  47011. this._collisionMask = !isNaN(mask) ? mask : -1;
  47012. },
  47013. enumerable: true,
  47014. configurable: true
  47015. });
  47016. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47017. var globalPosition;
  47018. if (this.parent) {
  47019. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47020. }
  47021. else {
  47022. globalPosition = this.position;
  47023. }
  47024. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47025. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47026. if (!this._collider) {
  47027. this._collider = new BABYLON.Collider();
  47028. }
  47029. this._collider._radius = this.ellipsoid;
  47030. this._collider.collisionMask = this._collisionMask;
  47031. //no need for clone, as long as gravity is not on.
  47032. var actualDisplacement = displacement;
  47033. //add gravity to the direction to prevent the dual-collision checking
  47034. if (this.applyGravity) {
  47035. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47036. actualDisplacement = displacement.add(this.getScene().gravity);
  47037. }
  47038. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47039. };
  47040. FreeCamera.prototype._checkInputs = function () {
  47041. if (!this._localDirection) {
  47042. this._localDirection = BABYLON.Vector3.Zero();
  47043. this._transformedDirection = BABYLON.Vector3.Zero();
  47044. }
  47045. this.inputs.checkInputs();
  47046. _super.prototype._checkInputs.call(this);
  47047. };
  47048. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47049. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47050. };
  47051. FreeCamera.prototype._updatePosition = function () {
  47052. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47053. this._collideWithWorld(this.cameraDirection);
  47054. }
  47055. else {
  47056. _super.prototype._updatePosition.call(this);
  47057. }
  47058. };
  47059. FreeCamera.prototype.dispose = function () {
  47060. this.inputs.clear();
  47061. _super.prototype.dispose.call(this);
  47062. };
  47063. FreeCamera.prototype.getClassName = function () {
  47064. return "FreeCamera";
  47065. };
  47066. __decorate([
  47067. BABYLON.serializeAsVector3()
  47068. ], FreeCamera.prototype, "ellipsoid", void 0);
  47069. __decorate([
  47070. BABYLON.serializeAsVector3()
  47071. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47072. __decorate([
  47073. BABYLON.serialize()
  47074. ], FreeCamera.prototype, "checkCollisions", void 0);
  47075. __decorate([
  47076. BABYLON.serialize()
  47077. ], FreeCamera.prototype, "applyGravity", void 0);
  47078. return FreeCamera;
  47079. }(BABYLON.TargetCamera));
  47080. BABYLON.FreeCamera = FreeCamera;
  47081. })(BABYLON || (BABYLON = {}));
  47082. //# sourceMappingURL=babylon.freeCamera.js.map
  47083. "use strict";
  47084. var BABYLON;
  47085. (function (BABYLON) {
  47086. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47087. function ArcRotateCameraKeyboardMoveInput() {
  47088. this._keys = new Array();
  47089. this.keysUp = [38];
  47090. this.keysDown = [40];
  47091. this.keysLeft = [37];
  47092. this.keysRight = [39];
  47093. this.keysReset = [220];
  47094. this.panningSensibility = 50.0;
  47095. this.zoomingSensibility = 25.0;
  47096. this.useAltToZoom = true;
  47097. }
  47098. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47099. var _this = this;
  47100. if (this._onCanvasBlurObserver) {
  47101. return;
  47102. }
  47103. this._scene = this.camera.getScene();
  47104. this._engine = this._scene.getEngine();
  47105. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47106. _this._keys = [];
  47107. });
  47108. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47109. var evt = info.event;
  47110. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47111. _this._ctrlPressed = evt.ctrlKey;
  47112. _this._altPressed = evt.altKey;
  47113. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47114. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47115. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47116. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47117. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47118. var index = _this._keys.indexOf(evt.keyCode);
  47119. if (index === -1) {
  47120. _this._keys.push(evt.keyCode);
  47121. }
  47122. if (evt.preventDefault) {
  47123. if (!noPreventDefault) {
  47124. evt.preventDefault();
  47125. }
  47126. }
  47127. }
  47128. }
  47129. else {
  47130. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47131. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47132. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47133. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47134. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47135. var index = _this._keys.indexOf(evt.keyCode);
  47136. if (index >= 0) {
  47137. _this._keys.splice(index, 1);
  47138. }
  47139. if (evt.preventDefault) {
  47140. if (!noPreventDefault) {
  47141. evt.preventDefault();
  47142. }
  47143. }
  47144. }
  47145. }
  47146. });
  47147. };
  47148. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47149. if (this._scene) {
  47150. if (this._onKeyboardObserver) {
  47151. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47152. }
  47153. if (this._onCanvasBlurObserver) {
  47154. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47155. }
  47156. this._onKeyboardObserver = null;
  47157. this._onCanvasBlurObserver = null;
  47158. }
  47159. this._keys = [];
  47160. };
  47161. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47162. if (this._onKeyboardObserver) {
  47163. var camera = this.camera;
  47164. for (var index = 0; index < this._keys.length; index++) {
  47165. var keyCode = this._keys[index];
  47166. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47167. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47168. camera.inertialPanningX -= 1 / this.panningSensibility;
  47169. }
  47170. else {
  47171. camera.inertialAlphaOffset -= 0.01;
  47172. }
  47173. }
  47174. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47175. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47176. camera.inertialPanningY += 1 / this.panningSensibility;
  47177. }
  47178. else if (this._altPressed && this.useAltToZoom) {
  47179. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47180. }
  47181. else {
  47182. camera.inertialBetaOffset -= 0.01;
  47183. }
  47184. }
  47185. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47186. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47187. camera.inertialPanningX += 1 / this.panningSensibility;
  47188. }
  47189. else {
  47190. camera.inertialAlphaOffset += 0.01;
  47191. }
  47192. }
  47193. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47194. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47195. camera.inertialPanningY -= 1 / this.panningSensibility;
  47196. }
  47197. else if (this._altPressed && this.useAltToZoom) {
  47198. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47199. }
  47200. else {
  47201. camera.inertialBetaOffset += 0.01;
  47202. }
  47203. }
  47204. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47205. camera.restoreState();
  47206. }
  47207. }
  47208. }
  47209. };
  47210. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47211. return "ArcRotateCameraKeyboardMoveInput";
  47212. };
  47213. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47214. return "keyboard";
  47215. };
  47216. __decorate([
  47217. BABYLON.serialize()
  47218. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47219. __decorate([
  47220. BABYLON.serialize()
  47221. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47222. __decorate([
  47223. BABYLON.serialize()
  47224. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47225. __decorate([
  47226. BABYLON.serialize()
  47227. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47228. __decorate([
  47229. BABYLON.serialize()
  47230. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47231. __decorate([
  47232. BABYLON.serialize()
  47233. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47234. __decorate([
  47235. BABYLON.serialize()
  47236. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47237. __decorate([
  47238. BABYLON.serialize()
  47239. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47240. return ArcRotateCameraKeyboardMoveInput;
  47241. }());
  47242. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47243. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47244. })(BABYLON || (BABYLON = {}));
  47245. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47246. "use strict";
  47247. var BABYLON;
  47248. (function (BABYLON) {
  47249. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47250. function ArcRotateCameraMouseWheelInput() {
  47251. this.wheelPrecision = 3.0;
  47252. /**
  47253. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47254. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47255. */
  47256. this.wheelDeltaPercentage = 0;
  47257. }
  47258. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47259. var _this = this;
  47260. this._wheel = function (p, s) {
  47261. //sanity check - this should be a PointerWheel event.
  47262. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47263. return;
  47264. var event = p.event;
  47265. var delta = 0;
  47266. if (event.wheelDelta) {
  47267. if (_this.wheelDeltaPercentage) {
  47268. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47269. if (event.wheelDelta > 0) {
  47270. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47271. }
  47272. else {
  47273. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47274. }
  47275. }
  47276. else {
  47277. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47278. }
  47279. }
  47280. else if (event.detail) {
  47281. delta = -event.detail / _this.wheelPrecision;
  47282. }
  47283. if (delta)
  47284. _this.camera.inertialRadiusOffset += delta;
  47285. if (event.preventDefault) {
  47286. if (!noPreventDefault) {
  47287. event.preventDefault();
  47288. }
  47289. }
  47290. };
  47291. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47292. };
  47293. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47294. if (this._observer && element) {
  47295. this.camera.getScene().onPointerObservable.remove(this._observer);
  47296. this._observer = null;
  47297. this._wheel = null;
  47298. }
  47299. };
  47300. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47301. return "ArcRotateCameraMouseWheelInput";
  47302. };
  47303. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47304. return "mousewheel";
  47305. };
  47306. __decorate([
  47307. BABYLON.serialize()
  47308. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47309. __decorate([
  47310. BABYLON.serialize()
  47311. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47312. return ArcRotateCameraMouseWheelInput;
  47313. }());
  47314. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47315. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47316. })(BABYLON || (BABYLON = {}));
  47317. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47318. "use strict";
  47319. var BABYLON;
  47320. (function (BABYLON) {
  47321. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47322. function ArcRotateCameraPointersInput() {
  47323. this.buttons = [0, 1, 2];
  47324. this.angularSensibilityX = 1000.0;
  47325. this.angularSensibilityY = 1000.0;
  47326. this.pinchPrecision = 12.0;
  47327. /**
  47328. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47329. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47330. */
  47331. this.pinchDeltaPercentage = 0;
  47332. this.panningSensibility = 1000.0;
  47333. this.multiTouchPanning = true;
  47334. this.multiTouchPanAndZoom = true;
  47335. this._isPanClick = false;
  47336. this.pinchInwards = true;
  47337. }
  47338. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47339. var _this = this;
  47340. var engine = this.camera.getEngine();
  47341. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47342. var pointA = null;
  47343. var pointB = null;
  47344. var previousPinchSquaredDistance = 0;
  47345. var initialDistance = 0;
  47346. var twoFingerActivityCount = 0;
  47347. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47348. this._pointerInput = function (p, s) {
  47349. var evt = p.event;
  47350. var isTouch = p.event.pointerType === "touch";
  47351. if (engine.isInVRExclusivePointerMode) {
  47352. return;
  47353. }
  47354. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47355. return;
  47356. }
  47357. var srcElement = (evt.srcElement || evt.target);
  47358. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47359. try {
  47360. srcElement.setPointerCapture(evt.pointerId);
  47361. }
  47362. catch (e) {
  47363. //Nothing to do with the error. Execution will continue.
  47364. }
  47365. // Manage panning with pan button click
  47366. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47367. // manage pointers
  47368. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47369. if (pointA === null) {
  47370. pointA = cacheSoloPointer;
  47371. }
  47372. else if (pointB === null) {
  47373. pointB = cacheSoloPointer;
  47374. }
  47375. if (!noPreventDefault) {
  47376. evt.preventDefault();
  47377. element.focus();
  47378. }
  47379. }
  47380. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47381. _this.camera.restoreState();
  47382. }
  47383. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47384. try {
  47385. srcElement.releasePointerCapture(evt.pointerId);
  47386. }
  47387. catch (e) {
  47388. //Nothing to do with the error.
  47389. }
  47390. cacheSoloPointer = null;
  47391. previousPinchSquaredDistance = 0;
  47392. previousMultiTouchPanPosition.isPaning = false;
  47393. previousMultiTouchPanPosition.isPinching = false;
  47394. twoFingerActivityCount = 0;
  47395. initialDistance = 0;
  47396. if (!isTouch) {
  47397. pointB = null; // Mouse and pen are mono pointer
  47398. }
  47399. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47400. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47401. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47402. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47403. if (engine._badOS) {
  47404. pointA = pointB = null;
  47405. }
  47406. else {
  47407. //only remove the impacted pointer in case of multitouch allowing on most
  47408. //platforms switching from rotate to zoom and pan seamlessly.
  47409. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47410. pointA = pointB;
  47411. pointB = null;
  47412. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47413. }
  47414. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47415. pointB = null;
  47416. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47417. }
  47418. else {
  47419. pointA = pointB = null;
  47420. }
  47421. }
  47422. if (!noPreventDefault) {
  47423. evt.preventDefault();
  47424. }
  47425. }
  47426. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47427. if (!noPreventDefault) {
  47428. evt.preventDefault();
  47429. }
  47430. // One button down
  47431. if (pointA && pointB === null && cacheSoloPointer) {
  47432. if (_this.panningSensibility !== 0 &&
  47433. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47434. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47435. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47436. }
  47437. else {
  47438. var offsetX = evt.clientX - cacheSoloPointer.x;
  47439. var offsetY = evt.clientY - cacheSoloPointer.y;
  47440. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47441. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47442. }
  47443. cacheSoloPointer.x = evt.clientX;
  47444. cacheSoloPointer.y = evt.clientY;
  47445. }
  47446. else if (pointA && pointB) {
  47447. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47448. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47449. ed.x = evt.clientX;
  47450. ed.y = evt.clientY;
  47451. var direction = _this.pinchInwards ? 1 : -1;
  47452. var distX = pointA.x - pointB.x;
  47453. var distY = pointA.y - pointB.y;
  47454. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47455. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47456. if (previousPinchSquaredDistance === 0) {
  47457. initialDistance = pinchDistance;
  47458. previousPinchSquaredDistance = pinchSquaredDistance;
  47459. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47460. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47461. return;
  47462. }
  47463. if (_this.multiTouchPanAndZoom) {
  47464. if (_this.pinchDeltaPercentage) {
  47465. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47466. }
  47467. else {
  47468. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47469. (_this.pinchPrecision *
  47470. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47471. direction);
  47472. }
  47473. if (_this.panningSensibility !== 0) {
  47474. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47475. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47476. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47477. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47478. previousMultiTouchPanPosition.x = pointersCenterX;
  47479. previousMultiTouchPanPosition.y = pointersCenterY;
  47480. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47481. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47482. }
  47483. }
  47484. else {
  47485. twoFingerActivityCount++;
  47486. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47487. if (_this.pinchDeltaPercentage) {
  47488. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47489. }
  47490. else {
  47491. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47492. (_this.pinchPrecision *
  47493. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47494. direction);
  47495. }
  47496. previousMultiTouchPanPosition.isPaning = false;
  47497. previousMultiTouchPanPosition.isPinching = true;
  47498. }
  47499. else {
  47500. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47501. if (!previousMultiTouchPanPosition.isPaning) {
  47502. previousMultiTouchPanPosition.isPaning = true;
  47503. previousMultiTouchPanPosition.isPinching = false;
  47504. previousMultiTouchPanPosition.x = ed.x;
  47505. previousMultiTouchPanPosition.y = ed.y;
  47506. return;
  47507. }
  47508. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47509. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47510. }
  47511. }
  47512. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47513. previousMultiTouchPanPosition.x = ed.x;
  47514. previousMultiTouchPanPosition.y = ed.y;
  47515. }
  47516. }
  47517. previousPinchSquaredDistance = pinchSquaredDistance;
  47518. }
  47519. }
  47520. };
  47521. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47522. this._onContextMenu = function (evt) {
  47523. evt.preventDefault();
  47524. };
  47525. if (!this.camera._useCtrlForPanning) {
  47526. element.addEventListener("contextmenu", this._onContextMenu, false);
  47527. }
  47528. this._onLostFocus = function () {
  47529. //this._keys = [];
  47530. pointA = pointB = null;
  47531. previousPinchSquaredDistance = 0;
  47532. previousMultiTouchPanPosition.isPaning = false;
  47533. previousMultiTouchPanPosition.isPinching = false;
  47534. twoFingerActivityCount = 0;
  47535. cacheSoloPointer = null;
  47536. initialDistance = 0;
  47537. };
  47538. this._onMouseMove = function (evt) {
  47539. if (!engine.isPointerLock) {
  47540. return;
  47541. }
  47542. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47543. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47544. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47545. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47546. if (!noPreventDefault) {
  47547. evt.preventDefault();
  47548. }
  47549. };
  47550. this._onGestureStart = function (e) {
  47551. if (window.MSGesture === undefined) {
  47552. return;
  47553. }
  47554. if (!_this._MSGestureHandler) {
  47555. _this._MSGestureHandler = new MSGesture();
  47556. _this._MSGestureHandler.target = element;
  47557. }
  47558. _this._MSGestureHandler.addPointer(e.pointerId);
  47559. };
  47560. this._onGesture = function (e) {
  47561. _this.camera.radius *= e.scale;
  47562. if (e.preventDefault) {
  47563. if (!noPreventDefault) {
  47564. e.stopPropagation();
  47565. e.preventDefault();
  47566. }
  47567. }
  47568. };
  47569. element.addEventListener("mousemove", this._onMouseMove, false);
  47570. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47571. element.addEventListener("MSGestureChange", this._onGesture, false);
  47572. BABYLON.Tools.RegisterTopRootEvents([
  47573. { name: "blur", handler: this._onLostFocus }
  47574. ]);
  47575. };
  47576. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47577. if (this._onLostFocus) {
  47578. BABYLON.Tools.UnregisterTopRootEvents([
  47579. { name: "blur", handler: this._onLostFocus }
  47580. ]);
  47581. }
  47582. if (element && this._observer) {
  47583. this.camera.getScene().onPointerObservable.remove(this._observer);
  47584. this._observer = null;
  47585. if (this._onContextMenu) {
  47586. element.removeEventListener("contextmenu", this._onContextMenu);
  47587. }
  47588. if (this._onMouseMove) {
  47589. element.removeEventListener("mousemove", this._onMouseMove);
  47590. }
  47591. if (this._onGestureStart) {
  47592. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47593. }
  47594. if (this._onGesture) {
  47595. element.removeEventListener("MSGestureChange", this._onGesture);
  47596. }
  47597. this._isPanClick = false;
  47598. this.pinchInwards = true;
  47599. this._onMouseMove = null;
  47600. this._onGestureStart = null;
  47601. this._onGesture = null;
  47602. this._MSGestureHandler = null;
  47603. this._onLostFocus = null;
  47604. this._onContextMenu = null;
  47605. }
  47606. };
  47607. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47608. return "ArcRotateCameraPointersInput";
  47609. };
  47610. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47611. return "pointers";
  47612. };
  47613. __decorate([
  47614. BABYLON.serialize()
  47615. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47616. __decorate([
  47617. BABYLON.serialize()
  47618. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47619. __decorate([
  47620. BABYLON.serialize()
  47621. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47622. __decorate([
  47623. BABYLON.serialize()
  47624. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47625. __decorate([
  47626. BABYLON.serialize()
  47627. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47628. __decorate([
  47629. BABYLON.serialize()
  47630. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47631. __decorate([
  47632. BABYLON.serialize()
  47633. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47634. __decorate([
  47635. BABYLON.serialize()
  47636. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47637. return ArcRotateCameraPointersInput;
  47638. }());
  47639. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47640. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47641. })(BABYLON || (BABYLON = {}));
  47642. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47643. "use strict";
  47644. var BABYLON;
  47645. (function (BABYLON) {
  47646. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47647. __extends(ArcRotateCameraInputsManager, _super);
  47648. function ArcRotateCameraInputsManager(camera) {
  47649. return _super.call(this, camera) || this;
  47650. }
  47651. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47652. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47653. return this;
  47654. };
  47655. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47656. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47657. return this;
  47658. };
  47659. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47660. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47661. return this;
  47662. };
  47663. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47664. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47665. return this;
  47666. };
  47667. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47668. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47669. return this;
  47670. };
  47671. return ArcRotateCameraInputsManager;
  47672. }(BABYLON.CameraInputsManager));
  47673. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47674. })(BABYLON || (BABYLON = {}));
  47675. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47676. "use strict";
  47677. var BABYLON;
  47678. (function (BABYLON) {
  47679. var ArcRotateCamera = /** @class */ (function (_super) {
  47680. __extends(ArcRotateCamera, _super);
  47681. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47682. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47683. _this.inertialAlphaOffset = 0;
  47684. _this.inertialBetaOffset = 0;
  47685. _this.inertialRadiusOffset = 0;
  47686. _this.lowerAlphaLimit = null;
  47687. _this.upperAlphaLimit = null;
  47688. _this.lowerBetaLimit = 0.01;
  47689. _this.upperBetaLimit = Math.PI;
  47690. _this.lowerRadiusLimit = null;
  47691. _this.upperRadiusLimit = null;
  47692. _this.inertialPanningX = 0;
  47693. _this.inertialPanningY = 0;
  47694. _this.pinchToPanMaxDistance = 20;
  47695. _this.panningDistanceLimit = null;
  47696. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47697. _this.panningInertia = 0.9;
  47698. //-- end properties for backward compatibility for inputs
  47699. _this.zoomOnFactor = 1;
  47700. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47701. _this.allowUpsideDown = true;
  47702. _this._viewMatrix = new BABYLON.Matrix();
  47703. // Panning
  47704. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47705. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47706. _this.checkCollisions = false;
  47707. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47708. _this._previousPosition = BABYLON.Vector3.Zero();
  47709. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47710. _this._newPosition = BABYLON.Vector3.Zero();
  47711. _this._computationVector = BABYLON.Vector3.Zero();
  47712. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47713. if (collidedMesh === void 0) { collidedMesh = null; }
  47714. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47715. newPosition.multiplyInPlace(_this._collider._radius);
  47716. }
  47717. if (!collidedMesh) {
  47718. _this._previousPosition.copyFrom(_this.position);
  47719. }
  47720. else {
  47721. _this.setPosition(newPosition);
  47722. if (_this.onCollide) {
  47723. _this.onCollide(collidedMesh);
  47724. }
  47725. }
  47726. // Recompute because of constraints
  47727. var cosa = Math.cos(_this.alpha);
  47728. var sina = Math.sin(_this.alpha);
  47729. var cosb = Math.cos(_this.beta);
  47730. var sinb = Math.sin(_this.beta);
  47731. if (sinb === 0) {
  47732. sinb = 0.0001;
  47733. }
  47734. var target = _this._getTargetPosition();
  47735. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47736. target.addToRef(_this._computationVector, _this._newPosition);
  47737. _this.position.copyFrom(_this._newPosition);
  47738. var up = _this.upVector;
  47739. if (_this.allowUpsideDown && _this.beta < 0) {
  47740. up = up.clone();
  47741. up = up.negate();
  47742. }
  47743. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  47744. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47745. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47746. _this._collisionTriggered = false;
  47747. };
  47748. _this._target = BABYLON.Vector3.Zero();
  47749. if (target) {
  47750. _this.setTarget(target);
  47751. }
  47752. _this.alpha = alpha;
  47753. _this.beta = beta;
  47754. _this.radius = radius;
  47755. _this.getViewMatrix();
  47756. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47757. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47758. return _this;
  47759. }
  47760. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47761. get: function () {
  47762. return this._target;
  47763. },
  47764. set: function (value) {
  47765. this.setTarget(value);
  47766. },
  47767. enumerable: true,
  47768. configurable: true
  47769. });
  47770. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47771. //-- begin properties for backward compatibility for inputs
  47772. get: function () {
  47773. var pointers = this.inputs.attached["pointers"];
  47774. if (pointers)
  47775. return pointers.angularSensibilityX;
  47776. return 0;
  47777. },
  47778. set: function (value) {
  47779. var pointers = this.inputs.attached["pointers"];
  47780. if (pointers) {
  47781. pointers.angularSensibilityX = value;
  47782. }
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47788. get: function () {
  47789. var pointers = this.inputs.attached["pointers"];
  47790. if (pointers)
  47791. return pointers.angularSensibilityY;
  47792. return 0;
  47793. },
  47794. set: function (value) {
  47795. var pointers = this.inputs.attached["pointers"];
  47796. if (pointers) {
  47797. pointers.angularSensibilityY = value;
  47798. }
  47799. },
  47800. enumerable: true,
  47801. configurable: true
  47802. });
  47803. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47804. get: function () {
  47805. var pointers = this.inputs.attached["pointers"];
  47806. if (pointers)
  47807. return pointers.pinchPrecision;
  47808. return 0;
  47809. },
  47810. set: function (value) {
  47811. var pointers = this.inputs.attached["pointers"];
  47812. if (pointers) {
  47813. pointers.pinchPrecision = value;
  47814. }
  47815. },
  47816. enumerable: true,
  47817. configurable: true
  47818. });
  47819. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47820. get: function () {
  47821. var pointers = this.inputs.attached["pointers"];
  47822. if (pointers)
  47823. return pointers.pinchDeltaPercentage;
  47824. return 0;
  47825. },
  47826. set: function (value) {
  47827. var pointers = this.inputs.attached["pointers"];
  47828. if (pointers) {
  47829. pointers.pinchDeltaPercentage = value;
  47830. }
  47831. },
  47832. enumerable: true,
  47833. configurable: true
  47834. });
  47835. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47836. get: function () {
  47837. var pointers = this.inputs.attached["pointers"];
  47838. if (pointers)
  47839. return pointers.panningSensibility;
  47840. return 0;
  47841. },
  47842. set: function (value) {
  47843. var pointers = this.inputs.attached["pointers"];
  47844. if (pointers) {
  47845. pointers.panningSensibility = value;
  47846. }
  47847. },
  47848. enumerable: true,
  47849. configurable: true
  47850. });
  47851. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47852. get: function () {
  47853. var keyboard = this.inputs.attached["keyboard"];
  47854. if (keyboard)
  47855. return keyboard.keysUp;
  47856. return [];
  47857. },
  47858. set: function (value) {
  47859. var keyboard = this.inputs.attached["keyboard"];
  47860. if (keyboard)
  47861. keyboard.keysUp = value;
  47862. },
  47863. enumerable: true,
  47864. configurable: true
  47865. });
  47866. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47867. get: function () {
  47868. var keyboard = this.inputs.attached["keyboard"];
  47869. if (keyboard)
  47870. return keyboard.keysDown;
  47871. return [];
  47872. },
  47873. set: function (value) {
  47874. var keyboard = this.inputs.attached["keyboard"];
  47875. if (keyboard)
  47876. keyboard.keysDown = value;
  47877. },
  47878. enumerable: true,
  47879. configurable: true
  47880. });
  47881. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47882. get: function () {
  47883. var keyboard = this.inputs.attached["keyboard"];
  47884. if (keyboard)
  47885. return keyboard.keysLeft;
  47886. return [];
  47887. },
  47888. set: function (value) {
  47889. var keyboard = this.inputs.attached["keyboard"];
  47890. if (keyboard)
  47891. keyboard.keysLeft = value;
  47892. },
  47893. enumerable: true,
  47894. configurable: true
  47895. });
  47896. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47897. get: function () {
  47898. var keyboard = this.inputs.attached["keyboard"];
  47899. if (keyboard)
  47900. return keyboard.keysRight;
  47901. return [];
  47902. },
  47903. set: function (value) {
  47904. var keyboard = this.inputs.attached["keyboard"];
  47905. if (keyboard)
  47906. keyboard.keysRight = value;
  47907. },
  47908. enumerable: true,
  47909. configurable: true
  47910. });
  47911. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47912. get: function () {
  47913. var mousewheel = this.inputs.attached["mousewheel"];
  47914. if (mousewheel)
  47915. return mousewheel.wheelPrecision;
  47916. return 0;
  47917. },
  47918. set: function (value) {
  47919. var mousewheel = this.inputs.attached["mousewheel"];
  47920. if (mousewheel)
  47921. mousewheel.wheelPrecision = value;
  47922. },
  47923. enumerable: true,
  47924. configurable: true
  47925. });
  47926. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47927. get: function () {
  47928. var mousewheel = this.inputs.attached["mousewheel"];
  47929. if (mousewheel)
  47930. return mousewheel.wheelDeltaPercentage;
  47931. return 0;
  47932. },
  47933. set: function (value) {
  47934. var mousewheel = this.inputs.attached["mousewheel"];
  47935. if (mousewheel)
  47936. mousewheel.wheelDeltaPercentage = value;
  47937. },
  47938. enumerable: true,
  47939. configurable: true
  47940. });
  47941. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47942. get: function () {
  47943. return this._bouncingBehavior;
  47944. },
  47945. enumerable: true,
  47946. configurable: true
  47947. });
  47948. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47949. get: function () {
  47950. return this._bouncingBehavior != null;
  47951. },
  47952. set: function (value) {
  47953. if (value === this.useBouncingBehavior) {
  47954. return;
  47955. }
  47956. if (value) {
  47957. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47958. this.addBehavior(this._bouncingBehavior);
  47959. }
  47960. else if (this._bouncingBehavior) {
  47961. this.removeBehavior(this._bouncingBehavior);
  47962. this._bouncingBehavior = null;
  47963. }
  47964. },
  47965. enumerable: true,
  47966. configurable: true
  47967. });
  47968. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47969. get: function () {
  47970. return this._framingBehavior;
  47971. },
  47972. enumerable: true,
  47973. configurable: true
  47974. });
  47975. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47976. get: function () {
  47977. return this._framingBehavior != null;
  47978. },
  47979. set: function (value) {
  47980. if (value === this.useFramingBehavior) {
  47981. return;
  47982. }
  47983. if (value) {
  47984. this._framingBehavior = new BABYLON.FramingBehavior();
  47985. this.addBehavior(this._framingBehavior);
  47986. }
  47987. else if (this._framingBehavior) {
  47988. this.removeBehavior(this._framingBehavior);
  47989. this._framingBehavior = null;
  47990. }
  47991. },
  47992. enumerable: true,
  47993. configurable: true
  47994. });
  47995. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47996. get: function () {
  47997. return this._autoRotationBehavior;
  47998. },
  47999. enumerable: true,
  48000. configurable: true
  48001. });
  48002. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48003. get: function () {
  48004. return this._autoRotationBehavior != null;
  48005. },
  48006. set: function (value) {
  48007. if (value === this.useAutoRotationBehavior) {
  48008. return;
  48009. }
  48010. if (value) {
  48011. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48012. this.addBehavior(this._autoRotationBehavior);
  48013. }
  48014. else if (this._autoRotationBehavior) {
  48015. this.removeBehavior(this._autoRotationBehavior);
  48016. this._autoRotationBehavior = null;
  48017. }
  48018. },
  48019. enumerable: true,
  48020. configurable: true
  48021. });
  48022. // Cache
  48023. ArcRotateCamera.prototype._initCache = function () {
  48024. _super.prototype._initCache.call(this);
  48025. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48026. this._cache.alpha = undefined;
  48027. this._cache.beta = undefined;
  48028. this._cache.radius = undefined;
  48029. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48030. };
  48031. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48032. if (!ignoreParentClass) {
  48033. _super.prototype._updateCache.call(this);
  48034. }
  48035. this._cache._target.copyFrom(this._getTargetPosition());
  48036. this._cache.alpha = this.alpha;
  48037. this._cache.beta = this.beta;
  48038. this._cache.radius = this.radius;
  48039. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48040. };
  48041. ArcRotateCamera.prototype._getTargetPosition = function () {
  48042. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48043. var pos = this._targetHost.getAbsolutePosition();
  48044. if (this._targetBoundingCenter) {
  48045. pos.addToRef(this._targetBoundingCenter, this._target);
  48046. }
  48047. else {
  48048. this._target.copyFrom(pos);
  48049. }
  48050. }
  48051. var lockedTargetPosition = this._getLockedTargetPosition();
  48052. if (lockedTargetPosition) {
  48053. return lockedTargetPosition;
  48054. }
  48055. return this._target;
  48056. };
  48057. ArcRotateCamera.prototype.storeState = function () {
  48058. this._storedAlpha = this.alpha;
  48059. this._storedBeta = this.beta;
  48060. this._storedRadius = this.radius;
  48061. this._storedTarget = this._getTargetPosition().clone();
  48062. return _super.prototype.storeState.call(this);
  48063. };
  48064. /**
  48065. * Restored camera state. You must call storeState() first
  48066. */
  48067. ArcRotateCamera.prototype._restoreStateValues = function () {
  48068. if (!_super.prototype._restoreStateValues.call(this)) {
  48069. return false;
  48070. }
  48071. this.alpha = this._storedAlpha;
  48072. this.beta = this._storedBeta;
  48073. this.radius = this._storedRadius;
  48074. this.setTarget(this._storedTarget.clone());
  48075. this.inertialAlphaOffset = 0;
  48076. this.inertialBetaOffset = 0;
  48077. this.inertialRadiusOffset = 0;
  48078. this.inertialPanningX = 0;
  48079. this.inertialPanningY = 0;
  48080. return true;
  48081. };
  48082. // Synchronized
  48083. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48084. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48085. return false;
  48086. return this._cache._target.equals(this._getTargetPosition())
  48087. && this._cache.alpha === this.alpha
  48088. && this._cache.beta === this.beta
  48089. && this._cache.radius === this.radius
  48090. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48091. };
  48092. // Methods
  48093. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48094. var _this = this;
  48095. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48096. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48097. this._useCtrlForPanning = useCtrlForPanning;
  48098. this._panningMouseButton = panningMouseButton;
  48099. this.inputs.attachElement(element, noPreventDefault);
  48100. this._reset = function () {
  48101. _this.inertialAlphaOffset = 0;
  48102. _this.inertialBetaOffset = 0;
  48103. _this.inertialRadiusOffset = 0;
  48104. _this.inertialPanningX = 0;
  48105. _this.inertialPanningY = 0;
  48106. };
  48107. };
  48108. ArcRotateCamera.prototype.detachControl = function (element) {
  48109. this.inputs.detachElement(element);
  48110. if (this._reset) {
  48111. this._reset();
  48112. }
  48113. };
  48114. ArcRotateCamera.prototype._checkInputs = function () {
  48115. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48116. if (this._collisionTriggered) {
  48117. return;
  48118. }
  48119. this.inputs.checkInputs();
  48120. // Inertia
  48121. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48122. if (this.getScene().useRightHandedSystem) {
  48123. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48124. }
  48125. else {
  48126. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48127. }
  48128. this.beta += this.inertialBetaOffset;
  48129. this.radius -= this.inertialRadiusOffset;
  48130. this.inertialAlphaOffset *= this.inertia;
  48131. this.inertialBetaOffset *= this.inertia;
  48132. this.inertialRadiusOffset *= this.inertia;
  48133. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48134. this.inertialAlphaOffset = 0;
  48135. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48136. this.inertialBetaOffset = 0;
  48137. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48138. this.inertialRadiusOffset = 0;
  48139. }
  48140. // Panning inertia
  48141. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48142. if (!this._localDirection) {
  48143. this._localDirection = BABYLON.Vector3.Zero();
  48144. this._transformedDirection = BABYLON.Vector3.Zero();
  48145. }
  48146. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48147. this._localDirection.multiplyInPlace(this.panningAxis);
  48148. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48149. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48150. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48151. if (!this.panningAxis.y) {
  48152. this._transformedDirection.y = 0;
  48153. }
  48154. if (!this._targetHost) {
  48155. if (this.panningDistanceLimit) {
  48156. this._transformedDirection.addInPlace(this._target);
  48157. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48158. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48159. this._target.copyFrom(this._transformedDirection);
  48160. }
  48161. }
  48162. else {
  48163. this._target.addInPlace(this._transformedDirection);
  48164. }
  48165. }
  48166. this.inertialPanningX *= this.panningInertia;
  48167. this.inertialPanningY *= this.panningInertia;
  48168. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48169. this.inertialPanningX = 0;
  48170. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48171. this.inertialPanningY = 0;
  48172. }
  48173. // Limits
  48174. this._checkLimits();
  48175. _super.prototype._checkInputs.call(this);
  48176. };
  48177. ArcRotateCamera.prototype._checkLimits = function () {
  48178. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48179. if (this.allowUpsideDown && this.beta > Math.PI) {
  48180. this.beta = this.beta - (2 * Math.PI);
  48181. }
  48182. }
  48183. else {
  48184. if (this.beta < this.lowerBetaLimit) {
  48185. this.beta = this.lowerBetaLimit;
  48186. }
  48187. }
  48188. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48189. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48190. this.beta = this.beta + (2 * Math.PI);
  48191. }
  48192. }
  48193. else {
  48194. if (this.beta > this.upperBetaLimit) {
  48195. this.beta = this.upperBetaLimit;
  48196. }
  48197. }
  48198. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48199. this.alpha = this.lowerAlphaLimit;
  48200. }
  48201. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48202. this.alpha = this.upperAlphaLimit;
  48203. }
  48204. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48205. this.radius = this.lowerRadiusLimit;
  48206. }
  48207. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48208. this.radius = this.upperRadiusLimit;
  48209. }
  48210. };
  48211. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48212. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48213. this.radius = this._computationVector.length();
  48214. if (this.radius === 0) {
  48215. this.radius = 0.0001; // Just to avoid division by zero
  48216. }
  48217. // Alpha
  48218. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48219. if (this._computationVector.z < 0) {
  48220. this.alpha = 2 * Math.PI - this.alpha;
  48221. }
  48222. // Beta
  48223. this.beta = Math.acos(this._computationVector.y / this.radius);
  48224. this._checkLimits();
  48225. };
  48226. ArcRotateCamera.prototype.setPosition = function (position) {
  48227. if (this.position.equals(position)) {
  48228. return;
  48229. }
  48230. this.position.copyFrom(position);
  48231. this.rebuildAnglesAndRadius();
  48232. };
  48233. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48234. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48235. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48236. if (target.getBoundingInfo) {
  48237. if (toBoundingCenter) {
  48238. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48239. }
  48240. else {
  48241. this._targetBoundingCenter = null;
  48242. }
  48243. this._targetHost = target;
  48244. this._target = this._getTargetPosition();
  48245. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48246. }
  48247. else {
  48248. var newTarget = target;
  48249. var currentTarget = this._getTargetPosition();
  48250. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48251. return;
  48252. }
  48253. this._targetHost = null;
  48254. this._target = newTarget;
  48255. this._targetBoundingCenter = null;
  48256. this.onMeshTargetChangedObservable.notifyObservers(null);
  48257. }
  48258. this.rebuildAnglesAndRadius();
  48259. };
  48260. ArcRotateCamera.prototype._getViewMatrix = function () {
  48261. // Compute
  48262. var cosa = Math.cos(this.alpha);
  48263. var sina = Math.sin(this.alpha);
  48264. var cosb = Math.cos(this.beta);
  48265. var sinb = Math.sin(this.beta);
  48266. if (sinb === 0) {
  48267. sinb = 0.0001;
  48268. }
  48269. var target = this._getTargetPosition();
  48270. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48271. target.addToRef(this._computationVector, this._newPosition);
  48272. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48273. if (!this._collider) {
  48274. this._collider = new BABYLON.Collider();
  48275. }
  48276. this._collider._radius = this.collisionRadius;
  48277. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48278. this._collisionTriggered = true;
  48279. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48280. }
  48281. else {
  48282. this.position.copyFrom(this._newPosition);
  48283. var up = this.upVector;
  48284. if (this.allowUpsideDown && sinb < 0) {
  48285. up = up.clone();
  48286. up = up.negate();
  48287. }
  48288. if (this.getScene().useRightHandedSystem) {
  48289. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48290. }
  48291. else {
  48292. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48293. }
  48294. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48295. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48296. }
  48297. this._currentTarget = target;
  48298. return this._viewMatrix;
  48299. };
  48300. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48301. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48302. meshes = meshes || this.getScene().meshes;
  48303. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48304. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48305. this.radius = distance * this.zoomOnFactor;
  48306. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48307. };
  48308. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48309. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48310. var meshesOrMinMaxVector;
  48311. var distance;
  48312. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  48313. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48314. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48315. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48316. }
  48317. else {
  48318. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48319. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48320. distance = minMaxVectorAndDistance.distance;
  48321. }
  48322. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48323. if (!doNotUpdateMaxZ) {
  48324. this.maxZ = distance * 2;
  48325. }
  48326. };
  48327. /**
  48328. * @override
  48329. * Override Camera.createRigCamera
  48330. */
  48331. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48332. var alphaShift = 0;
  48333. switch (this.cameraRigMode) {
  48334. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48335. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48336. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48337. case BABYLON.Camera.RIG_MODE_VR:
  48338. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48339. break;
  48340. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48341. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48342. break;
  48343. }
  48344. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48345. rigCam._cameraRigParams = {};
  48346. return rigCam;
  48347. };
  48348. /**
  48349. * @override
  48350. * Override Camera._updateRigCameras
  48351. */
  48352. ArcRotateCamera.prototype._updateRigCameras = function () {
  48353. var camLeft = this._rigCameras[0];
  48354. var camRight = this._rigCameras[1];
  48355. camLeft.beta = camRight.beta = this.beta;
  48356. camLeft.radius = camRight.radius = this.radius;
  48357. switch (this.cameraRigMode) {
  48358. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48359. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48360. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48361. case BABYLON.Camera.RIG_MODE_VR:
  48362. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48363. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48364. break;
  48365. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48366. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48367. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48368. break;
  48369. }
  48370. _super.prototype._updateRigCameras.call(this);
  48371. };
  48372. ArcRotateCamera.prototype.dispose = function () {
  48373. this.inputs.clear();
  48374. _super.prototype.dispose.call(this);
  48375. };
  48376. ArcRotateCamera.prototype.getClassName = function () {
  48377. return "ArcRotateCamera";
  48378. };
  48379. __decorate([
  48380. BABYLON.serialize()
  48381. ], ArcRotateCamera.prototype, "alpha", void 0);
  48382. __decorate([
  48383. BABYLON.serialize()
  48384. ], ArcRotateCamera.prototype, "beta", void 0);
  48385. __decorate([
  48386. BABYLON.serialize()
  48387. ], ArcRotateCamera.prototype, "radius", void 0);
  48388. __decorate([
  48389. BABYLON.serializeAsVector3("target")
  48390. ], ArcRotateCamera.prototype, "_target", void 0);
  48391. __decorate([
  48392. BABYLON.serialize()
  48393. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48394. __decorate([
  48395. BABYLON.serialize()
  48396. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48397. __decorate([
  48398. BABYLON.serialize()
  48399. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48400. __decorate([
  48401. BABYLON.serialize()
  48402. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48403. __decorate([
  48404. BABYLON.serialize()
  48405. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48406. __decorate([
  48407. BABYLON.serialize()
  48408. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48409. __decorate([
  48410. BABYLON.serialize()
  48411. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48412. __decorate([
  48413. BABYLON.serialize()
  48414. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48415. __decorate([
  48416. BABYLON.serialize()
  48417. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48418. __decorate([
  48419. BABYLON.serialize()
  48420. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48421. __decorate([
  48422. BABYLON.serialize()
  48423. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48424. __decorate([
  48425. BABYLON.serialize()
  48426. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48427. __decorate([
  48428. BABYLON.serialize()
  48429. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48430. __decorate([
  48431. BABYLON.serializeAsVector3()
  48432. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48433. __decorate([
  48434. BABYLON.serialize()
  48435. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48436. __decorate([
  48437. BABYLON.serialize()
  48438. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48439. __decorate([
  48440. BABYLON.serialize()
  48441. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48442. return ArcRotateCamera;
  48443. }(BABYLON.TargetCamera));
  48444. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48445. })(BABYLON || (BABYLON = {}));
  48446. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48447. "use strict";
  48448. var BABYLON;
  48449. (function (BABYLON) {
  48450. /**
  48451. * The HemisphericLight simulates the ambient environment light,
  48452. * so the passed direction is the light reflection direction, not the incoming direction.
  48453. */
  48454. var HemisphericLight = /** @class */ (function (_super) {
  48455. __extends(HemisphericLight, _super);
  48456. /**
  48457. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48458. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48459. * The HemisphericLight can't cast shadows.
  48460. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48461. * @param name The friendly name of the light
  48462. * @param direction The direction of the light reflection
  48463. * @param scene The scene the light belongs to
  48464. */
  48465. function HemisphericLight(name, direction, scene) {
  48466. var _this = _super.call(this, name, scene) || this;
  48467. /**
  48468. * The groundColor is the light in the opposite direction to the one specified during creation.
  48469. * 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.
  48470. */
  48471. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48472. _this.direction = direction || BABYLON.Vector3.Up();
  48473. return _this;
  48474. }
  48475. HemisphericLight.prototype._buildUniformLayout = function () {
  48476. this._uniformBuffer.addUniform("vLightData", 4);
  48477. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48478. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48479. this._uniformBuffer.addUniform("vLightGround", 3);
  48480. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48481. this._uniformBuffer.addUniform("depthValues", 2);
  48482. this._uniformBuffer.create();
  48483. };
  48484. /**
  48485. * Returns the string "HemisphericLight".
  48486. * @return The class name
  48487. */
  48488. HemisphericLight.prototype.getClassName = function () {
  48489. return "HemisphericLight";
  48490. };
  48491. /**
  48492. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48493. * Returns the updated direction.
  48494. * @param target The target the direction should point to
  48495. * @return The computed direction
  48496. */
  48497. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48498. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48499. return this.direction;
  48500. };
  48501. /**
  48502. * Returns the shadow generator associated to the light.
  48503. * @returns Always null for hemispheric lights because it does not support shadows.
  48504. */
  48505. HemisphericLight.prototype.getShadowGenerator = function () {
  48506. return null;
  48507. };
  48508. /**
  48509. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48510. * @param effect The effect to update
  48511. * @param lightIndex The index of the light in the effect to update
  48512. * @returns The hemispheric light
  48513. */
  48514. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48515. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48516. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48517. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48518. return this;
  48519. };
  48520. /**
  48521. * @ignore internal use only.
  48522. */
  48523. HemisphericLight.prototype._getWorldMatrix = function () {
  48524. if (!this._worldMatrix) {
  48525. this._worldMatrix = BABYLON.Matrix.Identity();
  48526. }
  48527. return this._worldMatrix;
  48528. };
  48529. /**
  48530. * Returns the integer 3.
  48531. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48532. */
  48533. HemisphericLight.prototype.getTypeID = function () {
  48534. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48535. };
  48536. __decorate([
  48537. BABYLON.serializeAsColor3()
  48538. ], HemisphericLight.prototype, "groundColor", void 0);
  48539. __decorate([
  48540. BABYLON.serializeAsVector3()
  48541. ], HemisphericLight.prototype, "direction", void 0);
  48542. return HemisphericLight;
  48543. }(BABYLON.Light));
  48544. BABYLON.HemisphericLight = HemisphericLight;
  48545. })(BABYLON || (BABYLON = {}));
  48546. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48547. "use strict";
  48548. var BABYLON;
  48549. (function (BABYLON) {
  48550. /**
  48551. * Base implementation IShadowLight
  48552. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48553. */
  48554. var ShadowLight = /** @class */ (function (_super) {
  48555. __extends(ShadowLight, _super);
  48556. function ShadowLight() {
  48557. var _this = _super !== null && _super.apply(this, arguments) || this;
  48558. _this._needProjectionMatrixCompute = true;
  48559. return _this;
  48560. }
  48561. ShadowLight.prototype._setPosition = function (value) {
  48562. this._position = value;
  48563. };
  48564. Object.defineProperty(ShadowLight.prototype, "position", {
  48565. /**
  48566. * Sets the position the shadow will be casted from. Also use as the light position for both
  48567. * point and spot lights.
  48568. */
  48569. get: function () {
  48570. return this._position;
  48571. },
  48572. /**
  48573. * Sets the position the shadow will be casted from. Also use as the light position for both
  48574. * point and spot lights.
  48575. */
  48576. set: function (value) {
  48577. this._setPosition(value);
  48578. },
  48579. enumerable: true,
  48580. configurable: true
  48581. });
  48582. ShadowLight.prototype._setDirection = function (value) {
  48583. this._direction = value;
  48584. };
  48585. Object.defineProperty(ShadowLight.prototype, "direction", {
  48586. /**
  48587. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48588. * Also use as the light direction on spot and directional lights.
  48589. */
  48590. get: function () {
  48591. return this._direction;
  48592. },
  48593. /**
  48594. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48595. * Also use as the light direction on spot and directional lights.
  48596. */
  48597. set: function (value) {
  48598. this._setDirection(value);
  48599. },
  48600. enumerable: true,
  48601. configurable: true
  48602. });
  48603. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48604. /**
  48605. * Gets the shadow projection clipping minimum z value.
  48606. */
  48607. get: function () {
  48608. return this._shadowMinZ;
  48609. },
  48610. /**
  48611. * Sets the shadow projection clipping minimum z value.
  48612. */
  48613. set: function (value) {
  48614. this._shadowMinZ = value;
  48615. this.forceProjectionMatrixCompute();
  48616. },
  48617. enumerable: true,
  48618. configurable: true
  48619. });
  48620. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48621. /**
  48622. * Sets the shadow projection clipping maximum z value.
  48623. */
  48624. get: function () {
  48625. return this._shadowMaxZ;
  48626. },
  48627. /**
  48628. * Gets the shadow projection clipping maximum z value.
  48629. */
  48630. set: function (value) {
  48631. this._shadowMaxZ = value;
  48632. this.forceProjectionMatrixCompute();
  48633. },
  48634. enumerable: true,
  48635. configurable: true
  48636. });
  48637. /**
  48638. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48639. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48640. */
  48641. ShadowLight.prototype.computeTransformedInformation = function () {
  48642. if (this.parent && this.parent.getWorldMatrix) {
  48643. if (!this.transformedPosition) {
  48644. this.transformedPosition = BABYLON.Vector3.Zero();
  48645. }
  48646. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48647. // In case the direction is present.
  48648. if (this.direction) {
  48649. if (!this.transformedDirection) {
  48650. this.transformedDirection = BABYLON.Vector3.Zero();
  48651. }
  48652. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48653. }
  48654. return true;
  48655. }
  48656. return false;
  48657. };
  48658. /**
  48659. * Return the depth scale used for the shadow map.
  48660. * @returns the depth scale.
  48661. */
  48662. ShadowLight.prototype.getDepthScale = function () {
  48663. return 50.0;
  48664. };
  48665. /**
  48666. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48667. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48668. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48669. */
  48670. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48671. return this.transformedDirection ? this.transformedDirection : this.direction;
  48672. };
  48673. /**
  48674. * Returns the ShadowLight absolute position in the World.
  48675. * @returns the position vector in world space
  48676. */
  48677. ShadowLight.prototype.getAbsolutePosition = function () {
  48678. return this.transformedPosition ? this.transformedPosition : this.position;
  48679. };
  48680. /**
  48681. * Sets the ShadowLight direction toward the passed target.
  48682. * @param target The point tot target in local space
  48683. * @returns the updated ShadowLight direction
  48684. */
  48685. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48686. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48687. return this.direction;
  48688. };
  48689. /**
  48690. * Returns the light rotation in euler definition.
  48691. * @returns the x y z rotation in local space.
  48692. */
  48693. ShadowLight.prototype.getRotation = function () {
  48694. this.direction.normalize();
  48695. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48696. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48697. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48698. };
  48699. /**
  48700. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48701. * @returns true if a cube texture needs to be use
  48702. */
  48703. ShadowLight.prototype.needCube = function () {
  48704. return false;
  48705. };
  48706. /**
  48707. * Detects if the projection matrix requires to be recomputed this frame.
  48708. * @returns true if it requires to be recomputed otherwise, false.
  48709. */
  48710. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48711. return this._needProjectionMatrixCompute;
  48712. };
  48713. /**
  48714. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48715. */
  48716. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48717. this._needProjectionMatrixCompute = true;
  48718. };
  48719. /**
  48720. * Get the world matrix of the sahdow lights.
  48721. * @ignore Internal Use Only
  48722. */
  48723. ShadowLight.prototype._getWorldMatrix = function () {
  48724. if (!this._worldMatrix) {
  48725. this._worldMatrix = BABYLON.Matrix.Identity();
  48726. }
  48727. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48728. return this._worldMatrix;
  48729. };
  48730. /**
  48731. * Gets the minZ used for shadow according to both the scene and the light.
  48732. * @param activeCamera The camera we are returning the min for
  48733. * @returns the depth min z
  48734. */
  48735. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48736. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48737. };
  48738. /**
  48739. * Gets the maxZ used for shadow according to both the scene and the light.
  48740. * @param activeCamera The camera we are returning the max for
  48741. * @returns the depth max z
  48742. */
  48743. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48744. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48745. };
  48746. /**
  48747. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48748. * @param matrix The materix to updated with the projection information
  48749. * @param viewMatrix The transform matrix of the light
  48750. * @param renderList The list of mesh to render in the map
  48751. * @returns The current light
  48752. */
  48753. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48754. if (this.customProjectionMatrixBuilder) {
  48755. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48756. }
  48757. else {
  48758. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48759. }
  48760. return this;
  48761. };
  48762. __decorate([
  48763. BABYLON.serializeAsVector3()
  48764. ], ShadowLight.prototype, "position", null);
  48765. __decorate([
  48766. BABYLON.serializeAsVector3()
  48767. ], ShadowLight.prototype, "direction", null);
  48768. __decorate([
  48769. BABYLON.serialize()
  48770. ], ShadowLight.prototype, "shadowMinZ", null);
  48771. __decorate([
  48772. BABYLON.serialize()
  48773. ], ShadowLight.prototype, "shadowMaxZ", null);
  48774. return ShadowLight;
  48775. }(BABYLON.Light));
  48776. BABYLON.ShadowLight = ShadowLight;
  48777. })(BABYLON || (BABYLON = {}));
  48778. //# sourceMappingURL=babylon.shadowLight.js.map
  48779. "use strict";
  48780. var BABYLON;
  48781. (function (BABYLON) {
  48782. /**
  48783. * A point light is a light defined by an unique point in world space.
  48784. * The light is emitted in every direction from this point.
  48785. * A good example of a point light is a standard light bulb.
  48786. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48787. */
  48788. var PointLight = /** @class */ (function (_super) {
  48789. __extends(PointLight, _super);
  48790. /**
  48791. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48792. * A PointLight emits the light in every direction.
  48793. * It can cast shadows.
  48794. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48795. * ```javascript
  48796. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48797. * ```
  48798. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48799. * @param name The light friendly name
  48800. * @param position The position of the point light in the scene
  48801. * @param scene The scene the lights belongs to
  48802. */
  48803. function PointLight(name, position, scene) {
  48804. var _this = _super.call(this, name, scene) || this;
  48805. _this._shadowAngle = Math.PI / 2;
  48806. _this.position = position;
  48807. return _this;
  48808. }
  48809. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48810. /**
  48811. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48812. * This specifies what angle the shadow will use to be created.
  48813. *
  48814. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48815. */
  48816. get: function () {
  48817. return this._shadowAngle;
  48818. },
  48819. /**
  48820. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48821. * This specifies what angle the shadow will use to be created.
  48822. *
  48823. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48824. */
  48825. set: function (value) {
  48826. this._shadowAngle = value;
  48827. this.forceProjectionMatrixCompute();
  48828. },
  48829. enumerable: true,
  48830. configurable: true
  48831. });
  48832. Object.defineProperty(PointLight.prototype, "direction", {
  48833. /**
  48834. * Gets the direction if it has been set.
  48835. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48836. */
  48837. get: function () {
  48838. return this._direction;
  48839. },
  48840. /**
  48841. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48842. */
  48843. set: function (value) {
  48844. var previousNeedCube = this.needCube();
  48845. this._direction = value;
  48846. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48847. this._shadowGenerator.recreateShadowMap();
  48848. }
  48849. },
  48850. enumerable: true,
  48851. configurable: true
  48852. });
  48853. /**
  48854. * Returns the string "PointLight"
  48855. * @returns the class name
  48856. */
  48857. PointLight.prototype.getClassName = function () {
  48858. return "PointLight";
  48859. };
  48860. /**
  48861. * Returns the integer 0.
  48862. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48863. */
  48864. PointLight.prototype.getTypeID = function () {
  48865. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48866. };
  48867. /**
  48868. * Specifies wether or not the shadowmap should be a cube texture.
  48869. * @returns true if the shadowmap needs to be a cube texture.
  48870. */
  48871. PointLight.prototype.needCube = function () {
  48872. return !this.direction;
  48873. };
  48874. /**
  48875. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48876. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48877. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48878. */
  48879. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48880. if (this.direction) {
  48881. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48882. }
  48883. else {
  48884. switch (faceIndex) {
  48885. case 0:
  48886. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48887. case 1:
  48888. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48889. case 2:
  48890. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48891. case 3:
  48892. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48893. case 4:
  48894. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48895. case 5:
  48896. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48897. }
  48898. }
  48899. return BABYLON.Vector3.Zero();
  48900. };
  48901. /**
  48902. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48903. * - fov = PI / 2
  48904. * - aspect ratio : 1.0
  48905. * - z-near and far equal to the active camera minZ and maxZ.
  48906. * Returns the PointLight.
  48907. */
  48908. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48909. var activeCamera = this.getScene().activeCamera;
  48910. if (!activeCamera) {
  48911. return;
  48912. }
  48913. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48914. };
  48915. PointLight.prototype._buildUniformLayout = function () {
  48916. this._uniformBuffer.addUniform("vLightData", 4);
  48917. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48918. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48919. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48920. this._uniformBuffer.addUniform("depthValues", 2);
  48921. this._uniformBuffer.create();
  48922. };
  48923. /**
  48924. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48925. * @param effect The effect to update
  48926. * @param lightIndex The index of the light in the effect to update
  48927. * @returns The point light
  48928. */
  48929. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48930. if (this.computeTransformedInformation()) {
  48931. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48932. return this;
  48933. }
  48934. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48935. return this;
  48936. };
  48937. __decorate([
  48938. BABYLON.serialize()
  48939. ], PointLight.prototype, "shadowAngle", null);
  48940. return PointLight;
  48941. }(BABYLON.ShadowLight));
  48942. BABYLON.PointLight = PointLight;
  48943. })(BABYLON || (BABYLON = {}));
  48944. //# sourceMappingURL=babylon.pointLight.js.map
  48945. "use strict";
  48946. var BABYLON;
  48947. (function (BABYLON) {
  48948. /**
  48949. * A directional light is defined by a direction (what a surprise!).
  48950. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48951. * 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.
  48952. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48953. */
  48954. var DirectionalLight = /** @class */ (function (_super) {
  48955. __extends(DirectionalLight, _super);
  48956. /**
  48957. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48958. * The directional light is emitted from everywhere in the given direction.
  48959. * It can cast shawdows.
  48960. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48961. * @param name The friendly name of the light
  48962. * @param direction The direction of the light
  48963. * @param scene The scene the light belongs to
  48964. */
  48965. function DirectionalLight(name, direction, scene) {
  48966. var _this = _super.call(this, name, scene) || this;
  48967. _this._shadowFrustumSize = 0;
  48968. _this._shadowOrthoScale = 0.1;
  48969. /**
  48970. * Automatically compute the projection matrix to best fit (including all the casters)
  48971. * on each frame.
  48972. */
  48973. _this.autoUpdateExtends = true;
  48974. // Cache
  48975. _this._orthoLeft = Number.MAX_VALUE;
  48976. _this._orthoRight = Number.MIN_VALUE;
  48977. _this._orthoTop = Number.MIN_VALUE;
  48978. _this._orthoBottom = Number.MAX_VALUE;
  48979. _this.position = direction.scale(-1.0);
  48980. _this.direction = direction;
  48981. return _this;
  48982. }
  48983. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48984. /**
  48985. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48986. */
  48987. get: function () {
  48988. return this._shadowFrustumSize;
  48989. },
  48990. /**
  48991. * Specifies a fix frustum size for the shadow generation.
  48992. */
  48993. set: function (value) {
  48994. this._shadowFrustumSize = value;
  48995. this.forceProjectionMatrixCompute();
  48996. },
  48997. enumerable: true,
  48998. configurable: true
  48999. });
  49000. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49001. /**
  49002. * Gets the shadow projection scale against the optimal computed one.
  49003. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49004. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49005. */
  49006. get: function () {
  49007. return this._shadowOrthoScale;
  49008. },
  49009. /**
  49010. * Sets the shadow projection scale against the optimal computed one.
  49011. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49012. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49013. */
  49014. set: function (value) {
  49015. this._shadowOrthoScale = value;
  49016. this.forceProjectionMatrixCompute();
  49017. },
  49018. enumerable: true,
  49019. configurable: true
  49020. });
  49021. /**
  49022. * Returns the string "DirectionalLight".
  49023. * @return The class name
  49024. */
  49025. DirectionalLight.prototype.getClassName = function () {
  49026. return "DirectionalLight";
  49027. };
  49028. /**
  49029. * Returns the integer 1.
  49030. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49031. */
  49032. DirectionalLight.prototype.getTypeID = function () {
  49033. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49034. };
  49035. /**
  49036. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49037. * Returns the DirectionalLight Shadow projection matrix.
  49038. */
  49039. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49040. if (this.shadowFrustumSize > 0) {
  49041. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49042. }
  49043. else {
  49044. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49045. }
  49046. };
  49047. /**
  49048. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49049. * Returns the DirectionalLight Shadow projection matrix.
  49050. */
  49051. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49052. var activeCamera = this.getScene().activeCamera;
  49053. if (!activeCamera) {
  49054. return;
  49055. }
  49056. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49057. };
  49058. /**
  49059. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49060. * Returns the DirectionalLight Shadow projection matrix.
  49061. */
  49062. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49063. var activeCamera = this.getScene().activeCamera;
  49064. if (!activeCamera) {
  49065. return;
  49066. }
  49067. // Check extends
  49068. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49069. var tempVector3 = BABYLON.Vector3.Zero();
  49070. this._orthoLeft = Number.MAX_VALUE;
  49071. this._orthoRight = Number.MIN_VALUE;
  49072. this._orthoTop = Number.MIN_VALUE;
  49073. this._orthoBottom = Number.MAX_VALUE;
  49074. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49075. var mesh = renderList[meshIndex];
  49076. if (!mesh) {
  49077. continue;
  49078. }
  49079. var boundingInfo = mesh.getBoundingInfo();
  49080. var boundingBox = boundingInfo.boundingBox;
  49081. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49082. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49083. if (tempVector3.x < this._orthoLeft)
  49084. this._orthoLeft = tempVector3.x;
  49085. if (tempVector3.y < this._orthoBottom)
  49086. this._orthoBottom = tempVector3.y;
  49087. if (tempVector3.x > this._orthoRight)
  49088. this._orthoRight = tempVector3.x;
  49089. if (tempVector3.y > this._orthoTop)
  49090. this._orthoTop = tempVector3.y;
  49091. }
  49092. }
  49093. }
  49094. var xOffset = this._orthoRight - this._orthoLeft;
  49095. var yOffset = this._orthoTop - this._orthoBottom;
  49096. 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);
  49097. };
  49098. DirectionalLight.prototype._buildUniformLayout = function () {
  49099. this._uniformBuffer.addUniform("vLightData", 4);
  49100. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49101. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49102. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49103. this._uniformBuffer.addUniform("depthValues", 2);
  49104. this._uniformBuffer.create();
  49105. };
  49106. /**
  49107. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49108. * @param effect The effect to update
  49109. * @param lightIndex The index of the light in the effect to update
  49110. * @returns The directional light
  49111. */
  49112. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49113. if (this.computeTransformedInformation()) {
  49114. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49115. return this;
  49116. }
  49117. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49118. return this;
  49119. };
  49120. /**
  49121. * Gets the minZ used for shadow according to both the scene and the light.
  49122. *
  49123. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49124. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49125. * @param activeCamera The camera we are returning the min for
  49126. * @returns the depth min z
  49127. */
  49128. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49129. return 1;
  49130. };
  49131. /**
  49132. * Gets the maxZ used for shadow according to both the scene and the light.
  49133. *
  49134. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49135. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49136. * @param activeCamera The camera we are returning the max for
  49137. * @returns the depth max z
  49138. */
  49139. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49140. return 1;
  49141. };
  49142. __decorate([
  49143. BABYLON.serialize()
  49144. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49145. __decorate([
  49146. BABYLON.serialize()
  49147. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49148. __decorate([
  49149. BABYLON.serialize()
  49150. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49151. return DirectionalLight;
  49152. }(BABYLON.ShadowLight));
  49153. BABYLON.DirectionalLight = DirectionalLight;
  49154. })(BABYLON || (BABYLON = {}));
  49155. //# sourceMappingURL=babylon.directionalLight.js.map
  49156. "use strict";
  49157. var BABYLON;
  49158. (function (BABYLON) {
  49159. /**
  49160. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49161. * These values define a cone of light starting from the position, emitting toward the direction.
  49162. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49163. * and the exponent defines the speed of the decay of the light with distance (reach).
  49164. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49165. */
  49166. var SpotLight = /** @class */ (function (_super) {
  49167. __extends(SpotLight, _super);
  49168. /**
  49169. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49170. * It can cast shadows.
  49171. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49172. * @param name The light friendly name
  49173. * @param position The position of the spot light in the scene
  49174. * @param direction The direction of the light in the scene
  49175. * @param angle The cone angle of the light in Radians
  49176. * @param exponent The light decay speed with the distance from the emission spot
  49177. * @param scene The scene the lights belongs to
  49178. */
  49179. function SpotLight(name, position, direction, angle, exponent, scene) {
  49180. var _this = _super.call(this, name, scene) || this;
  49181. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49182. _this._projectionTextureLightNear = 1e-6;
  49183. _this._projectionTextureLightFar = 1000.0;
  49184. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49185. _this._projectionTextureViewLightDirty = true;
  49186. _this._projectionTextureProjectionLightDirty = true;
  49187. _this._projectionTextureDirty = true;
  49188. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49189. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49190. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49191. _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);
  49192. _this.position = position;
  49193. _this.direction = direction;
  49194. _this.angle = angle;
  49195. _this.exponent = exponent;
  49196. return _this;
  49197. }
  49198. Object.defineProperty(SpotLight.prototype, "angle", {
  49199. /**
  49200. * Gets the cone angle of the spot light in Radians.
  49201. */
  49202. get: function () {
  49203. return this._angle;
  49204. },
  49205. /**
  49206. * Sets the cone angle of the spot light in Radians.
  49207. */
  49208. set: function (value) {
  49209. this._angle = value;
  49210. this._projectionTextureProjectionLightDirty = true;
  49211. this.forceProjectionMatrixCompute();
  49212. },
  49213. enumerable: true,
  49214. configurable: true
  49215. });
  49216. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49217. /**
  49218. * Allows scaling the angle of the light for shadow generation only.
  49219. */
  49220. get: function () {
  49221. return this._shadowAngleScale;
  49222. },
  49223. /**
  49224. * Allows scaling the angle of the light for shadow generation only.
  49225. */
  49226. set: function (value) {
  49227. this._shadowAngleScale = value;
  49228. this.forceProjectionMatrixCompute();
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49234. /**
  49235. * Allows reading the projecton texture
  49236. */
  49237. get: function () {
  49238. return this._projectionTextureMatrix;
  49239. },
  49240. enumerable: true,
  49241. configurable: true
  49242. });
  49243. ;
  49244. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49245. /**
  49246. * Gets the near clip of the Spotlight for texture projection.
  49247. */
  49248. get: function () {
  49249. return this._projectionTextureLightNear;
  49250. },
  49251. /**
  49252. * Sets the near clip of the Spotlight for texture projection.
  49253. */
  49254. set: function (value) {
  49255. this._projectionTextureLightNear = value;
  49256. this._projectionTextureProjectionLightDirty = true;
  49257. },
  49258. enumerable: true,
  49259. configurable: true
  49260. });
  49261. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49262. /**
  49263. * Gets the far clip of the Spotlight for texture projection.
  49264. */
  49265. get: function () {
  49266. return this._projectionTextureLightFar;
  49267. },
  49268. /**
  49269. * Sets the far clip of the Spotlight for texture projection.
  49270. */
  49271. set: function (value) {
  49272. this._projectionTextureLightFar = value;
  49273. this._projectionTextureProjectionLightDirty = true;
  49274. },
  49275. enumerable: true,
  49276. configurable: true
  49277. });
  49278. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49279. /**
  49280. * Gets the Up vector of the Spotlight for texture projection.
  49281. */
  49282. get: function () {
  49283. return this._projectionTextureUpDirection;
  49284. },
  49285. /**
  49286. * Sets the Up vector of the Spotlight for texture projection.
  49287. */
  49288. set: function (value) {
  49289. this._projectionTextureUpDirection = value;
  49290. this._projectionTextureProjectionLightDirty = true;
  49291. },
  49292. enumerable: true,
  49293. configurable: true
  49294. });
  49295. ;
  49296. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49297. /**
  49298. * Gets the projection texture of the light.
  49299. */
  49300. get: function () {
  49301. return this._projectionTexture;
  49302. },
  49303. /**
  49304. * Sets the projection texture of the light.
  49305. */
  49306. set: function (value) {
  49307. this._projectionTexture = value;
  49308. this._projectionTextureDirty = true;
  49309. },
  49310. enumerable: true,
  49311. configurable: true
  49312. });
  49313. /**
  49314. * Returns the string "SpotLight".
  49315. * @returns the class name
  49316. */
  49317. SpotLight.prototype.getClassName = function () {
  49318. return "SpotLight";
  49319. };
  49320. /**
  49321. * Returns the integer 2.
  49322. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49323. */
  49324. SpotLight.prototype.getTypeID = function () {
  49325. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49326. };
  49327. /**
  49328. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49329. */
  49330. SpotLight.prototype._setDirection = function (value) {
  49331. _super.prototype._setDirection.call(this, value);
  49332. this._projectionTextureViewLightDirty = true;
  49333. };
  49334. /**
  49335. * Overrides the position setter to recompute the projection texture view light Matrix.
  49336. */
  49337. SpotLight.prototype._setPosition = function (value) {
  49338. _super.prototype._setPosition.call(this, value);
  49339. this._projectionTextureViewLightDirty = true;
  49340. };
  49341. /**
  49342. * 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.
  49343. * Returns the SpotLight.
  49344. */
  49345. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49346. var activeCamera = this.getScene().activeCamera;
  49347. if (!activeCamera) {
  49348. return;
  49349. }
  49350. this._shadowAngleScale = this._shadowAngleScale || 1;
  49351. var angle = this._shadowAngleScale * this._angle;
  49352. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49353. };
  49354. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49355. this._projectionTextureViewLightDirty = false;
  49356. this._projectionTextureDirty = true;
  49357. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49358. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49359. };
  49360. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49361. this._projectionTextureProjectionLightDirty = false;
  49362. this._projectionTextureDirty = true;
  49363. var light_far = this.projectionTextureLightFar;
  49364. var light_near = this.projectionTextureLightNear;
  49365. var P = light_far / (light_far - light_near);
  49366. var Q = -P * light_near;
  49367. var S = 1.0 / Math.tan(this._angle / 2.0);
  49368. var A = 1.0;
  49369. 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);
  49370. };
  49371. /**
  49372. * Main function for light texture projection matrix computing.
  49373. */
  49374. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49375. this._projectionTextureDirty = false;
  49376. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49377. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49378. };
  49379. SpotLight.prototype._buildUniformLayout = function () {
  49380. this._uniformBuffer.addUniform("vLightData", 4);
  49381. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49382. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49383. this._uniformBuffer.addUniform("vLightDirection", 3);
  49384. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49385. this._uniformBuffer.addUniform("depthValues", 2);
  49386. this._uniformBuffer.create();
  49387. };
  49388. /**
  49389. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49390. * @param effect The effect to update
  49391. * @param lightIndex The index of the light in the effect to update
  49392. * @returns The spot light
  49393. */
  49394. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49395. var normalizeDirection;
  49396. if (this.computeTransformedInformation()) {
  49397. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49398. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49399. }
  49400. else {
  49401. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49402. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49403. }
  49404. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49405. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49406. if (this._projectionTextureViewLightDirty) {
  49407. this._computeProjectionTextureViewLightMatrix();
  49408. }
  49409. if (this._projectionTextureProjectionLightDirty) {
  49410. this._computeProjectionTextureProjectionLightMatrix();
  49411. }
  49412. if (this._projectionTextureDirty) {
  49413. this._computeProjectionTextureMatrix();
  49414. }
  49415. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49416. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49417. }
  49418. return this;
  49419. };
  49420. /**
  49421. * Disposes the light and the associated resources.
  49422. */
  49423. SpotLight.prototype.dispose = function () {
  49424. _super.prototype.dispose.call(this);
  49425. if (this._projectionTexture) {
  49426. this._projectionTexture.dispose();
  49427. }
  49428. };
  49429. __decorate([
  49430. BABYLON.serialize()
  49431. ], SpotLight.prototype, "angle", null);
  49432. __decorate([
  49433. BABYLON.serialize()
  49434. ], SpotLight.prototype, "shadowAngleScale", null);
  49435. __decorate([
  49436. BABYLON.serialize()
  49437. ], SpotLight.prototype, "exponent", void 0);
  49438. __decorate([
  49439. BABYLON.serialize()
  49440. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49441. __decorate([
  49442. BABYLON.serialize()
  49443. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49444. __decorate([
  49445. BABYLON.serialize()
  49446. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49447. __decorate([
  49448. BABYLON.serializeAsTexture("projectedLightTexture")
  49449. ], SpotLight.prototype, "_projectionTexture", void 0);
  49450. return SpotLight;
  49451. }(BABYLON.ShadowLight));
  49452. BABYLON.SpotLight = SpotLight;
  49453. })(BABYLON || (BABYLON = {}));
  49454. //# sourceMappingURL=babylon.spotLight.js.map
  49455. "use strict";
  49456. var BABYLON;
  49457. (function (BABYLON) {
  49458. /**
  49459. * Class used to override all child animations of a given target
  49460. */
  49461. var AnimationPropertiesOverride = /** @class */ (function () {
  49462. function AnimationPropertiesOverride() {
  49463. /**
  49464. * Gets or sets a value indicating if animation blending must be used
  49465. */
  49466. this.enableBlending = false;
  49467. /**
  49468. * Gets or sets the blending speed to use when enableBlending is true
  49469. */
  49470. this.blendingSpeed = 0.01;
  49471. /**
  49472. * Gets or sets the default loop mode to use
  49473. */
  49474. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49475. }
  49476. return AnimationPropertiesOverride;
  49477. }());
  49478. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49479. })(BABYLON || (BABYLON = {}));
  49480. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49481. "use strict";
  49482. var BABYLON;
  49483. (function (BABYLON) {
  49484. var AnimationRange = /** @class */ (function () {
  49485. function AnimationRange(name, from, to) {
  49486. this.name = name;
  49487. this.from = from;
  49488. this.to = to;
  49489. }
  49490. AnimationRange.prototype.clone = function () {
  49491. return new AnimationRange(this.name, this.from, this.to);
  49492. };
  49493. return AnimationRange;
  49494. }());
  49495. BABYLON.AnimationRange = AnimationRange;
  49496. /**
  49497. * Composed of a frame, and an action function
  49498. */
  49499. var AnimationEvent = /** @class */ (function () {
  49500. function AnimationEvent(frame, action, onlyOnce) {
  49501. this.frame = frame;
  49502. this.action = action;
  49503. this.onlyOnce = onlyOnce;
  49504. this.isDone = false;
  49505. }
  49506. return AnimationEvent;
  49507. }());
  49508. BABYLON.AnimationEvent = AnimationEvent;
  49509. var PathCursor = /** @class */ (function () {
  49510. function PathCursor(path) {
  49511. this.path = path;
  49512. this._onchange = new Array();
  49513. this.value = 0;
  49514. this.animations = new Array();
  49515. }
  49516. PathCursor.prototype.getPoint = function () {
  49517. var point = this.path.getPointAtLengthPosition(this.value);
  49518. return new BABYLON.Vector3(point.x, 0, point.y);
  49519. };
  49520. PathCursor.prototype.moveAhead = function (step) {
  49521. if (step === void 0) { step = 0.002; }
  49522. this.move(step);
  49523. return this;
  49524. };
  49525. PathCursor.prototype.moveBack = function (step) {
  49526. if (step === void 0) { step = 0.002; }
  49527. this.move(-step);
  49528. return this;
  49529. };
  49530. PathCursor.prototype.move = function (step) {
  49531. if (Math.abs(step) > 1) {
  49532. throw "step size should be less than 1.";
  49533. }
  49534. this.value += step;
  49535. this.ensureLimits();
  49536. this.raiseOnChange();
  49537. return this;
  49538. };
  49539. PathCursor.prototype.ensureLimits = function () {
  49540. while (this.value > 1) {
  49541. this.value -= 1;
  49542. }
  49543. while (this.value < 0) {
  49544. this.value += 1;
  49545. }
  49546. return this;
  49547. };
  49548. // used by animation engine
  49549. PathCursor.prototype.raiseOnChange = function () {
  49550. var _this = this;
  49551. this._onchange.forEach(function (f) { return f(_this); });
  49552. return this;
  49553. };
  49554. PathCursor.prototype.onchange = function (f) {
  49555. this._onchange.push(f);
  49556. return this;
  49557. };
  49558. return PathCursor;
  49559. }());
  49560. BABYLON.PathCursor = PathCursor;
  49561. var AnimationKeyInterpolation;
  49562. (function (AnimationKeyInterpolation) {
  49563. /**
  49564. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  49565. */
  49566. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49567. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49568. var Animation = /** @class */ (function () {
  49569. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  49570. this.name = name;
  49571. this.targetProperty = targetProperty;
  49572. this.framePerSecond = framePerSecond;
  49573. this.dataType = dataType;
  49574. this.loopMode = loopMode;
  49575. this.enableBlending = enableBlending;
  49576. this._runtimeAnimations = new Array();
  49577. // The set of event that will be linked to this animation
  49578. this._events = new Array();
  49579. this.blendingSpeed = 0.01;
  49580. this._ranges = {};
  49581. this.targetPropertyPath = targetProperty.split(".");
  49582. this.dataType = dataType;
  49583. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49584. }
  49585. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49586. var dataType = undefined;
  49587. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49588. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49589. }
  49590. else if (from instanceof BABYLON.Quaternion) {
  49591. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49592. }
  49593. else if (from instanceof BABYLON.Vector3) {
  49594. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49595. }
  49596. else if (from instanceof BABYLON.Vector2) {
  49597. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49598. }
  49599. else if (from instanceof BABYLON.Color3) {
  49600. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49601. }
  49602. else if (from instanceof BABYLON.Size) {
  49603. dataType = Animation.ANIMATIONTYPE_SIZE;
  49604. }
  49605. if (dataType == undefined) {
  49606. return null;
  49607. }
  49608. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49609. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49610. animation.setKeys(keys);
  49611. if (easingFunction !== undefined) {
  49612. animation.setEasingFunction(easingFunction);
  49613. }
  49614. return animation;
  49615. };
  49616. /**
  49617. * Sets up an animation.
  49618. * @param property the property to animate
  49619. * @param animationType the animation type to apply
  49620. * @param easingFunction the easing function used in the animation
  49621. * @returns The created animation
  49622. */
  49623. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49624. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49625. animation.setEasingFunction(easingFunction);
  49626. return animation;
  49627. };
  49628. /**
  49629. * Create and start an animation on a node
  49630. * @param {string} name defines the name of the global animation that will be run on all nodes
  49631. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49632. * @param {string} targetProperty defines property to animate
  49633. * @param {number} framePerSecond defines the number of frame per second yo use
  49634. * @param {number} totalFrame defines the number of frames in total
  49635. * @param {any} from defines the initial value
  49636. * @param {any} to defines the final value
  49637. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49638. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49639. * @param onAnimationEnd defines the callback to call when animation end
  49640. * @returns the animatable created for this animation
  49641. */
  49642. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49643. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49644. if (!animation) {
  49645. return null;
  49646. }
  49647. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49648. };
  49649. /**
  49650. * Create and start an animation on a node and its descendants
  49651. * @param {string} name defines the name of the global animation that will be run on all nodes
  49652. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49653. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  49654. * @param {string} targetProperty defines property to animate
  49655. * @param {number} framePerSecond defines the number of frame per second yo use
  49656. * @param {number} totalFrame defines the number of frames in total
  49657. * @param {any} from defines the initial value
  49658. * @param {any} to defines the final value
  49659. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49660. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49661. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49662. * @returns the list of animatables created for all nodes
  49663. * @example https://www.babylonjs-playground.com/#MH0VLI
  49664. */
  49665. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49666. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49667. if (!animation) {
  49668. return null;
  49669. }
  49670. var scene = node.getScene();
  49671. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49672. };
  49673. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49674. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49675. if (!animation) {
  49676. return null;
  49677. }
  49678. node.animations.push(animation);
  49679. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49680. };
  49681. /**
  49682. * Transition property of the Camera to the target Value.
  49683. * @param property The property to transition
  49684. * @param targetValue The target Value of the property
  49685. * @param host The object where the property to animate belongs
  49686. * @param scene Scene used to run the animation
  49687. * @param frameRate Framerate (in frame/s) to use
  49688. * @param transition The transition type we want to use
  49689. * @param duration The duration of the animation, in milliseconds
  49690. * @param onAnimationEnd Call back trigger at the end of the animation.
  49691. */
  49692. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49693. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49694. if (duration <= 0) {
  49695. host[property] = targetValue;
  49696. if (onAnimationEnd) {
  49697. onAnimationEnd();
  49698. }
  49699. return null;
  49700. }
  49701. var endFrame = frameRate * (duration / 1000);
  49702. transition.setKeys([{
  49703. frame: 0,
  49704. value: host[property].clone ? host[property].clone() : host[property]
  49705. },
  49706. {
  49707. frame: endFrame,
  49708. value: targetValue
  49709. }]);
  49710. if (!host.animations) {
  49711. host.animations = [];
  49712. }
  49713. host.animations.push(transition);
  49714. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49715. animation.onAnimationEnd = onAnimationEnd;
  49716. return animation;
  49717. };
  49718. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49719. /**
  49720. * Return the array of runtime animations currently using this animation
  49721. */
  49722. get: function () {
  49723. return this._runtimeAnimations;
  49724. },
  49725. enumerable: true,
  49726. configurable: true
  49727. });
  49728. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49729. get: function () {
  49730. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49731. var runtimeAnimation = _a[_i];
  49732. if (!runtimeAnimation.isStopped) {
  49733. return true;
  49734. }
  49735. }
  49736. return false;
  49737. },
  49738. enumerable: true,
  49739. configurable: true
  49740. });
  49741. // Methods
  49742. /**
  49743. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49744. */
  49745. Animation.prototype.toString = function (fullDetails) {
  49746. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49747. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49748. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49749. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49750. if (fullDetails) {
  49751. ret += ", Ranges: {";
  49752. var first = true;
  49753. for (var name in this._ranges) {
  49754. if (first) {
  49755. ret += ", ";
  49756. first = false;
  49757. }
  49758. ret += name;
  49759. }
  49760. ret += "}";
  49761. }
  49762. return ret;
  49763. };
  49764. /**
  49765. * Add an event to this animation.
  49766. */
  49767. Animation.prototype.addEvent = function (event) {
  49768. this._events.push(event);
  49769. };
  49770. /**
  49771. * Remove all events found at the given frame
  49772. * @param frame
  49773. */
  49774. Animation.prototype.removeEvents = function (frame) {
  49775. for (var index = 0; index < this._events.length; index++) {
  49776. if (this._events[index].frame === frame) {
  49777. this._events.splice(index, 1);
  49778. index--;
  49779. }
  49780. }
  49781. };
  49782. Animation.prototype.getEvents = function () {
  49783. return this._events;
  49784. };
  49785. Animation.prototype.createRange = function (name, from, to) {
  49786. // check name not already in use; could happen for bones after serialized
  49787. if (!this._ranges[name]) {
  49788. this._ranges[name] = new AnimationRange(name, from, to);
  49789. }
  49790. };
  49791. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49792. if (deleteFrames === void 0) { deleteFrames = true; }
  49793. var range = this._ranges[name];
  49794. if (!range) {
  49795. return;
  49796. }
  49797. if (deleteFrames) {
  49798. var from = range.from;
  49799. var to = range.to;
  49800. // this loop MUST go high to low for multiple splices to work
  49801. for (var key = this._keys.length - 1; key >= 0; key--) {
  49802. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49803. this._keys.splice(key, 1);
  49804. }
  49805. }
  49806. }
  49807. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49808. };
  49809. Animation.prototype.getRange = function (name) {
  49810. return this._ranges[name];
  49811. };
  49812. Animation.prototype.getKeys = function () {
  49813. return this._keys;
  49814. };
  49815. Animation.prototype.getHighestFrame = function () {
  49816. var ret = 0;
  49817. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49818. if (ret < this._keys[key].frame) {
  49819. ret = this._keys[key].frame;
  49820. }
  49821. }
  49822. return ret;
  49823. };
  49824. Animation.prototype.getEasingFunction = function () {
  49825. return this._easingFunction;
  49826. };
  49827. Animation.prototype.setEasingFunction = function (easingFunction) {
  49828. this._easingFunction = easingFunction;
  49829. };
  49830. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49831. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49832. };
  49833. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49834. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49835. };
  49836. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49837. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49838. };
  49839. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49840. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49841. };
  49842. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49843. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49844. };
  49845. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49846. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49847. };
  49848. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49849. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49850. };
  49851. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49852. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49853. };
  49854. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49855. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49856. };
  49857. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49858. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49859. };
  49860. /**
  49861. * Defines the function to use to interpolate matrices
  49862. * @param startValue defines the start matrix
  49863. * @param endValue defines the end matrix
  49864. * @param gradient defines the gradient between both matrices
  49865. * @param result defines an optional target matrix where to store the interpolation
  49866. * @returns the interpolated matrix
  49867. */
  49868. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49869. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49870. if (result) {
  49871. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49872. return result;
  49873. }
  49874. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49875. }
  49876. if (result) {
  49877. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49878. return result;
  49879. }
  49880. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49881. };
  49882. Animation.prototype.clone = function () {
  49883. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49884. clone.enableBlending = this.enableBlending;
  49885. clone.blendingSpeed = this.blendingSpeed;
  49886. if (this._keys) {
  49887. clone.setKeys(this._keys);
  49888. }
  49889. if (this._ranges) {
  49890. clone._ranges = {};
  49891. for (var name in this._ranges) {
  49892. var range = this._ranges[name];
  49893. if (!range) {
  49894. continue;
  49895. }
  49896. clone._ranges[name] = range.clone();
  49897. }
  49898. }
  49899. return clone;
  49900. };
  49901. Animation.prototype.setKeys = function (values) {
  49902. this._keys = values.slice(0);
  49903. };
  49904. Animation.prototype.serialize = function () {
  49905. var serializationObject = {};
  49906. serializationObject.name = this.name;
  49907. serializationObject.property = this.targetProperty;
  49908. serializationObject.framePerSecond = this.framePerSecond;
  49909. serializationObject.dataType = this.dataType;
  49910. serializationObject.loopBehavior = this.loopMode;
  49911. serializationObject.enableBlending = this.enableBlending;
  49912. serializationObject.blendingSpeed = this.blendingSpeed;
  49913. var dataType = this.dataType;
  49914. serializationObject.keys = [];
  49915. var keys = this.getKeys();
  49916. for (var index = 0; index < keys.length; index++) {
  49917. var animationKey = keys[index];
  49918. var key = {};
  49919. key.frame = animationKey.frame;
  49920. switch (dataType) {
  49921. case Animation.ANIMATIONTYPE_FLOAT:
  49922. key.values = [animationKey.value];
  49923. break;
  49924. case Animation.ANIMATIONTYPE_QUATERNION:
  49925. case Animation.ANIMATIONTYPE_MATRIX:
  49926. case Animation.ANIMATIONTYPE_VECTOR3:
  49927. case Animation.ANIMATIONTYPE_COLOR3:
  49928. key.values = animationKey.value.asArray();
  49929. break;
  49930. }
  49931. serializationObject.keys.push(key);
  49932. }
  49933. serializationObject.ranges = [];
  49934. for (var name in this._ranges) {
  49935. var source = this._ranges[name];
  49936. if (!source) {
  49937. continue;
  49938. }
  49939. var range = {};
  49940. range.name = name;
  49941. range.from = source.from;
  49942. range.to = source.to;
  49943. serializationObject.ranges.push(range);
  49944. }
  49945. return serializationObject;
  49946. };
  49947. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49948. get: function () {
  49949. return Animation._ANIMATIONTYPE_FLOAT;
  49950. },
  49951. enumerable: true,
  49952. configurable: true
  49953. });
  49954. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49955. get: function () {
  49956. return Animation._ANIMATIONTYPE_VECTOR3;
  49957. },
  49958. enumerable: true,
  49959. configurable: true
  49960. });
  49961. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49962. get: function () {
  49963. return Animation._ANIMATIONTYPE_VECTOR2;
  49964. },
  49965. enumerable: true,
  49966. configurable: true
  49967. });
  49968. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49969. get: function () {
  49970. return Animation._ANIMATIONTYPE_SIZE;
  49971. },
  49972. enumerable: true,
  49973. configurable: true
  49974. });
  49975. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49976. get: function () {
  49977. return Animation._ANIMATIONTYPE_QUATERNION;
  49978. },
  49979. enumerable: true,
  49980. configurable: true
  49981. });
  49982. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49983. get: function () {
  49984. return Animation._ANIMATIONTYPE_MATRIX;
  49985. },
  49986. enumerable: true,
  49987. configurable: true
  49988. });
  49989. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49990. get: function () {
  49991. return Animation._ANIMATIONTYPE_COLOR3;
  49992. },
  49993. enumerable: true,
  49994. configurable: true
  49995. });
  49996. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49997. get: function () {
  49998. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49999. },
  50000. enumerable: true,
  50001. configurable: true
  50002. });
  50003. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50004. get: function () {
  50005. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50006. },
  50007. enumerable: true,
  50008. configurable: true
  50009. });
  50010. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50011. get: function () {
  50012. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50013. },
  50014. enumerable: true,
  50015. configurable: true
  50016. });
  50017. Animation.Parse = function (parsedAnimation) {
  50018. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50019. var dataType = parsedAnimation.dataType;
  50020. var keys = [];
  50021. var data;
  50022. var index;
  50023. if (parsedAnimation.enableBlending) {
  50024. animation.enableBlending = parsedAnimation.enableBlending;
  50025. }
  50026. if (parsedAnimation.blendingSpeed) {
  50027. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50028. }
  50029. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50030. var key = parsedAnimation.keys[index];
  50031. var inTangent;
  50032. var outTangent;
  50033. switch (dataType) {
  50034. case Animation.ANIMATIONTYPE_FLOAT:
  50035. data = key.values[0];
  50036. if (key.values.length >= 1) {
  50037. inTangent = key.values[1];
  50038. }
  50039. if (key.values.length >= 2) {
  50040. outTangent = key.values[2];
  50041. }
  50042. break;
  50043. case Animation.ANIMATIONTYPE_QUATERNION:
  50044. data = BABYLON.Quaternion.FromArray(key.values);
  50045. if (key.values.length >= 8) {
  50046. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50047. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50048. inTangent = _inTangent;
  50049. }
  50050. }
  50051. if (key.values.length >= 12) {
  50052. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50053. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50054. outTangent = _outTangent;
  50055. }
  50056. }
  50057. break;
  50058. case Animation.ANIMATIONTYPE_MATRIX:
  50059. data = BABYLON.Matrix.FromArray(key.values);
  50060. break;
  50061. case Animation.ANIMATIONTYPE_COLOR3:
  50062. data = BABYLON.Color3.FromArray(key.values);
  50063. break;
  50064. case Animation.ANIMATIONTYPE_VECTOR3:
  50065. default:
  50066. data = BABYLON.Vector3.FromArray(key.values);
  50067. break;
  50068. }
  50069. var keyData = {};
  50070. keyData.frame = key.frame;
  50071. keyData.value = data;
  50072. if (inTangent != undefined) {
  50073. keyData.inTangent = inTangent;
  50074. }
  50075. if (outTangent != undefined) {
  50076. keyData.outTangent = outTangent;
  50077. }
  50078. keys.push(keyData);
  50079. }
  50080. animation.setKeys(keys);
  50081. if (parsedAnimation.ranges) {
  50082. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50083. data = parsedAnimation.ranges[index];
  50084. animation.createRange(data.name, data.from, data.to);
  50085. }
  50086. }
  50087. return animation;
  50088. };
  50089. Animation.AppendSerializedAnimations = function (source, destination) {
  50090. if (source.animations) {
  50091. destination.animations = [];
  50092. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50093. var animation = source.animations[animationIndex];
  50094. destination.animations.push(animation.serialize());
  50095. }
  50096. }
  50097. };
  50098. /**
  50099. * Use matrix interpolation instead of using direct key value when animating matrices
  50100. */
  50101. Animation.AllowMatricesInterpolation = false;
  50102. /**
  50103. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50104. */
  50105. Animation.AllowMatrixDecomposeForInterpolation = true;
  50106. // Statics
  50107. Animation._ANIMATIONTYPE_FLOAT = 0;
  50108. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50109. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50110. Animation._ANIMATIONTYPE_MATRIX = 3;
  50111. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50112. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50113. Animation._ANIMATIONTYPE_SIZE = 6;
  50114. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50115. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50116. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50117. return Animation;
  50118. }());
  50119. BABYLON.Animation = Animation;
  50120. })(BABYLON || (BABYLON = {}));
  50121. //# sourceMappingURL=babylon.animation.js.map
  50122. "use strict";
  50123. var BABYLON;
  50124. (function (BABYLON) {
  50125. /**
  50126. * This class defines the direct association between an animation and a target
  50127. */
  50128. var TargetedAnimation = /** @class */ (function () {
  50129. function TargetedAnimation() {
  50130. }
  50131. return TargetedAnimation;
  50132. }());
  50133. BABYLON.TargetedAnimation = TargetedAnimation;
  50134. /**
  50135. * Use this class to create coordinated animations on multiple targets
  50136. */
  50137. var AnimationGroup = /** @class */ (function () {
  50138. function AnimationGroup(name, scene) {
  50139. if (scene === void 0) { scene = null; }
  50140. this.name = name;
  50141. this._targetedAnimations = new Array();
  50142. this._animatables = new Array();
  50143. this._from = Number.MAX_VALUE;
  50144. this._to = -Number.MAX_VALUE;
  50145. this._speedRatio = 1;
  50146. this.onAnimationEndObservable = new BABYLON.Observable();
  50147. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50148. this._scene.animationGroups.push(this);
  50149. }
  50150. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50151. /**
  50152. * Define if the animations are started
  50153. */
  50154. get: function () {
  50155. return this._isStarted;
  50156. },
  50157. enumerable: true,
  50158. configurable: true
  50159. });
  50160. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50161. /**
  50162. * Gets or sets the speed ratio to use for all animations
  50163. */
  50164. get: function () {
  50165. return this._speedRatio;
  50166. },
  50167. /**
  50168. * Gets or sets the speed ratio to use for all animations
  50169. */
  50170. set: function (value) {
  50171. if (this._speedRatio === value) {
  50172. return;
  50173. }
  50174. this._speedRatio = value;
  50175. for (var index = 0; index < this._animatables.length; index++) {
  50176. var animatable = this._animatables[index];
  50177. animatable.speedRatio = this._speedRatio;
  50178. }
  50179. },
  50180. enumerable: true,
  50181. configurable: true
  50182. });
  50183. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50184. /**
  50185. * Gets the targeted animations for this animation group
  50186. */
  50187. get: function () {
  50188. return this._targetedAnimations;
  50189. },
  50190. enumerable: true,
  50191. configurable: true
  50192. });
  50193. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50194. /**
  50195. * returning the list of animatables controlled by this animation group.
  50196. */
  50197. get: function () {
  50198. return this._animatables;
  50199. },
  50200. enumerable: true,
  50201. configurable: true
  50202. });
  50203. /**
  50204. * Add an animation (with its target) in the group
  50205. * @param animation defines the animation we want to add
  50206. * @param target defines the target of the animation
  50207. * @returns the {BABYLON.TargetedAnimation} object
  50208. */
  50209. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50210. var targetedAnimation = {
  50211. animation: animation,
  50212. target: target
  50213. };
  50214. var keys = animation.getKeys();
  50215. if (this._from > keys[0].frame) {
  50216. this._from = keys[0].frame;
  50217. }
  50218. if (this._to < keys[keys.length - 1].frame) {
  50219. this._to = keys[keys.length - 1].frame;
  50220. }
  50221. this._targetedAnimations.push(targetedAnimation);
  50222. return targetedAnimation;
  50223. };
  50224. /**
  50225. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50226. * It can add constant keys at begin or end
  50227. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  50228. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  50229. */
  50230. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50231. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  50232. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  50233. beginFrame = Math.max(beginFrame, this._from);
  50234. endFrame = Math.min(endFrame, this._to);
  50235. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50236. var targetedAnimation = this._targetedAnimations[index];
  50237. var keys = targetedAnimation.animation.getKeys();
  50238. var startKey = keys[0];
  50239. var endKey = keys[keys.length - 1];
  50240. if (startKey.frame > beginFrame) {
  50241. var newKey = {
  50242. frame: beginFrame,
  50243. value: startKey.value,
  50244. inTangent: startKey.inTangent,
  50245. outTangent: startKey.outTangent,
  50246. interpolation: startKey.interpolation
  50247. };
  50248. keys.splice(0, 0, newKey);
  50249. }
  50250. if (endKey.frame < endFrame) {
  50251. var newKey = {
  50252. frame: endFrame,
  50253. value: endKey.value,
  50254. inTangent: endKey.outTangent,
  50255. outTangent: endKey.outTangent,
  50256. interpolation: endKey.interpolation
  50257. };
  50258. keys.push(newKey);
  50259. }
  50260. }
  50261. return this;
  50262. };
  50263. /**
  50264. * Start all animations on given targets
  50265. * @param loop defines if animations must loop
  50266. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50267. * @param from defines the from key (optional)
  50268. * @param to defines the to key (optional)
  50269. * @returns the current animation group
  50270. */
  50271. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50272. var _this = this;
  50273. if (loop === void 0) { loop = false; }
  50274. if (speedRatio === void 0) { speedRatio = 1; }
  50275. if (this._isStarted || this._targetedAnimations.length === 0) {
  50276. return this;
  50277. }
  50278. var _loop_1 = function () {
  50279. var targetedAnimation = this_1._targetedAnimations[index];
  50280. if (!targetedAnimation.target.animations) {
  50281. targetedAnimation.target.animations = [];
  50282. }
  50283. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  50284. targetedAnimation.target.animations.push(targetedAnimation.animation);
  50285. }
  50286. 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 () {
  50287. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50288. }));
  50289. };
  50290. var this_1 = this;
  50291. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50292. _loop_1();
  50293. }
  50294. this._speedRatio = speedRatio;
  50295. this._isStarted = true;
  50296. return this;
  50297. };
  50298. /**
  50299. * Pause all animations
  50300. */
  50301. AnimationGroup.prototype.pause = function () {
  50302. if (!this._isStarted) {
  50303. return this;
  50304. }
  50305. for (var index = 0; index < this._animatables.length; index++) {
  50306. var animatable = this._animatables[index];
  50307. animatable.pause();
  50308. }
  50309. return this;
  50310. };
  50311. /**
  50312. * Play all animations to initial state
  50313. * This function will start() the animations if they were not started or will restart() them if they were paused
  50314. * @param loop defines if animations must loop
  50315. */
  50316. AnimationGroup.prototype.play = function (loop) {
  50317. if (this.isStarted) {
  50318. if (loop !== undefined) {
  50319. for (var index = 0; index < this._animatables.length; index++) {
  50320. var animatable = this._animatables[index];
  50321. animatable.loopAnimation = loop;
  50322. }
  50323. }
  50324. this.restart();
  50325. }
  50326. else {
  50327. this.start(loop, this._speedRatio);
  50328. }
  50329. return this;
  50330. };
  50331. /**
  50332. * Reset all animations to initial state
  50333. */
  50334. AnimationGroup.prototype.reset = function () {
  50335. if (!this._isStarted) {
  50336. return this;
  50337. }
  50338. for (var index = 0; index < this._animatables.length; index++) {
  50339. var animatable = this._animatables[index];
  50340. animatable.reset();
  50341. }
  50342. return this;
  50343. };
  50344. /**
  50345. * Restart animations from key 0
  50346. */
  50347. AnimationGroup.prototype.restart = function () {
  50348. if (!this._isStarted) {
  50349. return this;
  50350. }
  50351. for (var index = 0; index < this._animatables.length; index++) {
  50352. var animatable = this._animatables[index];
  50353. animatable.restart();
  50354. }
  50355. return this;
  50356. };
  50357. /**
  50358. * Stop all animations
  50359. */
  50360. AnimationGroup.prototype.stop = function () {
  50361. if (!this._isStarted) {
  50362. return this;
  50363. }
  50364. for (var index = 0; index < this._animatables.length; index++) {
  50365. var animatable = this._animatables[index];
  50366. animatable.stop();
  50367. }
  50368. this._isStarted = false;
  50369. return this;
  50370. };
  50371. /**
  50372. * Goes to a specific frame in this animation group
  50373. *
  50374. * @param frame the frame number to go to
  50375. * @return the animationGroup
  50376. */
  50377. AnimationGroup.prototype.goToFrame = function (frame) {
  50378. if (!this._isStarted) {
  50379. return this;
  50380. }
  50381. for (var index = 0; index < this._animatables.length; index++) {
  50382. var animatable = this._animatables[index];
  50383. animatable.goToFrame(frame);
  50384. }
  50385. return this;
  50386. };
  50387. /**
  50388. * Dispose all associated resources
  50389. */
  50390. AnimationGroup.prototype.dispose = function () {
  50391. this._targetedAnimations = [];
  50392. this._animatables = [];
  50393. var index = this._scene.animationGroups.indexOf(this);
  50394. if (index > -1) {
  50395. this._scene.animationGroups.splice(index, 1);
  50396. }
  50397. };
  50398. return AnimationGroup;
  50399. }());
  50400. BABYLON.AnimationGroup = AnimationGroup;
  50401. })(BABYLON || (BABYLON = {}));
  50402. //# sourceMappingURL=babylon.animationGroup.js.map
  50403. "use strict";
  50404. var BABYLON;
  50405. (function (BABYLON) {
  50406. var RuntimeAnimation = /** @class */ (function () {
  50407. /**
  50408. * Create a new RuntimeAnimation object
  50409. * @param target defines the target of the animation
  50410. * @param animation defines the source {BABYLON.Animation} object
  50411. * @param scene defines the hosting scene
  50412. * @param host defines the initiating Animatable
  50413. */
  50414. function RuntimeAnimation(target, animation, scene, host) {
  50415. this._currentFrame = 0;
  50416. this._offsetsCache = {};
  50417. this._highLimitsCache = {};
  50418. this._stopped = false;
  50419. this._blendingFactor = 0;
  50420. this._targetPath = "";
  50421. this._weight = 1.0;
  50422. this._ratioOffset = 0;
  50423. this._previousDelay = 0;
  50424. this._previousRatio = 0;
  50425. this._animation = animation;
  50426. this._target = target;
  50427. this._scene = scene;
  50428. this._host = host;
  50429. animation._runtimeAnimations.push(this);
  50430. }
  50431. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50432. /**
  50433. * Gets the current frame
  50434. */
  50435. get: function () {
  50436. return this._currentFrame;
  50437. },
  50438. enumerable: true,
  50439. configurable: true
  50440. });
  50441. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50442. /**
  50443. * Gets the weight of the runtime animation
  50444. */
  50445. get: function () {
  50446. return this._weight;
  50447. },
  50448. enumerable: true,
  50449. configurable: true
  50450. });
  50451. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  50452. /**
  50453. * Gets the original value of the runtime animation
  50454. */
  50455. get: function () {
  50456. return this._originalValue;
  50457. },
  50458. enumerable: true,
  50459. configurable: true
  50460. });
  50461. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50462. /**
  50463. * Gets the current value of the runtime animation
  50464. */
  50465. get: function () {
  50466. return this._currentValue;
  50467. },
  50468. enumerable: true,
  50469. configurable: true
  50470. });
  50471. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50472. /**
  50473. * Gets the path where to store the animated value in the target
  50474. */
  50475. get: function () {
  50476. return this._targetPath;
  50477. },
  50478. enumerable: true,
  50479. configurable: true
  50480. });
  50481. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50482. /**
  50483. * Gets the actual target of the runtime animation
  50484. */
  50485. get: function () {
  50486. return this._activeTarget;
  50487. },
  50488. enumerable: true,
  50489. configurable: true
  50490. });
  50491. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50492. get: function () {
  50493. return this._animation;
  50494. },
  50495. enumerable: true,
  50496. configurable: true
  50497. });
  50498. RuntimeAnimation.prototype.reset = function () {
  50499. this._offsetsCache = {};
  50500. this._highLimitsCache = {};
  50501. this._currentFrame = 0;
  50502. this._blendingFactor = 0;
  50503. this._originalValue = null;
  50504. };
  50505. RuntimeAnimation.prototype.isStopped = function () {
  50506. return this._stopped;
  50507. };
  50508. RuntimeAnimation.prototype.dispose = function () {
  50509. var index = this._animation.runtimeAnimations.indexOf(this);
  50510. if (index > -1) {
  50511. this._animation.runtimeAnimations.splice(index, 1);
  50512. }
  50513. };
  50514. RuntimeAnimation.prototype._getKeyValue = function (value) {
  50515. if (typeof value === "function") {
  50516. return value();
  50517. }
  50518. return value;
  50519. };
  50520. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50521. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50522. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50523. }
  50524. this._currentFrame = currentFrame;
  50525. var keys = this._animation.getKeys();
  50526. // Try to get a hash to find the right key
  50527. 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));
  50528. if (keys[startKeyIndex].frame >= currentFrame) {
  50529. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50530. startKeyIndex--;
  50531. }
  50532. }
  50533. for (var key = startKeyIndex; key < keys.length; key++) {
  50534. var endKey = keys[key + 1];
  50535. if (endKey.frame >= currentFrame) {
  50536. var startKey = keys[key];
  50537. var startValue = this._getKeyValue(startKey.value);
  50538. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  50539. return startValue;
  50540. }
  50541. var endValue = this._getKeyValue(endKey.value);
  50542. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50543. var frameDelta = endKey.frame - startKey.frame;
  50544. // gradient : percent of currentFrame between the frame inf and the frame sup
  50545. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50546. // check for easingFunction and correction of gradient
  50547. var easingFunction = this._animation.getEasingFunction();
  50548. if (easingFunction != null) {
  50549. gradient = easingFunction.ease(gradient);
  50550. }
  50551. switch (this._animation.dataType) {
  50552. // Float
  50553. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50554. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  50555. switch (loopMode) {
  50556. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50557. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50558. return floatValue;
  50559. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50560. return offsetValue * repeatCount + floatValue;
  50561. }
  50562. break;
  50563. // Quaternion
  50564. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50565. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  50566. switch (loopMode) {
  50567. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50568. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50569. return quatValue;
  50570. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50571. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50572. }
  50573. return quatValue;
  50574. // Vector3
  50575. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50576. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  50577. switch (loopMode) {
  50578. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50579. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50580. return vec3Value;
  50581. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50582. return vec3Value.add(offsetValue.scale(repeatCount));
  50583. }
  50584. // Vector2
  50585. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50586. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  50587. switch (loopMode) {
  50588. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50589. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50590. return vec2Value;
  50591. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50592. return vec2Value.add(offsetValue.scale(repeatCount));
  50593. }
  50594. // Size
  50595. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50596. switch (loopMode) {
  50597. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50598. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50599. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  50600. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50601. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50602. }
  50603. // Color3
  50604. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50605. switch (loopMode) {
  50606. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50607. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50608. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  50609. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50610. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50611. }
  50612. // Matrix
  50613. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  50614. switch (loopMode) {
  50615. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50616. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50617. if (BABYLON.Animation.AllowMatricesInterpolation) {
  50618. this._workValue = this._animation.matrixInterpolateFunction(startValue, endValue, gradient, this._workValue);
  50619. return this._workValue;
  50620. }
  50621. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50622. return startValue;
  50623. }
  50624. default:
  50625. break;
  50626. }
  50627. break;
  50628. }
  50629. }
  50630. return this._getKeyValue(keys[keys.length - 1].value);
  50631. };
  50632. /**
  50633. * Affect the interpolated value to the target
  50634. * @param currentValue defines the value computed by the animation
  50635. * @param weight defines the weight to apply to this value
  50636. */
  50637. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50638. if (weight === void 0) { weight = 1.0; }
  50639. // Set value
  50640. var path;
  50641. var destination;
  50642. var targetPropertyPath = this._animation.targetPropertyPath;
  50643. if (targetPropertyPath.length > 1) {
  50644. var property = this._target[targetPropertyPath[0]];
  50645. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50646. property = property[targetPropertyPath[index]];
  50647. }
  50648. path = targetPropertyPath[targetPropertyPath.length - 1];
  50649. destination = property;
  50650. }
  50651. else {
  50652. path = targetPropertyPath[0];
  50653. destination = this._target;
  50654. }
  50655. this._targetPath = path;
  50656. this._activeTarget = destination;
  50657. this._weight = weight;
  50658. // Blending
  50659. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50660. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50661. if (enableBlending && this._blendingFactor <= 1.0) {
  50662. if (!this._originalBlendValue) {
  50663. var originalValue = destination[path];
  50664. if (originalValue.clone) {
  50665. this._originalBlendValue = originalValue.clone();
  50666. }
  50667. else {
  50668. this._originalBlendValue = originalValue;
  50669. }
  50670. }
  50671. }
  50672. if (weight !== -1.0) {
  50673. if (!this._originalValue) {
  50674. var originalValue = void 0;
  50675. if (destination.getRestPose) {
  50676. originalValue = destination.getRestPose();
  50677. }
  50678. else {
  50679. originalValue = destination[path];
  50680. }
  50681. if (originalValue.clone) {
  50682. this._originalValue = originalValue.clone();
  50683. }
  50684. else {
  50685. this._originalValue = originalValue;
  50686. }
  50687. }
  50688. }
  50689. if (enableBlending && this._blendingFactor <= 1.0) {
  50690. if (this._originalBlendValue.prototype) {
  50691. if (this._originalBlendValue.prototype.Lerp) {
  50692. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  50693. }
  50694. else {
  50695. this._currentValue = currentValue;
  50696. }
  50697. }
  50698. else if (this._originalBlendValue.m) {
  50699. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50700. if (this._currentValue) {
  50701. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50702. }
  50703. else {
  50704. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50705. }
  50706. }
  50707. else {
  50708. if (this._currentValue) {
  50709. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50710. }
  50711. else {
  50712. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50713. }
  50714. }
  50715. }
  50716. else {
  50717. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  50718. }
  50719. this._blendingFactor += blendingSpeed;
  50720. }
  50721. else {
  50722. this._currentValue = currentValue;
  50723. }
  50724. if (weight !== -1.0) {
  50725. this._scene._registerTargetForLateAnimationBinding(this);
  50726. }
  50727. else {
  50728. destination[path] = this._currentValue;
  50729. }
  50730. if (this._target.markAsDirty) {
  50731. this._target.markAsDirty(this._animation.targetProperty);
  50732. }
  50733. };
  50734. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50735. if (this._target && this._target.animationPropertiesOverride) {
  50736. return this._target.animationPropertiesOverride.loopMode;
  50737. }
  50738. return this._animation.loopMode;
  50739. };
  50740. /**
  50741. * Move the current animation to a given frame
  50742. * @param frame defines the frame to move to
  50743. */
  50744. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50745. var keys = this._animation.getKeys();
  50746. if (frame < keys[0].frame) {
  50747. frame = keys[0].frame;
  50748. }
  50749. else if (frame > keys[keys.length - 1].frame) {
  50750. frame = keys[keys.length - 1].frame;
  50751. }
  50752. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50753. this.setValue(currentValue, -1);
  50754. };
  50755. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50756. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50757. this._ratioOffset = this._previousRatio - newRatio;
  50758. };
  50759. /**
  50760. * Execute the current animation
  50761. * @param delay defines the delay to add to the current frame
  50762. * @param from defines the lower bound of the animation range
  50763. * @param to defines the upper bound of the animation range
  50764. * @param loop defines if the current animation must loop
  50765. * @param speedRatio defines the current speed ratio
  50766. * @param weight defines the weight of the animation (default is -1 so no weight)
  50767. * @returns a boolean indicating if the animation has ended
  50768. */
  50769. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50770. if (weight === void 0) { weight = -1.0; }
  50771. var targetPropertyPath = this._animation.targetPropertyPath;
  50772. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50773. this._stopped = true;
  50774. return false;
  50775. }
  50776. var returnValue = true;
  50777. var keys = this._animation.getKeys();
  50778. // Adding a start key at frame 0 if missing
  50779. if (keys[0].frame !== 0) {
  50780. var newKey = { frame: 0, value: keys[0].value };
  50781. keys.splice(0, 0, newKey);
  50782. }
  50783. // Check limits
  50784. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50785. from = keys[0].frame;
  50786. }
  50787. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50788. to = keys[keys.length - 1].frame;
  50789. }
  50790. //to and from cannot be the same key
  50791. if (from === to) {
  50792. if (from > keys[0].frame) {
  50793. from--;
  50794. }
  50795. else if (to < keys[keys.length - 1].frame) {
  50796. to++;
  50797. }
  50798. }
  50799. // Compute ratio
  50800. var range = to - from;
  50801. var offsetValue;
  50802. // ratio represents the frame delta between from and to
  50803. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50804. var highLimitValue = 0;
  50805. this._previousDelay = delay;
  50806. this._previousRatio = ratio;
  50807. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  50808. returnValue = false;
  50809. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  50810. }
  50811. else {
  50812. // Get max value if required
  50813. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50814. var keyOffset = to.toString() + from.toString();
  50815. if (!this._offsetsCache[keyOffset]) {
  50816. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50817. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50818. switch (this._animation.dataType) {
  50819. // Float
  50820. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50821. this._offsetsCache[keyOffset] = toValue - fromValue;
  50822. break;
  50823. // Quaternion
  50824. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50825. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50826. break;
  50827. // Vector3
  50828. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50829. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50830. // Vector2
  50831. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50832. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50833. // Size
  50834. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50835. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50836. // Color3
  50837. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50838. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50839. default:
  50840. break;
  50841. }
  50842. this._highLimitsCache[keyOffset] = toValue;
  50843. }
  50844. highLimitValue = this._highLimitsCache[keyOffset];
  50845. offsetValue = this._offsetsCache[keyOffset];
  50846. }
  50847. }
  50848. if (offsetValue === undefined) {
  50849. switch (this._animation.dataType) {
  50850. // Float
  50851. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50852. offsetValue = 0;
  50853. break;
  50854. // Quaternion
  50855. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50856. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50857. break;
  50858. // Vector3
  50859. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50860. offsetValue = BABYLON.Vector3.Zero();
  50861. break;
  50862. // Vector2
  50863. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50864. offsetValue = BABYLON.Vector2.Zero();
  50865. break;
  50866. // Size
  50867. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50868. offsetValue = BABYLON.Size.Zero();
  50869. break;
  50870. // Color3
  50871. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50872. offsetValue = BABYLON.Color3.Black();
  50873. }
  50874. }
  50875. // Compute value
  50876. var repeatCount = (ratio / range) >> 0;
  50877. var currentFrame = returnValue ? from + ratio % range : to;
  50878. // Need to normalize?
  50879. if (this._host && this._host.syncRoot) {
  50880. var syncRoot = this._host.syncRoot;
  50881. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50882. currentFrame = from + (to - from) * hostNormalizedFrame;
  50883. }
  50884. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50885. // Set value
  50886. this.setValue(currentValue, weight);
  50887. // Check events
  50888. var events = this._animation.getEvents();
  50889. for (var index = 0; index < events.length; index++) {
  50890. // Make sure current frame has passed event frame and that event frame is within the current range
  50891. // Also, handle both forward and reverse animations
  50892. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50893. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50894. var event = events[index];
  50895. if (!event.isDone) {
  50896. // If event should be done only once, remove it.
  50897. if (event.onlyOnce) {
  50898. events.splice(index, 1);
  50899. index--;
  50900. }
  50901. event.isDone = true;
  50902. event.action();
  50903. } // Don't do anything if the event has already be done.
  50904. }
  50905. else if (events[index].isDone && !events[index].onlyOnce) {
  50906. // reset event, the animation is looping
  50907. events[index].isDone = false;
  50908. }
  50909. }
  50910. if (!returnValue) {
  50911. this._stopped = true;
  50912. }
  50913. return returnValue;
  50914. };
  50915. return RuntimeAnimation;
  50916. }());
  50917. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50918. })(BABYLON || (BABYLON = {}));
  50919. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50920. "use strict";
  50921. var BABYLON;
  50922. (function (BABYLON) {
  50923. var Animatable = /** @class */ (function () {
  50924. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  50925. if (fromFrame === void 0) { fromFrame = 0; }
  50926. if (toFrame === void 0) { toFrame = 100; }
  50927. if (loopAnimation === void 0) { loopAnimation = false; }
  50928. if (speedRatio === void 0) { speedRatio = 1.0; }
  50929. this.target = target;
  50930. this.fromFrame = fromFrame;
  50931. this.toFrame = toFrame;
  50932. this.loopAnimation = loopAnimation;
  50933. this.onAnimationEnd = onAnimationEnd;
  50934. this._localDelayOffset = null;
  50935. this._pausedDelay = null;
  50936. this._runtimeAnimations = new Array();
  50937. this._paused = false;
  50938. this._speedRatio = 1;
  50939. this._weight = -1.0;
  50940. this.animationStarted = false;
  50941. if (animations) {
  50942. this.appendAnimations(target, animations);
  50943. }
  50944. this._speedRatio = speedRatio;
  50945. this._scene = scene;
  50946. scene._activeAnimatables.push(this);
  50947. }
  50948. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50949. /**
  50950. * Gets the root Animatable used to synchronize and normalize animations
  50951. */
  50952. get: function () {
  50953. return this._syncRoot;
  50954. },
  50955. enumerable: true,
  50956. configurable: true
  50957. });
  50958. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50959. /**
  50960. * Gets the current frame of the first RuntimeAnimation
  50961. * Used to synchronize Animatables
  50962. */
  50963. get: function () {
  50964. if (this._runtimeAnimations.length === 0) {
  50965. return 0;
  50966. }
  50967. return this._runtimeAnimations[0].currentFrame;
  50968. },
  50969. enumerable: true,
  50970. configurable: true
  50971. });
  50972. Object.defineProperty(Animatable.prototype, "weight", {
  50973. /**
  50974. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50975. */
  50976. get: function () {
  50977. return this._weight;
  50978. },
  50979. set: function (value) {
  50980. if (value === -1) {
  50981. this._weight = -1;
  50982. return;
  50983. }
  50984. // Else weight must be in [0, 1] range
  50985. this._weight = Math.min(Math.max(value, 0), 1.0);
  50986. },
  50987. enumerable: true,
  50988. configurable: true
  50989. });
  50990. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50991. /**
  50992. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50993. */
  50994. get: function () {
  50995. return this._speedRatio;
  50996. },
  50997. set: function (value) {
  50998. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50999. var animation = this._runtimeAnimations[index];
  51000. animation._prepareForSpeedRatioChange(value);
  51001. }
  51002. this._speedRatio = value;
  51003. },
  51004. enumerable: true,
  51005. configurable: true
  51006. });
  51007. // Methods
  51008. /**
  51009. * Synchronize and normalize current Animatable with a source Animatable.
  51010. * This is useful when using animation weights and when animations are not of the same length
  51011. * @param root defines the root Animatable to synchronize with
  51012. * @returns the current Animatable
  51013. */
  51014. Animatable.prototype.syncWith = function (root) {
  51015. this._syncRoot = root;
  51016. if (root) {
  51017. // Make sure this animatable will animate after the root
  51018. var index = this._scene._activeAnimatables.indexOf(this);
  51019. if (index > -1) {
  51020. this._scene._activeAnimatables.splice(index, 1);
  51021. this._scene._activeAnimatables.push(this);
  51022. }
  51023. }
  51024. return this;
  51025. };
  51026. Animatable.prototype.getAnimations = function () {
  51027. return this._runtimeAnimations;
  51028. };
  51029. Animatable.prototype.appendAnimations = function (target, animations) {
  51030. for (var index = 0; index < animations.length; index++) {
  51031. var animation = animations[index];
  51032. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51033. }
  51034. };
  51035. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51036. var runtimeAnimations = this._runtimeAnimations;
  51037. for (var index = 0; index < runtimeAnimations.length; index++) {
  51038. if (runtimeAnimations[index].animation.targetProperty === property) {
  51039. return runtimeAnimations[index].animation;
  51040. }
  51041. }
  51042. return null;
  51043. };
  51044. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51045. var runtimeAnimations = this._runtimeAnimations;
  51046. for (var index = 0; index < runtimeAnimations.length; index++) {
  51047. if (runtimeAnimations[index].animation.targetProperty === property) {
  51048. return runtimeAnimations[index];
  51049. }
  51050. }
  51051. return null;
  51052. };
  51053. Animatable.prototype.reset = function () {
  51054. var runtimeAnimations = this._runtimeAnimations;
  51055. for (var index = 0; index < runtimeAnimations.length; index++) {
  51056. runtimeAnimations[index].reset();
  51057. }
  51058. // Reset to original value
  51059. for (index = 0; index < runtimeAnimations.length; index++) {
  51060. var animation = runtimeAnimations[index];
  51061. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  51062. }
  51063. this._localDelayOffset = null;
  51064. this._pausedDelay = null;
  51065. };
  51066. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51067. var runtimeAnimations = this._runtimeAnimations;
  51068. for (var index = 0; index < runtimeAnimations.length; index++) {
  51069. runtimeAnimations[index].animation.enableBlending = true;
  51070. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51071. }
  51072. };
  51073. Animatable.prototype.disableBlending = function () {
  51074. var runtimeAnimations = this._runtimeAnimations;
  51075. for (var index = 0; index < runtimeAnimations.length; index++) {
  51076. runtimeAnimations[index].animation.enableBlending = false;
  51077. }
  51078. };
  51079. Animatable.prototype.goToFrame = function (frame) {
  51080. var runtimeAnimations = this._runtimeAnimations;
  51081. if (runtimeAnimations[0]) {
  51082. var fps = runtimeAnimations[0].animation.framePerSecond;
  51083. var currentFrame = runtimeAnimations[0].currentFrame;
  51084. var adjustTime = frame - currentFrame;
  51085. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51086. if (this._localDelayOffset === null) {
  51087. this._localDelayOffset = 0;
  51088. }
  51089. this._localDelayOffset -= delay;
  51090. }
  51091. for (var index = 0; index < runtimeAnimations.length; index++) {
  51092. runtimeAnimations[index].goToFrame(frame);
  51093. }
  51094. };
  51095. Animatable.prototype.pause = function () {
  51096. if (this._paused) {
  51097. return;
  51098. }
  51099. this._paused = true;
  51100. };
  51101. Animatable.prototype.restart = function () {
  51102. this._paused = false;
  51103. };
  51104. Animatable.prototype.stop = function (animationName) {
  51105. if (animationName) {
  51106. var idx = this._scene._activeAnimatables.indexOf(this);
  51107. if (idx > -1) {
  51108. var runtimeAnimations = this._runtimeAnimations;
  51109. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51110. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51111. continue;
  51112. }
  51113. runtimeAnimations[index].dispose();
  51114. runtimeAnimations.splice(index, 1);
  51115. }
  51116. if (runtimeAnimations.length == 0) {
  51117. this._scene._activeAnimatables.splice(idx, 1);
  51118. if (this.onAnimationEnd) {
  51119. this.onAnimationEnd();
  51120. }
  51121. }
  51122. }
  51123. }
  51124. else {
  51125. var index = this._scene._activeAnimatables.indexOf(this);
  51126. if (index > -1) {
  51127. this._scene._activeAnimatables.splice(index, 1);
  51128. var runtimeAnimations = this._runtimeAnimations;
  51129. for (var index = 0; index < runtimeAnimations.length; index++) {
  51130. runtimeAnimations[index].dispose();
  51131. }
  51132. if (this.onAnimationEnd) {
  51133. this.onAnimationEnd();
  51134. }
  51135. }
  51136. }
  51137. };
  51138. Animatable.prototype._animate = function (delay) {
  51139. if (this._paused) {
  51140. this.animationStarted = false;
  51141. if (this._pausedDelay === null) {
  51142. this._pausedDelay = delay;
  51143. }
  51144. return true;
  51145. }
  51146. if (this._localDelayOffset === null) {
  51147. this._localDelayOffset = delay;
  51148. this._pausedDelay = null;
  51149. }
  51150. else if (this._pausedDelay !== null) {
  51151. this._localDelayOffset += delay - this._pausedDelay;
  51152. this._pausedDelay = null;
  51153. }
  51154. if (this._weight === 0) {
  51155. return true;
  51156. }
  51157. // Animating
  51158. var running = false;
  51159. var runtimeAnimations = this._runtimeAnimations;
  51160. var index;
  51161. for (index = 0; index < runtimeAnimations.length; index++) {
  51162. var animation = runtimeAnimations[index];
  51163. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51164. running = running || isRunning;
  51165. }
  51166. this.animationStarted = running;
  51167. if (!running) {
  51168. // Remove from active animatables
  51169. index = this._scene._activeAnimatables.indexOf(this);
  51170. this._scene._activeAnimatables.splice(index, 1);
  51171. // Dispose all runtime animations
  51172. for (index = 0; index < runtimeAnimations.length; index++) {
  51173. runtimeAnimations[index].dispose();
  51174. }
  51175. }
  51176. if (!running && this.onAnimationEnd) {
  51177. this.onAnimationEnd();
  51178. this.onAnimationEnd = null;
  51179. }
  51180. return running;
  51181. };
  51182. return Animatable;
  51183. }());
  51184. BABYLON.Animatable = Animatable;
  51185. })(BABYLON || (BABYLON = {}));
  51186. //# sourceMappingURL=babylon.animatable.js.map
  51187. "use strict";
  51188. var BABYLON;
  51189. (function (BABYLON) {
  51190. var EasingFunction = /** @class */ (function () {
  51191. function EasingFunction() {
  51192. // Properties
  51193. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51194. }
  51195. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51196. get: function () {
  51197. return EasingFunction._EASINGMODE_EASEIN;
  51198. },
  51199. enumerable: true,
  51200. configurable: true
  51201. });
  51202. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51203. get: function () {
  51204. return EasingFunction._EASINGMODE_EASEOUT;
  51205. },
  51206. enumerable: true,
  51207. configurable: true
  51208. });
  51209. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51210. get: function () {
  51211. return EasingFunction._EASINGMODE_EASEINOUT;
  51212. },
  51213. enumerable: true,
  51214. configurable: true
  51215. });
  51216. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51217. var n = Math.min(Math.max(easingMode, 0), 2);
  51218. this._easingMode = n;
  51219. };
  51220. EasingFunction.prototype.getEasingMode = function () {
  51221. return this._easingMode;
  51222. };
  51223. EasingFunction.prototype.easeInCore = function (gradient) {
  51224. throw new Error('You must implement this method');
  51225. };
  51226. EasingFunction.prototype.ease = function (gradient) {
  51227. switch (this._easingMode) {
  51228. case EasingFunction.EASINGMODE_EASEIN:
  51229. return this.easeInCore(gradient);
  51230. case EasingFunction.EASINGMODE_EASEOUT:
  51231. return (1 - this.easeInCore(1 - gradient));
  51232. }
  51233. if (gradient >= 0.5) {
  51234. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51235. }
  51236. return (this.easeInCore(gradient * 2) * 0.5);
  51237. };
  51238. //Statics
  51239. EasingFunction._EASINGMODE_EASEIN = 0;
  51240. EasingFunction._EASINGMODE_EASEOUT = 1;
  51241. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51242. return EasingFunction;
  51243. }());
  51244. BABYLON.EasingFunction = EasingFunction;
  51245. var CircleEase = /** @class */ (function (_super) {
  51246. __extends(CircleEase, _super);
  51247. function CircleEase() {
  51248. return _super !== null && _super.apply(this, arguments) || this;
  51249. }
  51250. CircleEase.prototype.easeInCore = function (gradient) {
  51251. gradient = Math.max(0, Math.min(1, gradient));
  51252. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51253. };
  51254. return CircleEase;
  51255. }(EasingFunction));
  51256. BABYLON.CircleEase = CircleEase;
  51257. var BackEase = /** @class */ (function (_super) {
  51258. __extends(BackEase, _super);
  51259. function BackEase(amplitude) {
  51260. if (amplitude === void 0) { amplitude = 1; }
  51261. var _this = _super.call(this) || this;
  51262. _this.amplitude = amplitude;
  51263. return _this;
  51264. }
  51265. BackEase.prototype.easeInCore = function (gradient) {
  51266. var num = Math.max(0, this.amplitude);
  51267. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51268. };
  51269. return BackEase;
  51270. }(EasingFunction));
  51271. BABYLON.BackEase = BackEase;
  51272. var BounceEase = /** @class */ (function (_super) {
  51273. __extends(BounceEase, _super);
  51274. function BounceEase(bounces, bounciness) {
  51275. if (bounces === void 0) { bounces = 3; }
  51276. if (bounciness === void 0) { bounciness = 2; }
  51277. var _this = _super.call(this) || this;
  51278. _this.bounces = bounces;
  51279. _this.bounciness = bounciness;
  51280. return _this;
  51281. }
  51282. BounceEase.prototype.easeInCore = function (gradient) {
  51283. var y = Math.max(0.0, this.bounces);
  51284. var bounciness = this.bounciness;
  51285. if (bounciness <= 1.0) {
  51286. bounciness = 1.001;
  51287. }
  51288. var num9 = Math.pow(bounciness, y);
  51289. var num5 = 1.0 - bounciness;
  51290. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51291. var num15 = gradient * num4;
  51292. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51293. var num3 = Math.floor(num65);
  51294. var num13 = num3 + 1.0;
  51295. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51296. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51297. var num7 = (num8 + num12) * 0.5;
  51298. var num6 = gradient - num7;
  51299. var num2 = num7 - num8;
  51300. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51301. };
  51302. return BounceEase;
  51303. }(EasingFunction));
  51304. BABYLON.BounceEase = BounceEase;
  51305. var CubicEase = /** @class */ (function (_super) {
  51306. __extends(CubicEase, _super);
  51307. function CubicEase() {
  51308. return _super !== null && _super.apply(this, arguments) || this;
  51309. }
  51310. CubicEase.prototype.easeInCore = function (gradient) {
  51311. return (gradient * gradient * gradient);
  51312. };
  51313. return CubicEase;
  51314. }(EasingFunction));
  51315. BABYLON.CubicEase = CubicEase;
  51316. var ElasticEase = /** @class */ (function (_super) {
  51317. __extends(ElasticEase, _super);
  51318. function ElasticEase(oscillations, springiness) {
  51319. if (oscillations === void 0) { oscillations = 3; }
  51320. if (springiness === void 0) { springiness = 3; }
  51321. var _this = _super.call(this) || this;
  51322. _this.oscillations = oscillations;
  51323. _this.springiness = springiness;
  51324. return _this;
  51325. }
  51326. ElasticEase.prototype.easeInCore = function (gradient) {
  51327. var num2;
  51328. var num3 = Math.max(0.0, this.oscillations);
  51329. var num = Math.max(0.0, this.springiness);
  51330. if (num == 0) {
  51331. num2 = gradient;
  51332. }
  51333. else {
  51334. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51335. }
  51336. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51337. };
  51338. return ElasticEase;
  51339. }(EasingFunction));
  51340. BABYLON.ElasticEase = ElasticEase;
  51341. var ExponentialEase = /** @class */ (function (_super) {
  51342. __extends(ExponentialEase, _super);
  51343. function ExponentialEase(exponent) {
  51344. if (exponent === void 0) { exponent = 2; }
  51345. var _this = _super.call(this) || this;
  51346. _this.exponent = exponent;
  51347. return _this;
  51348. }
  51349. ExponentialEase.prototype.easeInCore = function (gradient) {
  51350. if (this.exponent <= 0) {
  51351. return gradient;
  51352. }
  51353. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51354. };
  51355. return ExponentialEase;
  51356. }(EasingFunction));
  51357. BABYLON.ExponentialEase = ExponentialEase;
  51358. var PowerEase = /** @class */ (function (_super) {
  51359. __extends(PowerEase, _super);
  51360. function PowerEase(power) {
  51361. if (power === void 0) { power = 2; }
  51362. var _this = _super.call(this) || this;
  51363. _this.power = power;
  51364. return _this;
  51365. }
  51366. PowerEase.prototype.easeInCore = function (gradient) {
  51367. var y = Math.max(0.0, this.power);
  51368. return Math.pow(gradient, y);
  51369. };
  51370. return PowerEase;
  51371. }(EasingFunction));
  51372. BABYLON.PowerEase = PowerEase;
  51373. var QuadraticEase = /** @class */ (function (_super) {
  51374. __extends(QuadraticEase, _super);
  51375. function QuadraticEase() {
  51376. return _super !== null && _super.apply(this, arguments) || this;
  51377. }
  51378. QuadraticEase.prototype.easeInCore = function (gradient) {
  51379. return (gradient * gradient);
  51380. };
  51381. return QuadraticEase;
  51382. }(EasingFunction));
  51383. BABYLON.QuadraticEase = QuadraticEase;
  51384. var QuarticEase = /** @class */ (function (_super) {
  51385. __extends(QuarticEase, _super);
  51386. function QuarticEase() {
  51387. return _super !== null && _super.apply(this, arguments) || this;
  51388. }
  51389. QuarticEase.prototype.easeInCore = function (gradient) {
  51390. return (gradient * gradient * gradient * gradient);
  51391. };
  51392. return QuarticEase;
  51393. }(EasingFunction));
  51394. BABYLON.QuarticEase = QuarticEase;
  51395. var QuinticEase = /** @class */ (function (_super) {
  51396. __extends(QuinticEase, _super);
  51397. function QuinticEase() {
  51398. return _super !== null && _super.apply(this, arguments) || this;
  51399. }
  51400. QuinticEase.prototype.easeInCore = function (gradient) {
  51401. return (gradient * gradient * gradient * gradient * gradient);
  51402. };
  51403. return QuinticEase;
  51404. }(EasingFunction));
  51405. BABYLON.QuinticEase = QuinticEase;
  51406. var SineEase = /** @class */ (function (_super) {
  51407. __extends(SineEase, _super);
  51408. function SineEase() {
  51409. return _super !== null && _super.apply(this, arguments) || this;
  51410. }
  51411. SineEase.prototype.easeInCore = function (gradient) {
  51412. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51413. };
  51414. return SineEase;
  51415. }(EasingFunction));
  51416. BABYLON.SineEase = SineEase;
  51417. var BezierCurveEase = /** @class */ (function (_super) {
  51418. __extends(BezierCurveEase, _super);
  51419. function BezierCurveEase(x1, y1, x2, y2) {
  51420. if (x1 === void 0) { x1 = 0; }
  51421. if (y1 === void 0) { y1 = 0; }
  51422. if (x2 === void 0) { x2 = 1; }
  51423. if (y2 === void 0) { y2 = 1; }
  51424. var _this = _super.call(this) || this;
  51425. _this.x1 = x1;
  51426. _this.y1 = y1;
  51427. _this.x2 = x2;
  51428. _this.y2 = y2;
  51429. return _this;
  51430. }
  51431. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51432. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51433. };
  51434. return BezierCurveEase;
  51435. }(EasingFunction));
  51436. BABYLON.BezierCurveEase = BezierCurveEase;
  51437. })(BABYLON || (BABYLON = {}));
  51438. //# sourceMappingURL=babylon.easing.js.map
  51439. "use strict";
  51440. var BABYLON;
  51441. (function (BABYLON) {
  51442. /**
  51443. * A Condition applied to an Action
  51444. */
  51445. var Condition = /** @class */ (function () {
  51446. /**
  51447. * Creates a new Condition
  51448. * @param actionManager the manager of the action the condition is applied to
  51449. */
  51450. function Condition(actionManager) {
  51451. this._actionManager = actionManager;
  51452. }
  51453. /**
  51454. * Check if the current condition is valid
  51455. * @returns a boolean
  51456. */
  51457. Condition.prototype.isValid = function () {
  51458. return true;
  51459. };
  51460. /**
  51461. * Internal only
  51462. * @ignore
  51463. */
  51464. Condition.prototype._getProperty = function (propertyPath) {
  51465. return this._actionManager._getProperty(propertyPath);
  51466. };
  51467. /**
  51468. * Internal only
  51469. * @ignore
  51470. */
  51471. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51472. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51473. };
  51474. /**
  51475. * Serialize placeholder for child classes
  51476. * @returns the serialized object
  51477. */
  51478. Condition.prototype.serialize = function () {
  51479. };
  51480. /**
  51481. * Internal only
  51482. * @ignore
  51483. */
  51484. Condition.prototype._serialize = function (serializedCondition) {
  51485. return {
  51486. type: 2,
  51487. children: [],
  51488. name: serializedCondition.name,
  51489. properties: serializedCondition.properties
  51490. };
  51491. };
  51492. return Condition;
  51493. }());
  51494. BABYLON.Condition = Condition;
  51495. /**
  51496. * Defines specific conditional operators as extensions of Condition
  51497. */
  51498. var ValueCondition = /** @class */ (function (_super) {
  51499. __extends(ValueCondition, _super);
  51500. /**
  51501. * Creates a new ValueCondition
  51502. * @param actionManager manager for the action the condition applies to
  51503. * @param target for the action
  51504. * @param propertyPath path to specify the property of the target the conditional operator uses
  51505. * @param value the vale compared by the conditional operator against the current value of the property
  51506. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  51507. */
  51508. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  51509. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51510. var _this = _super.call(this, actionManager) || this;
  51511. _this.propertyPath = propertyPath;
  51512. _this.value = value;
  51513. _this.operator = operator;
  51514. _this._target = target;
  51515. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51516. _this._property = _this._getProperty(_this.propertyPath);
  51517. return _this;
  51518. }
  51519. Object.defineProperty(ValueCondition, "IsEqual", {
  51520. /**
  51521. * returns the number for IsEqual
  51522. */
  51523. get: function () {
  51524. return ValueCondition._IsEqual;
  51525. },
  51526. enumerable: true,
  51527. configurable: true
  51528. });
  51529. Object.defineProperty(ValueCondition, "IsDifferent", {
  51530. /**
  51531. * Returns the number for IsDifferent
  51532. */
  51533. get: function () {
  51534. return ValueCondition._IsDifferent;
  51535. },
  51536. enumerable: true,
  51537. configurable: true
  51538. });
  51539. Object.defineProperty(ValueCondition, "IsGreater", {
  51540. /**
  51541. * Returns the number for IsGreater
  51542. */
  51543. get: function () {
  51544. return ValueCondition._IsGreater;
  51545. },
  51546. enumerable: true,
  51547. configurable: true
  51548. });
  51549. Object.defineProperty(ValueCondition, "IsLesser", {
  51550. /**
  51551. * Returns the number for IsLesser
  51552. */
  51553. get: function () {
  51554. return ValueCondition._IsLesser;
  51555. },
  51556. enumerable: true,
  51557. configurable: true
  51558. });
  51559. /**
  51560. * Compares the given value with the property value for the specified conditional operator
  51561. * @returns the result of the comparison
  51562. */
  51563. ValueCondition.prototype.isValid = function () {
  51564. switch (this.operator) {
  51565. case ValueCondition.IsGreater:
  51566. return this._effectiveTarget[this._property] > this.value;
  51567. case ValueCondition.IsLesser:
  51568. return this._effectiveTarget[this._property] < this.value;
  51569. case ValueCondition.IsEqual:
  51570. case ValueCondition.IsDifferent:
  51571. var check;
  51572. if (this.value.equals) {
  51573. check = this.value.equals(this._effectiveTarget[this._property]);
  51574. }
  51575. else {
  51576. check = this.value === this._effectiveTarget[this._property];
  51577. }
  51578. return this.operator === ValueCondition.IsEqual ? check : !check;
  51579. }
  51580. return false;
  51581. };
  51582. /**
  51583. * Serialize the ValueCondition into a JSON compatible object
  51584. * @returns serialization object
  51585. */
  51586. ValueCondition.prototype.serialize = function () {
  51587. return this._serialize({
  51588. name: "ValueCondition",
  51589. properties: [
  51590. BABYLON.Action._GetTargetProperty(this._target),
  51591. { name: "propertyPath", value: this.propertyPath },
  51592. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51593. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51594. ]
  51595. });
  51596. };
  51597. /**
  51598. * Gets the name of the conditional operator for the ValueCondition
  51599. * @param operator the conditional operator
  51600. * @returns the name
  51601. */
  51602. ValueCondition.GetOperatorName = function (operator) {
  51603. switch (operator) {
  51604. case ValueCondition._IsEqual: return "IsEqual";
  51605. case ValueCondition._IsDifferent: return "IsDifferent";
  51606. case ValueCondition._IsGreater: return "IsGreater";
  51607. case ValueCondition._IsLesser: return "IsLesser";
  51608. default: return "";
  51609. }
  51610. };
  51611. /**
  51612. * Internal only
  51613. * @ignore
  51614. */
  51615. ValueCondition._IsEqual = 0;
  51616. /**
  51617. * Internal only
  51618. * @ignore
  51619. */
  51620. ValueCondition._IsDifferent = 1;
  51621. /**
  51622. * Internal only
  51623. * @ignore
  51624. */
  51625. ValueCondition._IsGreater = 2;
  51626. /**
  51627. * Internal only
  51628. * @ignore
  51629. */
  51630. ValueCondition._IsLesser = 3;
  51631. return ValueCondition;
  51632. }(Condition));
  51633. BABYLON.ValueCondition = ValueCondition;
  51634. /**
  51635. * Defines a predicate condition as an extension of Condition
  51636. */
  51637. var PredicateCondition = /** @class */ (function (_super) {
  51638. __extends(PredicateCondition, _super);
  51639. /**
  51640. * Creates a new {BABYLON.PredicateCondition}
  51641. * @param actionManager manager for the action the condition applies to
  51642. * @param predicate
  51643. */
  51644. function PredicateCondition(actionManager, predicate) {
  51645. var _this = _super.call(this, actionManager) || this;
  51646. _this.predicate = predicate;
  51647. return _this;
  51648. }
  51649. /**
  51650. * @returns the validity of the predicate condition
  51651. */
  51652. PredicateCondition.prototype.isValid = function () {
  51653. return this.predicate();
  51654. };
  51655. return PredicateCondition;
  51656. }(Condition));
  51657. BABYLON.PredicateCondition = PredicateCondition;
  51658. /**
  51659. * Defines a state condition as an extension of {BABYLON.Condition}
  51660. */
  51661. var StateCondition = /** @class */ (function (_super) {
  51662. __extends(StateCondition, _super);
  51663. /**
  51664. * Creates a new {BABYLON.StateCondition}
  51665. * @param actionManager manager for the action the condition applies to
  51666. * @param target of the condition
  51667. * @param value to compare with target state
  51668. */
  51669. function StateCondition(actionManager, target, value) {
  51670. var _this = _super.call(this, actionManager) || this;
  51671. _this.value = value;
  51672. _this._target = target;
  51673. return _this;
  51674. }
  51675. /**
  51676. * @returns the validity of the state
  51677. */
  51678. StateCondition.prototype.isValid = function () {
  51679. return this._target.state === this.value;
  51680. };
  51681. /**
  51682. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  51683. * @returns serialization object
  51684. */
  51685. StateCondition.prototype.serialize = function () {
  51686. return this._serialize({
  51687. name: "StateCondition",
  51688. properties: [
  51689. BABYLON.Action._GetTargetProperty(this._target),
  51690. { name: "value", value: this.value }
  51691. ]
  51692. });
  51693. };
  51694. return StateCondition;
  51695. }(Condition));
  51696. BABYLON.StateCondition = StateCondition;
  51697. })(BABYLON || (BABYLON = {}));
  51698. //# sourceMappingURL=babylon.condition.js.map
  51699. "use strict";
  51700. var BABYLON;
  51701. (function (BABYLON) {
  51702. /**
  51703. * The action to be carried out following a trigger
  51704. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51705. */
  51706. var Action = /** @class */ (function () {
  51707. /**
  51708. * Creates a new Action
  51709. * @param triggerOptions the trigger, with or without parameters, for the action
  51710. * @param condition an optional determinant of action
  51711. */
  51712. function Action(triggerOptions, condition) {
  51713. this.triggerOptions = triggerOptions;
  51714. /**
  51715. * An event triggered prior to action being executed.
  51716. */
  51717. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51718. if (triggerOptions.parameter) {
  51719. this.trigger = triggerOptions.trigger;
  51720. this._triggerParameter = triggerOptions.parameter;
  51721. }
  51722. else {
  51723. this.trigger = triggerOptions;
  51724. }
  51725. this._nextActiveAction = this;
  51726. this._condition = condition;
  51727. }
  51728. /**
  51729. * Internal only
  51730. * @ignore
  51731. */
  51732. Action.prototype._prepare = function () {
  51733. };
  51734. /**
  51735. * Gets the trigger parameters
  51736. * @returns the trigger parameters
  51737. */
  51738. Action.prototype.getTriggerParameter = function () {
  51739. return this._triggerParameter;
  51740. };
  51741. /**
  51742. * Internal only - executes current action event
  51743. * @ignore
  51744. */
  51745. Action.prototype._executeCurrent = function (evt) {
  51746. if (this._nextActiveAction._condition) {
  51747. var condition = this._nextActiveAction._condition;
  51748. var currentRenderId = this._actionManager.getScene().getRenderId();
  51749. // We cache the current evaluation for the current frame
  51750. if (condition._evaluationId === currentRenderId) {
  51751. if (!condition._currentResult) {
  51752. return;
  51753. }
  51754. }
  51755. else {
  51756. condition._evaluationId = currentRenderId;
  51757. if (!condition.isValid()) {
  51758. condition._currentResult = false;
  51759. return;
  51760. }
  51761. condition._currentResult = true;
  51762. }
  51763. }
  51764. this.onBeforeExecuteObservable.notifyObservers(this);
  51765. this._nextActiveAction.execute(evt);
  51766. this.skipToNextActiveAction();
  51767. };
  51768. /**
  51769. * Execute placeholder for child classes
  51770. * @param evt optional action event
  51771. */
  51772. Action.prototype.execute = function (evt) {
  51773. };
  51774. /**
  51775. * Skips to next active action
  51776. */
  51777. Action.prototype.skipToNextActiveAction = function () {
  51778. if (this._nextActiveAction._child) {
  51779. if (!this._nextActiveAction._child._actionManager) {
  51780. this._nextActiveAction._child._actionManager = this._actionManager;
  51781. }
  51782. this._nextActiveAction = this._nextActiveAction._child;
  51783. }
  51784. else {
  51785. this._nextActiveAction = this;
  51786. }
  51787. };
  51788. /**
  51789. * Adds action to chain of actions, may be a DoNothingAction
  51790. * @param index The index of the attribute.
  51791. * @returns The action passed in
  51792. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51793. */
  51794. Action.prototype.then = function (action) {
  51795. this._child = action;
  51796. action._actionManager = this._actionManager;
  51797. action._prepare();
  51798. return action;
  51799. };
  51800. /**
  51801. * Internal only
  51802. * @ignore
  51803. */
  51804. Action.prototype._getProperty = function (propertyPath) {
  51805. return this._actionManager._getProperty(propertyPath);
  51806. };
  51807. /**
  51808. * Internal only
  51809. * @ignore
  51810. */
  51811. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51812. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51813. };
  51814. /**
  51815. * Serialize placeholder for child classes
  51816. * @param parent of child
  51817. * @returns the serialized object
  51818. */
  51819. Action.prototype.serialize = function (parent) {
  51820. };
  51821. /**
  51822. * Internal only called by serialize
  51823. * @ignore
  51824. */
  51825. Action.prototype._serialize = function (serializedAction, parent) {
  51826. var serializationObject = {
  51827. type: 1,
  51828. children: [],
  51829. name: serializedAction.name,
  51830. properties: serializedAction.properties || []
  51831. };
  51832. // Serialize child
  51833. if (this._child) {
  51834. this._child.serialize(serializationObject);
  51835. }
  51836. // Check if "this" has a condition
  51837. if (this._condition) {
  51838. var serializedCondition = this._condition.serialize();
  51839. serializedCondition.children.push(serializationObject);
  51840. if (parent) {
  51841. parent.children.push(serializedCondition);
  51842. }
  51843. return serializedCondition;
  51844. }
  51845. if (parent) {
  51846. parent.children.push(serializationObject);
  51847. }
  51848. return serializationObject;
  51849. };
  51850. /**
  51851. * Internal only
  51852. * @ignore
  51853. */
  51854. Action._SerializeValueAsString = function (value) {
  51855. if (typeof value === "number") {
  51856. return value.toString();
  51857. }
  51858. if (typeof value === "boolean") {
  51859. return value ? "true" : "false";
  51860. }
  51861. if (value instanceof BABYLON.Vector2) {
  51862. return value.x + ", " + value.y;
  51863. }
  51864. if (value instanceof BABYLON.Vector3) {
  51865. return value.x + ", " + value.y + ", " + value.z;
  51866. }
  51867. if (value instanceof BABYLON.Color3) {
  51868. return value.r + ", " + value.g + ", " + value.b;
  51869. }
  51870. if (value instanceof BABYLON.Color4) {
  51871. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51872. }
  51873. return value; // string
  51874. };
  51875. /**
  51876. * Internal only
  51877. * @ignore
  51878. */
  51879. Action._GetTargetProperty = function (target) {
  51880. return {
  51881. name: "target",
  51882. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51883. : target instanceof BABYLON.Light ? "LightProperties"
  51884. : target instanceof BABYLON.Camera ? "CameraProperties"
  51885. : "SceneProperties",
  51886. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51887. };
  51888. };
  51889. return Action;
  51890. }());
  51891. BABYLON.Action = Action;
  51892. })(BABYLON || (BABYLON = {}));
  51893. //# sourceMappingURL=babylon.action.js.map
  51894. "use strict";
  51895. var BABYLON;
  51896. (function (BABYLON) {
  51897. /**
  51898. * ActionEvent is the event being sent when an action is triggered.
  51899. */
  51900. var ActionEvent = /** @class */ (function () {
  51901. /**
  51902. * @param source The mesh or sprite that triggered the action.
  51903. * @param pointerX The X mouse cursor position at the time of the event
  51904. * @param pointerY The Y mouse cursor position at the time of the event
  51905. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51906. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51907. */
  51908. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  51909. this.source = source;
  51910. this.pointerX = pointerX;
  51911. this.pointerY = pointerY;
  51912. this.meshUnderPointer = meshUnderPointer;
  51913. this.sourceEvent = sourceEvent;
  51914. this.additionalData = additionalData;
  51915. }
  51916. /**
  51917. * Helper function to auto-create an ActionEvent from a source mesh.
  51918. * @param source The source mesh that triggered the event
  51919. * @param evt {Event} The original (browser) event
  51920. */
  51921. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51922. var scene = source.getScene();
  51923. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51924. };
  51925. /**
  51926. * Helper function to auto-create an ActionEvent from a source mesh.
  51927. * @param source The source sprite that triggered the event
  51928. * @param scene Scene associated with the sprite
  51929. * @param evt {Event} The original (browser) event
  51930. */
  51931. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51932. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51933. };
  51934. /**
  51935. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51936. * @param scene the scene where the event occurred
  51937. * @param evt {Event} The original (browser) event
  51938. */
  51939. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51940. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51941. };
  51942. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51943. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51944. };
  51945. return ActionEvent;
  51946. }());
  51947. BABYLON.ActionEvent = ActionEvent;
  51948. /**
  51949. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51950. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51951. */
  51952. var ActionManager = /** @class */ (function () {
  51953. function ActionManager(scene) {
  51954. // Members
  51955. this.actions = new Array();
  51956. this.hoverCursor = '';
  51957. this._scene = scene;
  51958. scene._actionManagers.push(this);
  51959. }
  51960. Object.defineProperty(ActionManager, "NothingTrigger", {
  51961. get: function () {
  51962. return ActionManager._NothingTrigger;
  51963. },
  51964. enumerable: true,
  51965. configurable: true
  51966. });
  51967. Object.defineProperty(ActionManager, "OnPickTrigger", {
  51968. get: function () {
  51969. return ActionManager._OnPickTrigger;
  51970. },
  51971. enumerable: true,
  51972. configurable: true
  51973. });
  51974. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  51975. get: function () {
  51976. return ActionManager._OnLeftPickTrigger;
  51977. },
  51978. enumerable: true,
  51979. configurable: true
  51980. });
  51981. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  51982. get: function () {
  51983. return ActionManager._OnRightPickTrigger;
  51984. },
  51985. enumerable: true,
  51986. configurable: true
  51987. });
  51988. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  51989. get: function () {
  51990. return ActionManager._OnCenterPickTrigger;
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  51996. get: function () {
  51997. return ActionManager._OnPickDownTrigger;
  51998. },
  51999. enumerable: true,
  52000. configurable: true
  52001. });
  52002. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52003. get: function () {
  52004. return ActionManager._OnDoublePickTrigger;
  52005. },
  52006. enumerable: true,
  52007. configurable: true
  52008. });
  52009. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52010. get: function () {
  52011. return ActionManager._OnPickUpTrigger;
  52012. },
  52013. enumerable: true,
  52014. configurable: true
  52015. });
  52016. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52017. /// This trigger will only be raised if you also declared a OnPickDown
  52018. get: function () {
  52019. return ActionManager._OnPickOutTrigger;
  52020. },
  52021. enumerable: true,
  52022. configurable: true
  52023. });
  52024. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52025. get: function () {
  52026. return ActionManager._OnLongPressTrigger;
  52027. },
  52028. enumerable: true,
  52029. configurable: true
  52030. });
  52031. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52032. get: function () {
  52033. return ActionManager._OnPointerOverTrigger;
  52034. },
  52035. enumerable: true,
  52036. configurable: true
  52037. });
  52038. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52039. get: function () {
  52040. return ActionManager._OnPointerOutTrigger;
  52041. },
  52042. enumerable: true,
  52043. configurable: true
  52044. });
  52045. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52046. get: function () {
  52047. return ActionManager._OnEveryFrameTrigger;
  52048. },
  52049. enumerable: true,
  52050. configurable: true
  52051. });
  52052. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52053. get: function () {
  52054. return ActionManager._OnIntersectionEnterTrigger;
  52055. },
  52056. enumerable: true,
  52057. configurable: true
  52058. });
  52059. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52060. get: function () {
  52061. return ActionManager._OnIntersectionExitTrigger;
  52062. },
  52063. enumerable: true,
  52064. configurable: true
  52065. });
  52066. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52067. get: function () {
  52068. return ActionManager._OnKeyDownTrigger;
  52069. },
  52070. enumerable: true,
  52071. configurable: true
  52072. });
  52073. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52074. get: function () {
  52075. return ActionManager._OnKeyUpTrigger;
  52076. },
  52077. enumerable: true,
  52078. configurable: true
  52079. });
  52080. // Methods
  52081. ActionManager.prototype.dispose = function () {
  52082. var index = this._scene._actionManagers.indexOf(this);
  52083. for (var i = 0; i < this.actions.length; i++) {
  52084. var action = this.actions[i];
  52085. ActionManager.Triggers[action.trigger]--;
  52086. if (ActionManager.Triggers[action.trigger] === 0) {
  52087. delete ActionManager.Triggers[action.trigger];
  52088. }
  52089. }
  52090. if (index > -1) {
  52091. this._scene._actionManagers.splice(index, 1);
  52092. }
  52093. };
  52094. ActionManager.prototype.getScene = function () {
  52095. return this._scene;
  52096. };
  52097. /**
  52098. * Does this action manager handles actions of any of the given triggers
  52099. * @param {number[]} triggers - the triggers to be tested
  52100. * @return {boolean} whether one (or more) of the triggers is handeled
  52101. */
  52102. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52103. for (var index = 0; index < this.actions.length; index++) {
  52104. var action = this.actions[index];
  52105. if (triggers.indexOf(action.trigger) > -1) {
  52106. return true;
  52107. }
  52108. }
  52109. return false;
  52110. };
  52111. /**
  52112. * Does this action manager handles actions of a given trigger
  52113. * @param trigger defines the trigger to be tested
  52114. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52115. * @return whether the trigger is handled
  52116. */
  52117. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52118. for (var index = 0; index < this.actions.length; index++) {
  52119. var action = this.actions[index];
  52120. if (action.trigger === trigger) {
  52121. if (parameterPredicate) {
  52122. if (parameterPredicate(action.getTriggerParameter())) {
  52123. return true;
  52124. }
  52125. }
  52126. else {
  52127. return true;
  52128. }
  52129. }
  52130. }
  52131. return false;
  52132. };
  52133. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52134. /**
  52135. * Does this action manager has pointer triggers
  52136. * @return {boolean} whether or not it has pointer triggers
  52137. */
  52138. get: function () {
  52139. for (var index = 0; index < this.actions.length; index++) {
  52140. var action = this.actions[index];
  52141. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52142. return true;
  52143. }
  52144. }
  52145. return false;
  52146. },
  52147. enumerable: true,
  52148. configurable: true
  52149. });
  52150. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52151. /**
  52152. * Does this action manager has pick triggers
  52153. * @return {boolean} whether or not it has pick triggers
  52154. */
  52155. get: function () {
  52156. for (var index = 0; index < this.actions.length; index++) {
  52157. var action = this.actions[index];
  52158. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52159. return true;
  52160. }
  52161. }
  52162. return false;
  52163. },
  52164. enumerable: true,
  52165. configurable: true
  52166. });
  52167. Object.defineProperty(ActionManager, "HasTriggers", {
  52168. /**
  52169. * Does exist one action manager with at least one trigger
  52170. * @return {boolean} whether or not it exists one action manager with one trigger
  52171. **/
  52172. get: function () {
  52173. for (var t in ActionManager.Triggers) {
  52174. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52175. return true;
  52176. }
  52177. }
  52178. return false;
  52179. },
  52180. enumerable: true,
  52181. configurable: true
  52182. });
  52183. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52184. /**
  52185. * Does exist one action manager with at least one pick trigger
  52186. * @return {boolean} whether or not it exists one action manager with one pick trigger
  52187. **/
  52188. get: function () {
  52189. for (var t in ActionManager.Triggers) {
  52190. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52191. var t_int = parseInt(t);
  52192. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52193. return true;
  52194. }
  52195. }
  52196. }
  52197. return false;
  52198. },
  52199. enumerable: true,
  52200. configurable: true
  52201. });
  52202. /**
  52203. * Does exist one action manager that handles actions of a given trigger
  52204. * @param {number} trigger - the trigger to be tested
  52205. * @return {boolean} whether the trigger is handeled by at least one action manager
  52206. **/
  52207. ActionManager.HasSpecificTrigger = function (trigger) {
  52208. for (var t in ActionManager.Triggers) {
  52209. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52210. var t_int = parseInt(t);
  52211. if (t_int === trigger) {
  52212. return true;
  52213. }
  52214. }
  52215. }
  52216. return false;
  52217. };
  52218. /**
  52219. * Registers an action to this action manager
  52220. * @param {BABYLON.Action} action - the action to be registered
  52221. * @return {BABYLON.Action} the action amended (prepared) after registration
  52222. */
  52223. ActionManager.prototype.registerAction = function (action) {
  52224. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52225. if (this.getScene().actionManager !== this) {
  52226. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52227. return null;
  52228. }
  52229. }
  52230. this.actions.push(action);
  52231. if (ActionManager.Triggers[action.trigger]) {
  52232. ActionManager.Triggers[action.trigger]++;
  52233. }
  52234. else {
  52235. ActionManager.Triggers[action.trigger] = 1;
  52236. }
  52237. action._actionManager = this;
  52238. action._prepare();
  52239. return action;
  52240. };
  52241. /**
  52242. * Unregisters an action to this action manager
  52243. * @param action The action to be unregistered
  52244. * @return whether the action has been unregistered
  52245. */
  52246. ActionManager.prototype.unregisterAction = function (action) {
  52247. var index = this.actions.indexOf(action);
  52248. if (index !== -1) {
  52249. this.actions.splice(index, 1);
  52250. ActionManager.Triggers[action.trigger] -= 1;
  52251. if (ActionManager.Triggers[action.trigger] === 0) {
  52252. delete ActionManager.Triggers[action.trigger];
  52253. }
  52254. delete action._actionManager;
  52255. return true;
  52256. }
  52257. return false;
  52258. };
  52259. /**
  52260. * Process a specific trigger
  52261. * @param {number} trigger - the trigger to process
  52262. * @param evt {BABYLON.ActionEvent} the event details to be processed
  52263. */
  52264. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52265. for (var index = 0; index < this.actions.length; index++) {
  52266. var action = this.actions[index];
  52267. if (action.trigger === trigger) {
  52268. if (evt) {
  52269. if (trigger === ActionManager.OnKeyUpTrigger
  52270. || trigger === ActionManager.OnKeyDownTrigger) {
  52271. var parameter = action.getTriggerParameter();
  52272. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52273. if (!parameter.toLowerCase) {
  52274. continue;
  52275. }
  52276. var lowerCase = parameter.toLowerCase();
  52277. if (lowerCase !== evt.sourceEvent.key) {
  52278. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52279. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52280. if (actualkey !== lowerCase) {
  52281. continue;
  52282. }
  52283. }
  52284. }
  52285. }
  52286. }
  52287. action._executeCurrent(evt);
  52288. }
  52289. }
  52290. };
  52291. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52292. var properties = propertyPath.split(".");
  52293. for (var index = 0; index < properties.length - 1; index++) {
  52294. target = target[properties[index]];
  52295. }
  52296. return target;
  52297. };
  52298. ActionManager.prototype._getProperty = function (propertyPath) {
  52299. var properties = propertyPath.split(".");
  52300. return properties[properties.length - 1];
  52301. };
  52302. ActionManager.prototype.serialize = function (name) {
  52303. var root = {
  52304. children: new Array(),
  52305. name: name,
  52306. type: 3,
  52307. properties: new Array() // Empty for root but required
  52308. };
  52309. for (var i = 0; i < this.actions.length; i++) {
  52310. var triggerObject = {
  52311. type: 0,
  52312. children: new Array(),
  52313. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52314. properties: new Array()
  52315. };
  52316. var triggerOptions = this.actions[i].triggerOptions;
  52317. if (triggerOptions && typeof triggerOptions !== "number") {
  52318. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52319. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52320. }
  52321. else {
  52322. var parameter = {};
  52323. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52324. if (triggerOptions.parameter.mesh) {
  52325. parameter._meshId = triggerOptions.parameter.mesh.id;
  52326. }
  52327. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52328. }
  52329. }
  52330. // Serialize child action, recursively
  52331. this.actions[i].serialize(triggerObject);
  52332. // Add serialized trigger
  52333. root.children.push(triggerObject);
  52334. }
  52335. return root;
  52336. };
  52337. ActionManager.Parse = function (parsedActions, object, scene) {
  52338. var actionManager = new ActionManager(scene);
  52339. if (object === null)
  52340. scene.actionManager = actionManager;
  52341. else
  52342. object.actionManager = actionManager;
  52343. // instanciate a new object
  52344. var instanciate = function (name, params) {
  52345. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52346. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52347. newInstance.constructor.apply(newInstance, params);
  52348. return newInstance;
  52349. };
  52350. var parseParameter = function (name, value, target, propertyPath) {
  52351. if (propertyPath === null) {
  52352. // String, boolean or float
  52353. var floatValue = parseFloat(value);
  52354. if (value === "true" || value === "false")
  52355. return value === "true";
  52356. else
  52357. return isNaN(floatValue) ? value : floatValue;
  52358. }
  52359. var effectiveTarget = propertyPath.split(".");
  52360. var values = value.split(",");
  52361. // Get effective Target
  52362. for (var i = 0; i < effectiveTarget.length; i++) {
  52363. target = target[effectiveTarget[i]];
  52364. }
  52365. // Return appropriate value with its type
  52366. if (typeof (target) === "boolean")
  52367. return values[0] === "true";
  52368. if (typeof (target) === "string")
  52369. return values[0];
  52370. // Parameters with multiple values such as Vector3 etc.
  52371. var split = new Array();
  52372. for (var i = 0; i < values.length; i++)
  52373. split.push(parseFloat(values[i]));
  52374. if (target instanceof BABYLON.Vector3)
  52375. return BABYLON.Vector3.FromArray(split);
  52376. if (target instanceof BABYLON.Vector4)
  52377. return BABYLON.Vector4.FromArray(split);
  52378. if (target instanceof BABYLON.Color3)
  52379. return BABYLON.Color3.FromArray(split);
  52380. if (target instanceof BABYLON.Color4)
  52381. return BABYLON.Color4.FromArray(split);
  52382. return parseFloat(values[0]);
  52383. };
  52384. // traverse graph per trigger
  52385. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52386. if (combineArray === void 0) { combineArray = null; }
  52387. if (parsedAction.detached)
  52388. return;
  52389. var parameters = new Array();
  52390. var target = null;
  52391. var propertyPath = null;
  52392. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52393. // Parameters
  52394. if (parsedAction.type === 2)
  52395. parameters.push(actionManager);
  52396. else
  52397. parameters.push(trigger);
  52398. if (combine) {
  52399. var actions = new Array();
  52400. for (var j = 0; j < parsedAction.combine.length; j++) {
  52401. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52402. }
  52403. parameters.push(actions);
  52404. }
  52405. else {
  52406. for (var i = 0; i < parsedAction.properties.length; i++) {
  52407. var value = parsedAction.properties[i].value;
  52408. var name = parsedAction.properties[i].name;
  52409. var targetType = parsedAction.properties[i].targetType;
  52410. if (name === "target")
  52411. if (targetType !== null && targetType === "SceneProperties")
  52412. value = target = scene;
  52413. else
  52414. value = target = scene.getNodeByName(value);
  52415. else if (name === "parent")
  52416. value = scene.getNodeByName(value);
  52417. else if (name === "sound")
  52418. value = scene.getSoundByName(value);
  52419. else if (name !== "propertyPath") {
  52420. if (parsedAction.type === 2 && name === "operator")
  52421. value = BABYLON.ValueCondition[value];
  52422. else
  52423. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52424. }
  52425. else {
  52426. propertyPath = value;
  52427. }
  52428. parameters.push(value);
  52429. }
  52430. }
  52431. if (combineArray === null) {
  52432. parameters.push(condition);
  52433. }
  52434. else {
  52435. parameters.push(null);
  52436. }
  52437. // If interpolate value action
  52438. if (parsedAction.name === "InterpolateValueAction") {
  52439. var param = parameters[parameters.length - 2];
  52440. parameters[parameters.length - 1] = param;
  52441. parameters[parameters.length - 2] = condition;
  52442. }
  52443. // Action or condition(s) and not CombineAction
  52444. var newAction = instanciate(parsedAction.name, parameters);
  52445. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52446. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52447. if (action)
  52448. action.then(nothing);
  52449. else
  52450. actionManager.registerAction(nothing);
  52451. action = nothing;
  52452. }
  52453. if (combineArray === null) {
  52454. if (newAction instanceof BABYLON.Condition) {
  52455. condition = newAction;
  52456. newAction = action;
  52457. }
  52458. else {
  52459. condition = null;
  52460. if (action)
  52461. action.then(newAction);
  52462. else
  52463. actionManager.registerAction(newAction);
  52464. }
  52465. }
  52466. else {
  52467. combineArray.push(newAction);
  52468. }
  52469. for (var i = 0; i < parsedAction.children.length; i++)
  52470. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52471. };
  52472. // triggers
  52473. for (var i = 0; i < parsedActions.children.length; i++) {
  52474. var triggerParams;
  52475. var trigger = parsedActions.children[i];
  52476. if (trigger.properties.length > 0) {
  52477. var param = trigger.properties[0].value;
  52478. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52479. if (value._meshId) {
  52480. value.mesh = scene.getMeshByID(value._meshId);
  52481. }
  52482. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52483. }
  52484. else
  52485. triggerParams = ActionManager[trigger.name];
  52486. for (var j = 0; j < trigger.children.length; j++) {
  52487. if (!trigger.detached)
  52488. traverse(trigger.children[j], triggerParams, null, null);
  52489. }
  52490. }
  52491. };
  52492. ActionManager.GetTriggerName = function (trigger) {
  52493. switch (trigger) {
  52494. case 0: return "NothingTrigger";
  52495. case 1: return "OnPickTrigger";
  52496. case 2: return "OnLeftPickTrigger";
  52497. case 3: return "OnRightPickTrigger";
  52498. case 4: return "OnCenterPickTrigger";
  52499. case 5: return "OnPickDownTrigger";
  52500. case 6: return "OnPickUpTrigger";
  52501. case 7: return "OnLongPressTrigger";
  52502. case 8: return "OnPointerOverTrigger";
  52503. case 9: return "OnPointerOutTrigger";
  52504. case 10: return "OnEveryFrameTrigger";
  52505. case 11: return "OnIntersectionEnterTrigger";
  52506. case 12: return "OnIntersectionExitTrigger";
  52507. case 13: return "OnKeyDownTrigger";
  52508. case 14: return "OnKeyUpTrigger";
  52509. case 15: return "OnPickOutTrigger";
  52510. default: return "";
  52511. }
  52512. };
  52513. // Statics
  52514. ActionManager._NothingTrigger = 0;
  52515. ActionManager._OnPickTrigger = 1;
  52516. ActionManager._OnLeftPickTrigger = 2;
  52517. ActionManager._OnRightPickTrigger = 3;
  52518. ActionManager._OnCenterPickTrigger = 4;
  52519. ActionManager._OnPickDownTrigger = 5;
  52520. ActionManager._OnDoublePickTrigger = 6;
  52521. ActionManager._OnPickUpTrigger = 7;
  52522. ActionManager._OnLongPressTrigger = 8;
  52523. ActionManager._OnPointerOverTrigger = 9;
  52524. ActionManager._OnPointerOutTrigger = 10;
  52525. ActionManager._OnEveryFrameTrigger = 11;
  52526. ActionManager._OnIntersectionEnterTrigger = 12;
  52527. ActionManager._OnIntersectionExitTrigger = 13;
  52528. ActionManager._OnKeyDownTrigger = 14;
  52529. ActionManager._OnKeyUpTrigger = 15;
  52530. ActionManager._OnPickOutTrigger = 16;
  52531. ActionManager.Triggers = {};
  52532. return ActionManager;
  52533. }());
  52534. BABYLON.ActionManager = ActionManager;
  52535. })(BABYLON || (BABYLON = {}));
  52536. //# sourceMappingURL=babylon.actionManager.js.map
  52537. "use strict";
  52538. var BABYLON;
  52539. (function (BABYLON) {
  52540. var InterpolateValueAction = /** @class */ (function (_super) {
  52541. __extends(InterpolateValueAction, _super);
  52542. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52543. if (duration === void 0) { duration = 1000; }
  52544. var _this = _super.call(this, triggerOptions, condition) || this;
  52545. _this.propertyPath = propertyPath;
  52546. _this.value = value;
  52547. _this.duration = duration;
  52548. _this.stopOtherAnimations = stopOtherAnimations;
  52549. _this.onInterpolationDone = onInterpolationDone;
  52550. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52551. _this._target = _this._effectiveTarget = target;
  52552. return _this;
  52553. }
  52554. InterpolateValueAction.prototype._prepare = function () {
  52555. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52556. this._property = this._getProperty(this.propertyPath);
  52557. };
  52558. InterpolateValueAction.prototype.execute = function () {
  52559. var _this = this;
  52560. var scene = this._actionManager.getScene();
  52561. var keys = [
  52562. {
  52563. frame: 0,
  52564. value: this._effectiveTarget[this._property]
  52565. }, {
  52566. frame: 100,
  52567. value: this.value
  52568. }
  52569. ];
  52570. var dataType;
  52571. if (typeof this.value === "number") {
  52572. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52573. }
  52574. else if (this.value instanceof BABYLON.Color3) {
  52575. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52576. }
  52577. else if (this.value instanceof BABYLON.Vector3) {
  52578. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52579. }
  52580. else if (this.value instanceof BABYLON.Matrix) {
  52581. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52582. }
  52583. else if (this.value instanceof BABYLON.Quaternion) {
  52584. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52585. }
  52586. else {
  52587. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52588. return;
  52589. }
  52590. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52591. animation.setKeys(keys);
  52592. if (this.stopOtherAnimations) {
  52593. scene.stopAnimation(this._effectiveTarget);
  52594. }
  52595. var wrapper = function () {
  52596. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52597. if (_this.onInterpolationDone) {
  52598. _this.onInterpolationDone();
  52599. }
  52600. };
  52601. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52602. };
  52603. InterpolateValueAction.prototype.serialize = function (parent) {
  52604. return _super.prototype._serialize.call(this, {
  52605. name: "InterpolateValueAction",
  52606. properties: [
  52607. BABYLON.Action._GetTargetProperty(this._target),
  52608. { name: "propertyPath", value: this.propertyPath },
  52609. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52610. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52611. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52612. ]
  52613. }, parent);
  52614. };
  52615. return InterpolateValueAction;
  52616. }(BABYLON.Action));
  52617. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52618. })(BABYLON || (BABYLON = {}));
  52619. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52620. "use strict";
  52621. var BABYLON;
  52622. (function (BABYLON) {
  52623. var SwitchBooleanAction = /** @class */ (function (_super) {
  52624. __extends(SwitchBooleanAction, _super);
  52625. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52626. var _this = _super.call(this, triggerOptions, condition) || this;
  52627. _this.propertyPath = propertyPath;
  52628. _this._target = _this._effectiveTarget = target;
  52629. return _this;
  52630. }
  52631. SwitchBooleanAction.prototype._prepare = function () {
  52632. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52633. this._property = this._getProperty(this.propertyPath);
  52634. };
  52635. SwitchBooleanAction.prototype.execute = function () {
  52636. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52637. };
  52638. SwitchBooleanAction.prototype.serialize = function (parent) {
  52639. return _super.prototype._serialize.call(this, {
  52640. name: "SwitchBooleanAction",
  52641. properties: [
  52642. BABYLON.Action._GetTargetProperty(this._target),
  52643. { name: "propertyPath", value: this.propertyPath }
  52644. ]
  52645. }, parent);
  52646. };
  52647. return SwitchBooleanAction;
  52648. }(BABYLON.Action));
  52649. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52650. var SetStateAction = /** @class */ (function (_super) {
  52651. __extends(SetStateAction, _super);
  52652. function SetStateAction(triggerOptions, target, value, condition) {
  52653. var _this = _super.call(this, triggerOptions, condition) || this;
  52654. _this.value = value;
  52655. _this._target = target;
  52656. return _this;
  52657. }
  52658. SetStateAction.prototype.execute = function () {
  52659. this._target.state = this.value;
  52660. };
  52661. SetStateAction.prototype.serialize = function (parent) {
  52662. return _super.prototype._serialize.call(this, {
  52663. name: "SetStateAction",
  52664. properties: [
  52665. BABYLON.Action._GetTargetProperty(this._target),
  52666. { name: "value", value: this.value }
  52667. ]
  52668. }, parent);
  52669. };
  52670. return SetStateAction;
  52671. }(BABYLON.Action));
  52672. BABYLON.SetStateAction = SetStateAction;
  52673. var SetValueAction = /** @class */ (function (_super) {
  52674. __extends(SetValueAction, _super);
  52675. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52676. var _this = _super.call(this, triggerOptions, condition) || this;
  52677. _this.propertyPath = propertyPath;
  52678. _this.value = value;
  52679. _this._target = _this._effectiveTarget = target;
  52680. return _this;
  52681. }
  52682. SetValueAction.prototype._prepare = function () {
  52683. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52684. this._property = this._getProperty(this.propertyPath);
  52685. };
  52686. SetValueAction.prototype.execute = function () {
  52687. this._effectiveTarget[this._property] = this.value;
  52688. if (this._target.markAsDirty) {
  52689. this._target.markAsDirty(this._property);
  52690. }
  52691. };
  52692. SetValueAction.prototype.serialize = function (parent) {
  52693. return _super.prototype._serialize.call(this, {
  52694. name: "SetValueAction",
  52695. properties: [
  52696. BABYLON.Action._GetTargetProperty(this._target),
  52697. { name: "propertyPath", value: this.propertyPath },
  52698. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52699. ]
  52700. }, parent);
  52701. };
  52702. return SetValueAction;
  52703. }(BABYLON.Action));
  52704. BABYLON.SetValueAction = SetValueAction;
  52705. var IncrementValueAction = /** @class */ (function (_super) {
  52706. __extends(IncrementValueAction, _super);
  52707. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52708. var _this = _super.call(this, triggerOptions, condition) || this;
  52709. _this.propertyPath = propertyPath;
  52710. _this.value = value;
  52711. _this._target = _this._effectiveTarget = target;
  52712. return _this;
  52713. }
  52714. IncrementValueAction.prototype._prepare = function () {
  52715. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52716. this._property = this._getProperty(this.propertyPath);
  52717. if (typeof this._effectiveTarget[this._property] !== "number") {
  52718. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52719. }
  52720. };
  52721. IncrementValueAction.prototype.execute = function () {
  52722. this._effectiveTarget[this._property] += this.value;
  52723. if (this._target.markAsDirty) {
  52724. this._target.markAsDirty(this._property);
  52725. }
  52726. };
  52727. IncrementValueAction.prototype.serialize = function (parent) {
  52728. return _super.prototype._serialize.call(this, {
  52729. name: "IncrementValueAction",
  52730. properties: [
  52731. BABYLON.Action._GetTargetProperty(this._target),
  52732. { name: "propertyPath", value: this.propertyPath },
  52733. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52734. ]
  52735. }, parent);
  52736. };
  52737. return IncrementValueAction;
  52738. }(BABYLON.Action));
  52739. BABYLON.IncrementValueAction = IncrementValueAction;
  52740. var PlayAnimationAction = /** @class */ (function (_super) {
  52741. __extends(PlayAnimationAction, _super);
  52742. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52743. var _this = _super.call(this, triggerOptions, condition) || this;
  52744. _this.from = from;
  52745. _this.to = to;
  52746. _this.loop = loop;
  52747. _this._target = target;
  52748. return _this;
  52749. }
  52750. PlayAnimationAction.prototype._prepare = function () {
  52751. };
  52752. PlayAnimationAction.prototype.execute = function () {
  52753. var scene = this._actionManager.getScene();
  52754. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52755. };
  52756. PlayAnimationAction.prototype.serialize = function (parent) {
  52757. return _super.prototype._serialize.call(this, {
  52758. name: "PlayAnimationAction",
  52759. properties: [
  52760. BABYLON.Action._GetTargetProperty(this._target),
  52761. { name: "from", value: String(this.from) },
  52762. { name: "to", value: String(this.to) },
  52763. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52764. ]
  52765. }, parent);
  52766. };
  52767. return PlayAnimationAction;
  52768. }(BABYLON.Action));
  52769. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52770. var StopAnimationAction = /** @class */ (function (_super) {
  52771. __extends(StopAnimationAction, _super);
  52772. function StopAnimationAction(triggerOptions, target, condition) {
  52773. var _this = _super.call(this, triggerOptions, condition) || this;
  52774. _this._target = target;
  52775. return _this;
  52776. }
  52777. StopAnimationAction.prototype._prepare = function () {
  52778. };
  52779. StopAnimationAction.prototype.execute = function () {
  52780. var scene = this._actionManager.getScene();
  52781. scene.stopAnimation(this._target);
  52782. };
  52783. StopAnimationAction.prototype.serialize = function (parent) {
  52784. return _super.prototype._serialize.call(this, {
  52785. name: "StopAnimationAction",
  52786. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52787. }, parent);
  52788. };
  52789. return StopAnimationAction;
  52790. }(BABYLON.Action));
  52791. BABYLON.StopAnimationAction = StopAnimationAction;
  52792. var DoNothingAction = /** @class */ (function (_super) {
  52793. __extends(DoNothingAction, _super);
  52794. function DoNothingAction(triggerOptions, condition) {
  52795. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52796. return _super.call(this, triggerOptions, condition) || this;
  52797. }
  52798. DoNothingAction.prototype.execute = function () {
  52799. };
  52800. DoNothingAction.prototype.serialize = function (parent) {
  52801. return _super.prototype._serialize.call(this, {
  52802. name: "DoNothingAction",
  52803. properties: []
  52804. }, parent);
  52805. };
  52806. return DoNothingAction;
  52807. }(BABYLON.Action));
  52808. BABYLON.DoNothingAction = DoNothingAction;
  52809. var CombineAction = /** @class */ (function (_super) {
  52810. __extends(CombineAction, _super);
  52811. function CombineAction(triggerOptions, children, condition) {
  52812. var _this = _super.call(this, triggerOptions, condition) || this;
  52813. _this.children = children;
  52814. return _this;
  52815. }
  52816. CombineAction.prototype._prepare = function () {
  52817. for (var index = 0; index < this.children.length; index++) {
  52818. this.children[index]._actionManager = this._actionManager;
  52819. this.children[index]._prepare();
  52820. }
  52821. };
  52822. CombineAction.prototype.execute = function (evt) {
  52823. for (var index = 0; index < this.children.length; index++) {
  52824. this.children[index].execute(evt);
  52825. }
  52826. };
  52827. CombineAction.prototype.serialize = function (parent) {
  52828. var serializationObject = _super.prototype._serialize.call(this, {
  52829. name: "CombineAction",
  52830. properties: [],
  52831. combine: []
  52832. }, parent);
  52833. for (var i = 0; i < this.children.length; i++) {
  52834. serializationObject.combine.push(this.children[i].serialize(null));
  52835. }
  52836. return serializationObject;
  52837. };
  52838. return CombineAction;
  52839. }(BABYLON.Action));
  52840. BABYLON.CombineAction = CombineAction;
  52841. var ExecuteCodeAction = /** @class */ (function (_super) {
  52842. __extends(ExecuteCodeAction, _super);
  52843. function ExecuteCodeAction(triggerOptions, func, condition) {
  52844. var _this = _super.call(this, triggerOptions, condition) || this;
  52845. _this.func = func;
  52846. return _this;
  52847. }
  52848. ExecuteCodeAction.prototype.execute = function (evt) {
  52849. this.func(evt);
  52850. };
  52851. return ExecuteCodeAction;
  52852. }(BABYLON.Action));
  52853. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52854. var SetParentAction = /** @class */ (function (_super) {
  52855. __extends(SetParentAction, _super);
  52856. function SetParentAction(triggerOptions, target, parent, condition) {
  52857. var _this = _super.call(this, triggerOptions, condition) || this;
  52858. _this._target = target;
  52859. _this._parent = parent;
  52860. return _this;
  52861. }
  52862. SetParentAction.prototype._prepare = function () {
  52863. };
  52864. SetParentAction.prototype.execute = function () {
  52865. if (this._target.parent === this._parent) {
  52866. return;
  52867. }
  52868. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52869. invertParentWorldMatrix.invert();
  52870. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52871. this._target.parent = this._parent;
  52872. };
  52873. SetParentAction.prototype.serialize = function (parent) {
  52874. return _super.prototype._serialize.call(this, {
  52875. name: "SetParentAction",
  52876. properties: [
  52877. BABYLON.Action._GetTargetProperty(this._target),
  52878. BABYLON.Action._GetTargetProperty(this._parent),
  52879. ]
  52880. }, parent);
  52881. };
  52882. return SetParentAction;
  52883. }(BABYLON.Action));
  52884. BABYLON.SetParentAction = SetParentAction;
  52885. var PlaySoundAction = /** @class */ (function (_super) {
  52886. __extends(PlaySoundAction, _super);
  52887. function PlaySoundAction(triggerOptions, sound, condition) {
  52888. var _this = _super.call(this, triggerOptions, condition) || this;
  52889. _this._sound = sound;
  52890. return _this;
  52891. }
  52892. PlaySoundAction.prototype._prepare = function () {
  52893. };
  52894. PlaySoundAction.prototype.execute = function () {
  52895. if (this._sound !== undefined)
  52896. this._sound.play();
  52897. };
  52898. PlaySoundAction.prototype.serialize = function (parent) {
  52899. return _super.prototype._serialize.call(this, {
  52900. name: "PlaySoundAction",
  52901. properties: [{ name: "sound", value: this._sound.name }]
  52902. }, parent);
  52903. };
  52904. return PlaySoundAction;
  52905. }(BABYLON.Action));
  52906. BABYLON.PlaySoundAction = PlaySoundAction;
  52907. var StopSoundAction = /** @class */ (function (_super) {
  52908. __extends(StopSoundAction, _super);
  52909. function StopSoundAction(triggerOptions, sound, condition) {
  52910. var _this = _super.call(this, triggerOptions, condition) || this;
  52911. _this._sound = sound;
  52912. return _this;
  52913. }
  52914. StopSoundAction.prototype._prepare = function () {
  52915. };
  52916. StopSoundAction.prototype.execute = function () {
  52917. if (this._sound !== undefined)
  52918. this._sound.stop();
  52919. };
  52920. StopSoundAction.prototype.serialize = function (parent) {
  52921. return _super.prototype._serialize.call(this, {
  52922. name: "StopSoundAction",
  52923. properties: [{ name: "sound", value: this._sound.name }]
  52924. }, parent);
  52925. };
  52926. return StopSoundAction;
  52927. }(BABYLON.Action));
  52928. BABYLON.StopSoundAction = StopSoundAction;
  52929. })(BABYLON || (BABYLON = {}));
  52930. //# sourceMappingURL=babylon.directActions.js.map
  52931. "use strict";
  52932. var BABYLON;
  52933. (function (BABYLON) {
  52934. var SpriteManager = /** @class */ (function () {
  52935. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  52936. if (epsilon === void 0) { epsilon = 0.01; }
  52937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52938. this.name = name;
  52939. this.sprites = new Array();
  52940. this.renderingGroupId = 0;
  52941. this.layerMask = 0x0FFFFFFF;
  52942. this.fogEnabled = true;
  52943. this.isPickable = false;
  52944. /**
  52945. * An event triggered when the manager is disposed.
  52946. */
  52947. this.onDisposeObservable = new BABYLON.Observable();
  52948. this._vertexBuffers = {};
  52949. this._capacity = capacity;
  52950. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  52951. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52952. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52953. if (cellSize.width && cellSize.height) {
  52954. this.cellWidth = cellSize.width;
  52955. this.cellHeight = cellSize.height;
  52956. }
  52957. else if (cellSize !== undefined) {
  52958. this.cellWidth = cellSize;
  52959. this.cellHeight = cellSize;
  52960. }
  52961. else {
  52962. return;
  52963. }
  52964. this._epsilon = epsilon;
  52965. this._scene = scene;
  52966. this._scene.spriteManagers.push(this);
  52967. var indices = [];
  52968. var index = 0;
  52969. for (var count = 0; count < capacity; count++) {
  52970. indices.push(index);
  52971. indices.push(index + 1);
  52972. indices.push(index + 2);
  52973. indices.push(index);
  52974. indices.push(index + 2);
  52975. indices.push(index + 3);
  52976. index += 4;
  52977. }
  52978. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  52979. // VBO
  52980. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  52981. this._vertexData = new Float32Array(capacity * 16 * 4);
  52982. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  52983. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  52984. var options = this._buffer.createVertexBuffer("options", 4, 4);
  52985. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  52986. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  52987. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  52988. this._vertexBuffers["options"] = options;
  52989. this._vertexBuffers["cellInfo"] = cellInfo;
  52990. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  52991. // Effects
  52992. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  52993. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  52994. }
  52995. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  52996. set: function (callback) {
  52997. if (this._onDisposeObserver) {
  52998. this.onDisposeObservable.remove(this._onDisposeObserver);
  52999. }
  53000. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53001. },
  53002. enumerable: true,
  53003. configurable: true
  53004. });
  53005. Object.defineProperty(SpriteManager.prototype, "texture", {
  53006. get: function () {
  53007. return this._spriteTexture;
  53008. },
  53009. set: function (value) {
  53010. this._spriteTexture = value;
  53011. },
  53012. enumerable: true,
  53013. configurable: true
  53014. });
  53015. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53016. var arrayOffset = index * 16;
  53017. if (offsetX === 0)
  53018. offsetX = this._epsilon;
  53019. else if (offsetX === 1)
  53020. offsetX = 1 - this._epsilon;
  53021. if (offsetY === 0)
  53022. offsetY = this._epsilon;
  53023. else if (offsetY === 1)
  53024. offsetY = 1 - this._epsilon;
  53025. this._vertexData[arrayOffset] = sprite.position.x;
  53026. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53027. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53028. this._vertexData[arrayOffset + 3] = sprite.angle;
  53029. this._vertexData[arrayOffset + 4] = sprite.width;
  53030. this._vertexData[arrayOffset + 5] = sprite.height;
  53031. this._vertexData[arrayOffset + 6] = offsetX;
  53032. this._vertexData[arrayOffset + 7] = offsetY;
  53033. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53034. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53035. var offset = (sprite.cellIndex / rowSize) >> 0;
  53036. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53037. this._vertexData[arrayOffset + 11] = offset;
  53038. // Color
  53039. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53040. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53041. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53042. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53043. };
  53044. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53045. var count = Math.min(this._capacity, this.sprites.length);
  53046. var min = BABYLON.Vector3.Zero();
  53047. var max = BABYLON.Vector3.Zero();
  53048. var distance = Number.MAX_VALUE;
  53049. var currentSprite = null;
  53050. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53051. var cameraView = camera.getViewMatrix();
  53052. for (var index = 0; index < count; index++) {
  53053. var sprite = this.sprites[index];
  53054. if (!sprite) {
  53055. continue;
  53056. }
  53057. if (predicate) {
  53058. if (!predicate(sprite)) {
  53059. continue;
  53060. }
  53061. }
  53062. else if (!sprite.isPickable) {
  53063. continue;
  53064. }
  53065. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53066. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53067. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53068. if (ray.intersectsBoxMinMax(min, max)) {
  53069. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53070. if (distance > currentDistance) {
  53071. distance = currentDistance;
  53072. currentSprite = sprite;
  53073. if (fastCheck) {
  53074. break;
  53075. }
  53076. }
  53077. }
  53078. }
  53079. if (currentSprite) {
  53080. var result = new BABYLON.PickingInfo();
  53081. result.hit = true;
  53082. result.pickedSprite = currentSprite;
  53083. result.distance = distance;
  53084. return result;
  53085. }
  53086. return null;
  53087. };
  53088. SpriteManager.prototype.render = function () {
  53089. // Check
  53090. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53091. return;
  53092. var engine = this._scene.getEngine();
  53093. var baseSize = this._spriteTexture.getBaseSize();
  53094. // Sprites
  53095. var deltaTime = engine.getDeltaTime();
  53096. var max = Math.min(this._capacity, this.sprites.length);
  53097. var rowSize = baseSize.width / this.cellWidth;
  53098. var offset = 0;
  53099. for (var index = 0; index < max; index++) {
  53100. var sprite = this.sprites[index];
  53101. if (!sprite) {
  53102. continue;
  53103. }
  53104. sprite._animate(deltaTime);
  53105. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53106. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53107. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53108. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53109. }
  53110. this._buffer.update(this._vertexData);
  53111. // Render
  53112. var effect = this._effectBase;
  53113. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53114. effect = this._effectFog;
  53115. }
  53116. engine.enableEffect(effect);
  53117. var viewMatrix = this._scene.getViewMatrix();
  53118. effect.setTexture("diffuseSampler", this._spriteTexture);
  53119. effect.setMatrix("view", viewMatrix);
  53120. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53121. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53122. // Fog
  53123. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53124. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53125. effect.setColor3("vFogColor", this._scene.fogColor);
  53126. }
  53127. // VBOs
  53128. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53129. // Draw order
  53130. engine.setDepthFunctionToLessOrEqual();
  53131. effect.setBool("alphaTest", true);
  53132. engine.setColorWrite(false);
  53133. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53134. engine.setColorWrite(true);
  53135. effect.setBool("alphaTest", false);
  53136. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53137. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53138. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53139. };
  53140. SpriteManager.prototype.dispose = function () {
  53141. if (this._buffer) {
  53142. this._buffer.dispose();
  53143. this._buffer = null;
  53144. }
  53145. if (this._indexBuffer) {
  53146. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53147. this._indexBuffer = null;
  53148. }
  53149. if (this._spriteTexture) {
  53150. this._spriteTexture.dispose();
  53151. this._spriteTexture = null;
  53152. }
  53153. // Remove from scene
  53154. var index = this._scene.spriteManagers.indexOf(this);
  53155. this._scene.spriteManagers.splice(index, 1);
  53156. // Callback
  53157. this.onDisposeObservable.notifyObservers(this);
  53158. this.onDisposeObservable.clear();
  53159. };
  53160. return SpriteManager;
  53161. }());
  53162. BABYLON.SpriteManager = SpriteManager;
  53163. })(BABYLON || (BABYLON = {}));
  53164. //# sourceMappingURL=babylon.spriteManager.js.map
  53165. "use strict";
  53166. var BABYLON;
  53167. (function (BABYLON) {
  53168. var Sprite = /** @class */ (function () {
  53169. function Sprite(name, manager) {
  53170. this.name = name;
  53171. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53172. this.width = 1.0;
  53173. this.height = 1.0;
  53174. this.angle = 0;
  53175. this.cellIndex = 0;
  53176. this.invertU = 0;
  53177. this.invertV = 0;
  53178. this.animations = new Array();
  53179. this.isPickable = false;
  53180. this._animationStarted = false;
  53181. this._loopAnimation = false;
  53182. this._fromIndex = 0;
  53183. this._toIndex = 0;
  53184. this._delay = 0;
  53185. this._direction = 1;
  53186. this._time = 0;
  53187. this._manager = manager;
  53188. this._manager.sprites.push(this);
  53189. this.position = BABYLON.Vector3.Zero();
  53190. }
  53191. Object.defineProperty(Sprite.prototype, "size", {
  53192. get: function () {
  53193. return this.width;
  53194. },
  53195. set: function (value) {
  53196. this.width = value;
  53197. this.height = value;
  53198. },
  53199. enumerable: true,
  53200. configurable: true
  53201. });
  53202. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53203. this._fromIndex = from;
  53204. this._toIndex = to;
  53205. this._loopAnimation = loop;
  53206. this._delay = delay;
  53207. this._animationStarted = true;
  53208. this._direction = from < to ? 1 : -1;
  53209. this.cellIndex = from;
  53210. this._time = 0;
  53211. this._onAnimationEnd = onAnimationEnd;
  53212. };
  53213. Sprite.prototype.stopAnimation = function () {
  53214. this._animationStarted = false;
  53215. };
  53216. Sprite.prototype._animate = function (deltaTime) {
  53217. if (!this._animationStarted)
  53218. return;
  53219. this._time += deltaTime;
  53220. if (this._time > this._delay) {
  53221. this._time = this._time % this._delay;
  53222. this.cellIndex += this._direction;
  53223. if (this.cellIndex > this._toIndex) {
  53224. if (this._loopAnimation) {
  53225. this.cellIndex = this._fromIndex;
  53226. }
  53227. else {
  53228. this.cellIndex = this._toIndex;
  53229. this._animationStarted = false;
  53230. if (this._onAnimationEnd) {
  53231. this._onAnimationEnd();
  53232. }
  53233. if (this.disposeWhenFinishedAnimating) {
  53234. this.dispose();
  53235. }
  53236. }
  53237. }
  53238. }
  53239. };
  53240. Sprite.prototype.dispose = function () {
  53241. for (var i = 0; i < this._manager.sprites.length; i++) {
  53242. if (this._manager.sprites[i] == this) {
  53243. this._manager.sprites.splice(i, 1);
  53244. }
  53245. }
  53246. };
  53247. return Sprite;
  53248. }());
  53249. BABYLON.Sprite = Sprite;
  53250. })(BABYLON || (BABYLON = {}));
  53251. //# sourceMappingURL=babylon.sprite.js.map
  53252. "use strict";
  53253. var BABYLON;
  53254. (function (BABYLON) {
  53255. var IntersectionInfo = /** @class */ (function () {
  53256. function IntersectionInfo(bu, bv, distance) {
  53257. this.bu = bu;
  53258. this.bv = bv;
  53259. this.distance = distance;
  53260. this.faceId = 0;
  53261. this.subMeshId = 0;
  53262. }
  53263. return IntersectionInfo;
  53264. }());
  53265. BABYLON.IntersectionInfo = IntersectionInfo;
  53266. var PickingInfo = /** @class */ (function () {
  53267. function PickingInfo() {
  53268. this.hit = false;
  53269. this.distance = 0;
  53270. this.pickedPoint = null;
  53271. this.pickedMesh = null;
  53272. this.bu = 0;
  53273. this.bv = 0;
  53274. this.faceId = -1;
  53275. this.subMeshId = 0;
  53276. this.pickedSprite = null;
  53277. }
  53278. // Methods
  53279. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53280. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53281. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53282. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53283. return null;
  53284. }
  53285. var indices = this.pickedMesh.getIndices();
  53286. if (!indices) {
  53287. return null;
  53288. }
  53289. var result;
  53290. if (useVerticesNormals) {
  53291. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53292. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53293. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53294. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53295. normal0 = normal0.scale(this.bu);
  53296. normal1 = normal1.scale(this.bv);
  53297. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53298. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53299. }
  53300. else {
  53301. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53302. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53303. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53304. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53305. var p1p2 = vertex1.subtract(vertex2);
  53306. var p3p2 = vertex3.subtract(vertex2);
  53307. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53308. }
  53309. if (useWorldCoordinates) {
  53310. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53311. }
  53312. return BABYLON.Vector3.Normalize(result);
  53313. };
  53314. PickingInfo.prototype.getTextureCoordinates = function () {
  53315. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53316. return null;
  53317. }
  53318. var indices = this.pickedMesh.getIndices();
  53319. if (!indices) {
  53320. return null;
  53321. }
  53322. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53323. if (!uvs) {
  53324. return null;
  53325. }
  53326. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53327. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53328. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53329. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53330. uv1 = uv1.scale(this.bu);
  53331. uv2 = uv2.scale(this.bv);
  53332. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53333. };
  53334. return PickingInfo;
  53335. }());
  53336. BABYLON.PickingInfo = PickingInfo;
  53337. })(BABYLON || (BABYLON = {}));
  53338. //# sourceMappingURL=babylon.pickingInfo.js.map
  53339. "use strict";
  53340. var BABYLON;
  53341. (function (BABYLON) {
  53342. var Ray = /** @class */ (function () {
  53343. function Ray(origin, direction, length) {
  53344. if (length === void 0) { length = Number.MAX_VALUE; }
  53345. this.origin = origin;
  53346. this.direction = direction;
  53347. this.length = length;
  53348. }
  53349. // Methods
  53350. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53351. var d = 0.0;
  53352. var maxValue = Number.MAX_VALUE;
  53353. var inv;
  53354. var min;
  53355. var max;
  53356. var temp;
  53357. if (Math.abs(this.direction.x) < 0.0000001) {
  53358. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53359. return false;
  53360. }
  53361. }
  53362. else {
  53363. inv = 1.0 / this.direction.x;
  53364. min = (minimum.x - this.origin.x) * inv;
  53365. max = (maximum.x - this.origin.x) * inv;
  53366. if (max === -Infinity) {
  53367. max = Infinity;
  53368. }
  53369. if (min > max) {
  53370. temp = min;
  53371. min = max;
  53372. max = temp;
  53373. }
  53374. d = Math.max(min, d);
  53375. maxValue = Math.min(max, maxValue);
  53376. if (d > maxValue) {
  53377. return false;
  53378. }
  53379. }
  53380. if (Math.abs(this.direction.y) < 0.0000001) {
  53381. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53382. return false;
  53383. }
  53384. }
  53385. else {
  53386. inv = 1.0 / this.direction.y;
  53387. min = (minimum.y - this.origin.y) * inv;
  53388. max = (maximum.y - this.origin.y) * inv;
  53389. if (max === -Infinity) {
  53390. max = Infinity;
  53391. }
  53392. if (min > max) {
  53393. temp = min;
  53394. min = max;
  53395. max = temp;
  53396. }
  53397. d = Math.max(min, d);
  53398. maxValue = Math.min(max, maxValue);
  53399. if (d > maxValue) {
  53400. return false;
  53401. }
  53402. }
  53403. if (Math.abs(this.direction.z) < 0.0000001) {
  53404. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53405. return false;
  53406. }
  53407. }
  53408. else {
  53409. inv = 1.0 / this.direction.z;
  53410. min = (minimum.z - this.origin.z) * inv;
  53411. max = (maximum.z - this.origin.z) * inv;
  53412. if (max === -Infinity) {
  53413. max = Infinity;
  53414. }
  53415. if (min > max) {
  53416. temp = min;
  53417. min = max;
  53418. max = temp;
  53419. }
  53420. d = Math.max(min, d);
  53421. maxValue = Math.min(max, maxValue);
  53422. if (d > maxValue) {
  53423. return false;
  53424. }
  53425. }
  53426. return true;
  53427. };
  53428. Ray.prototype.intersectsBox = function (box) {
  53429. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53430. };
  53431. Ray.prototype.intersectsSphere = function (sphere) {
  53432. var x = sphere.center.x - this.origin.x;
  53433. var y = sphere.center.y - this.origin.y;
  53434. var z = sphere.center.z - this.origin.z;
  53435. var pyth = (x * x) + (y * y) + (z * z);
  53436. var rr = sphere.radius * sphere.radius;
  53437. if (pyth <= rr) {
  53438. return true;
  53439. }
  53440. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53441. if (dot < 0.0) {
  53442. return false;
  53443. }
  53444. var temp = pyth - (dot * dot);
  53445. return temp <= rr;
  53446. };
  53447. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53448. if (!this._edge1) {
  53449. this._edge1 = BABYLON.Vector3.Zero();
  53450. this._edge2 = BABYLON.Vector3.Zero();
  53451. this._pvec = BABYLON.Vector3.Zero();
  53452. this._tvec = BABYLON.Vector3.Zero();
  53453. this._qvec = BABYLON.Vector3.Zero();
  53454. }
  53455. vertex1.subtractToRef(vertex0, this._edge1);
  53456. vertex2.subtractToRef(vertex0, this._edge2);
  53457. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53458. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53459. if (det === 0) {
  53460. return null;
  53461. }
  53462. var invdet = 1 / det;
  53463. this.origin.subtractToRef(vertex0, this._tvec);
  53464. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53465. if (bu < 0 || bu > 1.0) {
  53466. return null;
  53467. }
  53468. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53469. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53470. if (bv < 0 || bu + bv > 1.0) {
  53471. return null;
  53472. }
  53473. //check if the distance is longer than the predefined length.
  53474. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53475. if (distance > this.length) {
  53476. return null;
  53477. }
  53478. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53479. };
  53480. Ray.prototype.intersectsPlane = function (plane) {
  53481. var distance;
  53482. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53483. if (Math.abs(result1) < 9.99999997475243E-07) {
  53484. return null;
  53485. }
  53486. else {
  53487. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53488. distance = (-plane.d - result2) / result1;
  53489. if (distance < 0.0) {
  53490. if (distance < -9.99999997475243E-07) {
  53491. return null;
  53492. }
  53493. else {
  53494. return 0;
  53495. }
  53496. }
  53497. return distance;
  53498. }
  53499. };
  53500. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53501. var tm = BABYLON.Tmp.Matrix[0];
  53502. mesh.getWorldMatrix().invertToRef(tm);
  53503. if (this._tmpRay) {
  53504. Ray.TransformToRef(this, tm, this._tmpRay);
  53505. }
  53506. else {
  53507. this._tmpRay = Ray.Transform(this, tm);
  53508. }
  53509. return mesh.intersects(this._tmpRay, fastCheck);
  53510. };
  53511. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53512. if (results) {
  53513. results.length = 0;
  53514. }
  53515. else {
  53516. results = [];
  53517. }
  53518. for (var i = 0; i < meshes.length; i++) {
  53519. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53520. if (pickInfo.hit) {
  53521. results.push(pickInfo);
  53522. }
  53523. }
  53524. results.sort(this._comparePickingInfo);
  53525. return results;
  53526. };
  53527. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53528. if (pickingInfoA.distance < pickingInfoB.distance) {
  53529. return -1;
  53530. }
  53531. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53532. return 1;
  53533. }
  53534. else {
  53535. return 0;
  53536. }
  53537. };
  53538. /**
  53539. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53540. * @param sega the first point of the segment to test the intersection against
  53541. * @param segb the second point of the segment to test the intersection against
  53542. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53543. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53544. */
  53545. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53546. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53547. var u = segb.subtract(sega);
  53548. var v = rsegb.subtract(this.origin);
  53549. var w = sega.subtract(this.origin);
  53550. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53551. var b = BABYLON.Vector3.Dot(u, v);
  53552. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53553. var d = BABYLON.Vector3.Dot(u, w);
  53554. var e = BABYLON.Vector3.Dot(v, w);
  53555. var D = a * c - b * b; // always >= 0
  53556. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53557. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53558. // compute the line parameters of the two closest points
  53559. if (D < Ray.smallnum) {
  53560. sN = 0.0; // force using point P0 on segment S1
  53561. sD = 1.0; // to prevent possible division by 0.0 later
  53562. tN = e;
  53563. tD = c;
  53564. }
  53565. else {
  53566. sN = (b * e - c * d);
  53567. tN = (a * e - b * d);
  53568. if (sN < 0.0) {
  53569. sN = 0.0;
  53570. tN = e;
  53571. tD = c;
  53572. }
  53573. else if (sN > sD) {
  53574. sN = sD;
  53575. tN = e + b;
  53576. tD = c;
  53577. }
  53578. }
  53579. if (tN < 0.0) {
  53580. tN = 0.0;
  53581. // recompute sc for this edge
  53582. if (-d < 0.0) {
  53583. sN = 0.0;
  53584. }
  53585. else if (-d > a)
  53586. sN = sD;
  53587. else {
  53588. sN = -d;
  53589. sD = a;
  53590. }
  53591. }
  53592. else if (tN > tD) {
  53593. tN = tD;
  53594. // recompute sc for this edge
  53595. if ((-d + b) < 0.0) {
  53596. sN = 0;
  53597. }
  53598. else if ((-d + b) > a) {
  53599. sN = sD;
  53600. }
  53601. else {
  53602. sN = (-d + b);
  53603. sD = a;
  53604. }
  53605. }
  53606. // finally do the division to get sc and tc
  53607. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53608. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53609. // get the difference of the two closest points
  53610. var qtc = v.multiplyByFloats(tc, tc, tc);
  53611. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53612. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53613. if (isIntersected) {
  53614. return qtc.length();
  53615. }
  53616. return -1;
  53617. };
  53618. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53619. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53620. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53621. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53622. this.direction.normalize();
  53623. return this;
  53624. };
  53625. // Statics
  53626. Ray.Zero = function () {
  53627. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53628. };
  53629. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53630. var result = Ray.Zero();
  53631. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53632. };
  53633. /**
  53634. * 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
  53635. * transformed to the given world matrix.
  53636. * @param origin The origin point
  53637. * @param end The end point
  53638. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53639. */
  53640. Ray.CreateNewFromTo = function (origin, end, world) {
  53641. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53642. var direction = end.subtract(origin);
  53643. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53644. direction.normalize();
  53645. return Ray.Transform(new Ray(origin, direction, length), world);
  53646. };
  53647. Ray.Transform = function (ray, matrix) {
  53648. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53649. Ray.TransformToRef(ray, matrix, result);
  53650. return result;
  53651. };
  53652. Ray.TransformToRef = function (ray, matrix, result) {
  53653. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53654. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53655. result.length = ray.length;
  53656. var dir = result.direction;
  53657. var len = dir.length();
  53658. if (!(len === 0 || len === 1)) {
  53659. var num = 1.0 / len;
  53660. dir.x *= num;
  53661. dir.y *= num;
  53662. dir.z *= num;
  53663. result.length *= len;
  53664. }
  53665. };
  53666. Ray.smallnum = 0.00000001;
  53667. Ray.rayl = 10e8;
  53668. return Ray;
  53669. }());
  53670. BABYLON.Ray = Ray;
  53671. })(BABYLON || (BABYLON = {}));
  53672. //# sourceMappingURL=babylon.ray.js.map
  53673. "use strict";
  53674. var BABYLON;
  53675. (function (BABYLON) {
  53676. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53677. if (boxMin.x > sphereCenter.x + sphereRadius)
  53678. return false;
  53679. if (sphereCenter.x - sphereRadius > boxMax.x)
  53680. return false;
  53681. if (boxMin.y > sphereCenter.y + sphereRadius)
  53682. return false;
  53683. if (sphereCenter.y - sphereRadius > boxMax.y)
  53684. return false;
  53685. if (boxMin.z > sphereCenter.z + sphereRadius)
  53686. return false;
  53687. if (sphereCenter.z - sphereRadius > boxMax.z)
  53688. return false;
  53689. return true;
  53690. };
  53691. var getLowestRoot = (function () {
  53692. var result = { root: 0, found: false };
  53693. return function (a, b, c, maxR) {
  53694. result.root = 0;
  53695. result.found = false;
  53696. var determinant = b * b - 4.0 * a * c;
  53697. if (determinant < 0)
  53698. return result;
  53699. var sqrtD = Math.sqrt(determinant);
  53700. var r1 = (-b - sqrtD) / (2.0 * a);
  53701. var r2 = (-b + sqrtD) / (2.0 * a);
  53702. if (r1 > r2) {
  53703. var temp = r2;
  53704. r2 = r1;
  53705. r1 = temp;
  53706. }
  53707. if (r1 > 0 && r1 < maxR) {
  53708. result.root = r1;
  53709. result.found = true;
  53710. return result;
  53711. }
  53712. if (r2 > 0 && r2 < maxR) {
  53713. result.root = r2;
  53714. result.found = true;
  53715. return result;
  53716. }
  53717. return result;
  53718. };
  53719. })();
  53720. var Collider = /** @class */ (function () {
  53721. function Collider() {
  53722. this._collisionPoint = BABYLON.Vector3.Zero();
  53723. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53724. this._tempVector = BABYLON.Vector3.Zero();
  53725. this._tempVector2 = BABYLON.Vector3.Zero();
  53726. this._tempVector3 = BABYLON.Vector3.Zero();
  53727. this._tempVector4 = BABYLON.Vector3.Zero();
  53728. this._edge = BABYLON.Vector3.Zero();
  53729. this._baseToVertex = BABYLON.Vector3.Zero();
  53730. this._destinationPoint = BABYLON.Vector3.Zero();
  53731. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53732. this._displacementVector = BABYLON.Vector3.Zero();
  53733. this._radius = BABYLON.Vector3.One();
  53734. this._retry = 0;
  53735. this._basePointWorld = BABYLON.Vector3.Zero();
  53736. this._velocityWorld = BABYLON.Vector3.Zero();
  53737. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53738. this._collisionMask = -1;
  53739. }
  53740. Object.defineProperty(Collider.prototype, "collisionMask", {
  53741. get: function () {
  53742. return this._collisionMask;
  53743. },
  53744. set: function (mask) {
  53745. this._collisionMask = !isNaN(mask) ? mask : -1;
  53746. },
  53747. enumerable: true,
  53748. configurable: true
  53749. });
  53750. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53751. /**
  53752. * Gets the plane normal used to compute the sliding response (in local space)
  53753. */
  53754. get: function () {
  53755. return this._slidePlaneNormal;
  53756. },
  53757. enumerable: true,
  53758. configurable: true
  53759. });
  53760. // Methods
  53761. Collider.prototype._initialize = function (source, dir, e) {
  53762. this._velocity = dir;
  53763. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53764. this._basePoint = source;
  53765. source.multiplyToRef(this._radius, this._basePointWorld);
  53766. dir.multiplyToRef(this._radius, this._velocityWorld);
  53767. this._velocityWorldLength = this._velocityWorld.length();
  53768. this._epsilon = e;
  53769. this.collisionFound = false;
  53770. };
  53771. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53772. pa.subtractToRef(point, this._tempVector);
  53773. pb.subtractToRef(point, this._tempVector2);
  53774. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53775. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53776. if (d < 0)
  53777. return false;
  53778. pc.subtractToRef(point, this._tempVector3);
  53779. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53780. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53781. if (d < 0)
  53782. return false;
  53783. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53784. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53785. return d >= 0;
  53786. };
  53787. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53788. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53789. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53790. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53791. return false;
  53792. }
  53793. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53794. return false;
  53795. return true;
  53796. };
  53797. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53798. var t0;
  53799. var embeddedInPlane = false;
  53800. //defensive programming, actually not needed.
  53801. if (!trianglePlaneArray) {
  53802. trianglePlaneArray = [];
  53803. }
  53804. if (!trianglePlaneArray[faceIndex]) {
  53805. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53806. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53807. }
  53808. var trianglePlane = trianglePlaneArray[faceIndex];
  53809. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53810. return;
  53811. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53812. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53813. if (normalDotVelocity == 0) {
  53814. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53815. return;
  53816. embeddedInPlane = true;
  53817. t0 = 0;
  53818. }
  53819. else {
  53820. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53821. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53822. if (t0 > t1) {
  53823. var temp = t1;
  53824. t1 = t0;
  53825. t0 = temp;
  53826. }
  53827. if (t0 > 1.0 || t1 < 0.0)
  53828. return;
  53829. if (t0 < 0)
  53830. t0 = 0;
  53831. if (t0 > 1.0)
  53832. t0 = 1.0;
  53833. }
  53834. this._collisionPoint.copyFromFloats(0, 0, 0);
  53835. var found = false;
  53836. var t = 1.0;
  53837. if (!embeddedInPlane) {
  53838. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53839. this._velocity.scaleToRef(t0, this._tempVector);
  53840. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53841. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53842. found = true;
  53843. t = t0;
  53844. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53845. }
  53846. }
  53847. if (!found) {
  53848. var velocitySquaredLength = this._velocity.lengthSquared();
  53849. var a = velocitySquaredLength;
  53850. this._basePoint.subtractToRef(p1, this._tempVector);
  53851. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53852. var c = this._tempVector.lengthSquared() - 1.0;
  53853. var lowestRoot = getLowestRoot(a, b, c, t);
  53854. if (lowestRoot.found) {
  53855. t = lowestRoot.root;
  53856. found = true;
  53857. this._collisionPoint.copyFrom(p1);
  53858. }
  53859. this._basePoint.subtractToRef(p2, this._tempVector);
  53860. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53861. c = this._tempVector.lengthSquared() - 1.0;
  53862. lowestRoot = getLowestRoot(a, b, c, t);
  53863. if (lowestRoot.found) {
  53864. t = lowestRoot.root;
  53865. found = true;
  53866. this._collisionPoint.copyFrom(p2);
  53867. }
  53868. this._basePoint.subtractToRef(p3, this._tempVector);
  53869. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53870. c = this._tempVector.lengthSquared() - 1.0;
  53871. lowestRoot = getLowestRoot(a, b, c, t);
  53872. if (lowestRoot.found) {
  53873. t = lowestRoot.root;
  53874. found = true;
  53875. this._collisionPoint.copyFrom(p3);
  53876. }
  53877. p2.subtractToRef(p1, this._edge);
  53878. p1.subtractToRef(this._basePoint, this._baseToVertex);
  53879. var edgeSquaredLength = this._edge.lengthSquared();
  53880. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53881. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53882. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53883. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53884. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53885. lowestRoot = getLowestRoot(a, b, c, t);
  53886. if (lowestRoot.found) {
  53887. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53888. if (f >= 0.0 && f <= 1.0) {
  53889. t = lowestRoot.root;
  53890. found = true;
  53891. this._edge.scaleInPlace(f);
  53892. p1.addToRef(this._edge, this._collisionPoint);
  53893. }
  53894. }
  53895. p3.subtractToRef(p2, this._edge);
  53896. p2.subtractToRef(this._basePoint, this._baseToVertex);
  53897. edgeSquaredLength = this._edge.lengthSquared();
  53898. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53899. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53900. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53901. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53902. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53903. lowestRoot = getLowestRoot(a, b, c, t);
  53904. if (lowestRoot.found) {
  53905. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53906. if (f >= 0.0 && f <= 1.0) {
  53907. t = lowestRoot.root;
  53908. found = true;
  53909. this._edge.scaleInPlace(f);
  53910. p2.addToRef(this._edge, this._collisionPoint);
  53911. }
  53912. }
  53913. p1.subtractToRef(p3, this._edge);
  53914. p3.subtractToRef(this._basePoint, this._baseToVertex);
  53915. edgeSquaredLength = this._edge.lengthSquared();
  53916. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53917. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53918. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53919. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53920. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53921. lowestRoot = getLowestRoot(a, b, c, t);
  53922. if (lowestRoot.found) {
  53923. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53924. if (f >= 0.0 && f <= 1.0) {
  53925. t = lowestRoot.root;
  53926. found = true;
  53927. this._edge.scaleInPlace(f);
  53928. p3.addToRef(this._edge, this._collisionPoint);
  53929. }
  53930. }
  53931. }
  53932. if (found) {
  53933. var distToCollision = t * this._velocity.length();
  53934. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  53935. if (!this.intersectionPoint) {
  53936. this.intersectionPoint = this._collisionPoint.clone();
  53937. }
  53938. else {
  53939. this.intersectionPoint.copyFrom(this._collisionPoint);
  53940. }
  53941. this._nearestDistance = distToCollision;
  53942. this.collisionFound = true;
  53943. }
  53944. }
  53945. };
  53946. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  53947. for (var i = indexStart; i < indexEnd; i += 3) {
  53948. var p1 = pts[indices[i] - decal];
  53949. var p2 = pts[indices[i + 1] - decal];
  53950. var p3 = pts[indices[i + 2] - decal];
  53951. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  53952. }
  53953. };
  53954. Collider.prototype._getResponse = function (pos, vel) {
  53955. pos.addToRef(vel, this._destinationPoint);
  53956. vel.scaleInPlace((this._nearestDistance / vel.length()));
  53957. this._basePoint.addToRef(vel, pos);
  53958. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  53959. this._slidePlaneNormal.normalize();
  53960. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  53961. pos.addInPlace(this._displacementVector);
  53962. this.intersectionPoint.addInPlace(this._displacementVector);
  53963. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  53964. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  53965. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  53966. };
  53967. return Collider;
  53968. }());
  53969. BABYLON.Collider = Collider;
  53970. })(BABYLON || (BABYLON = {}));
  53971. //# sourceMappingURL=babylon.collider.js.map
  53972. "use strict";
  53973. var BABYLON;
  53974. (function (BABYLON) {
  53975. //WebWorker code will be inserted to this variable.
  53976. BABYLON.CollisionWorker = "";
  53977. var WorkerTaskType;
  53978. (function (WorkerTaskType) {
  53979. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  53980. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  53981. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  53982. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  53983. var WorkerReplyType;
  53984. (function (WorkerReplyType) {
  53985. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  53986. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  53987. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  53988. var CollisionCoordinatorWorker = /** @class */ (function () {
  53989. function CollisionCoordinatorWorker() {
  53990. var _this = this;
  53991. this._scaledPosition = BABYLON.Vector3.Zero();
  53992. this._scaledVelocity = BABYLON.Vector3.Zero();
  53993. this.onMeshUpdated = function (transformNode) {
  53994. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  53995. };
  53996. this.onGeometryUpdated = function (geometry) {
  53997. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  53998. };
  53999. this._afterRender = function () {
  54000. if (!_this._init)
  54001. return;
  54002. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54003. return;
  54004. }
  54005. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54006. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54007. if (_this._runningUpdated > 4) {
  54008. return;
  54009. }
  54010. ++_this._runningUpdated;
  54011. var payload = {
  54012. updatedMeshes: _this._addUpdateMeshesList,
  54013. updatedGeometries: _this._addUpdateGeometriesList,
  54014. removedGeometries: _this._toRemoveGeometryArray,
  54015. removedMeshes: _this._toRemoveMeshesArray
  54016. };
  54017. var message = {
  54018. payload: payload,
  54019. taskType: WorkerTaskType.UPDATE
  54020. };
  54021. var serializable = [];
  54022. for (var id in payload.updatedGeometries) {
  54023. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54024. //prepare transferables
  54025. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54026. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54027. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54028. }
  54029. }
  54030. _this._worker.postMessage(message, serializable);
  54031. _this._addUpdateMeshesList = {};
  54032. _this._addUpdateGeometriesList = {};
  54033. _this._toRemoveGeometryArray = [];
  54034. _this._toRemoveMeshesArray = [];
  54035. };
  54036. this._onMessageFromWorker = function (e) {
  54037. var returnData = e.data;
  54038. if (returnData.error != WorkerReplyType.SUCCESS) {
  54039. //TODO what errors can be returned from the worker?
  54040. BABYLON.Tools.Warn("error returned from worker!");
  54041. return;
  54042. }
  54043. switch (returnData.taskType) {
  54044. case WorkerTaskType.INIT:
  54045. _this._init = true;
  54046. //Update the worked with ALL of the scene's current state
  54047. _this._scene.meshes.forEach(function (mesh) {
  54048. _this.onMeshAdded(mesh);
  54049. });
  54050. _this._scene.getGeometries().forEach(function (geometry) {
  54051. _this.onGeometryAdded(geometry);
  54052. });
  54053. break;
  54054. case WorkerTaskType.UPDATE:
  54055. _this._runningUpdated--;
  54056. break;
  54057. case WorkerTaskType.COLLIDE:
  54058. var returnPayload = returnData.payload;
  54059. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54060. return;
  54061. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54062. if (callback) {
  54063. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54064. if (mesh) {
  54065. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54066. }
  54067. }
  54068. //cleanup
  54069. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54070. break;
  54071. }
  54072. };
  54073. this._collisionsCallbackArray = [];
  54074. this._init = false;
  54075. this._runningUpdated = 0;
  54076. this._addUpdateMeshesList = {};
  54077. this._addUpdateGeometriesList = {};
  54078. this._toRemoveGeometryArray = [];
  54079. this._toRemoveMeshesArray = [];
  54080. }
  54081. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54082. if (!this._init)
  54083. return;
  54084. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54085. return;
  54086. position.divideToRef(collider._radius, this._scaledPosition);
  54087. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54088. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54089. var payload = {
  54090. collider: {
  54091. position: this._scaledPosition.asArray(),
  54092. velocity: this._scaledVelocity.asArray(),
  54093. radius: collider._radius.asArray()
  54094. },
  54095. collisionId: collisionIndex,
  54096. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54097. maximumRetry: maximumRetry
  54098. };
  54099. var message = {
  54100. payload: payload,
  54101. taskType: WorkerTaskType.COLLIDE
  54102. };
  54103. this._worker.postMessage(message);
  54104. };
  54105. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54106. this._scene = scene;
  54107. this._scene.registerAfterRender(this._afterRender);
  54108. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54109. this._worker = new Worker(workerUrl);
  54110. this._worker.onmessage = this._onMessageFromWorker;
  54111. var message = {
  54112. payload: {},
  54113. taskType: WorkerTaskType.INIT
  54114. };
  54115. this._worker.postMessage(message);
  54116. };
  54117. CollisionCoordinatorWorker.prototype.destroy = function () {
  54118. this._scene.unregisterAfterRender(this._afterRender);
  54119. this._worker.terminate();
  54120. };
  54121. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54122. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54123. this.onMeshUpdated(mesh);
  54124. };
  54125. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54126. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54127. };
  54128. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54129. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54130. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54131. this.onGeometryUpdated(geometry);
  54132. };
  54133. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54134. this._toRemoveGeometryArray.push(geometry.id);
  54135. };
  54136. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54137. var submeshes = [];
  54138. if (mesh.subMeshes) {
  54139. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54140. var boundingInfo = sm.getBoundingInfo();
  54141. return {
  54142. position: idx,
  54143. verticesStart: sm.verticesStart,
  54144. verticesCount: sm.verticesCount,
  54145. indexStart: sm.indexStart,
  54146. indexCount: sm.indexCount,
  54147. hasMaterial: !!sm.getMaterial(),
  54148. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54149. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54150. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54151. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54152. };
  54153. });
  54154. }
  54155. var geometryId = null;
  54156. if (mesh instanceof BABYLON.Mesh) {
  54157. var geometry = mesh.geometry;
  54158. geometryId = geometry ? geometry.id : null;
  54159. }
  54160. else if (mesh instanceof BABYLON.InstancedMesh) {
  54161. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54162. geometryId = geometry ? geometry.id : null;
  54163. }
  54164. var boundingInfo = mesh.getBoundingInfo();
  54165. return {
  54166. uniqueId: mesh.uniqueId,
  54167. id: mesh.id,
  54168. name: mesh.name,
  54169. geometryId: geometryId,
  54170. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54171. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54172. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54173. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54174. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54175. subMeshes: submeshes,
  54176. checkCollisions: mesh.checkCollisions
  54177. };
  54178. };
  54179. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54180. return {
  54181. id: geometry.id,
  54182. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54183. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54184. indices: new Uint32Array(geometry.getIndices() || []),
  54185. };
  54186. };
  54187. return CollisionCoordinatorWorker;
  54188. }());
  54189. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54190. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54191. function CollisionCoordinatorLegacy() {
  54192. this._scaledPosition = BABYLON.Vector3.Zero();
  54193. this._scaledVelocity = BABYLON.Vector3.Zero();
  54194. this._finalPosition = BABYLON.Vector3.Zero();
  54195. }
  54196. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54197. position.divideToRef(collider._radius, this._scaledPosition);
  54198. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54199. collider.collidedMesh = null;
  54200. collider._retry = 0;
  54201. collider._initialVelocity = this._scaledVelocity;
  54202. collider._initialPosition = this._scaledPosition;
  54203. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54204. this._finalPosition.multiplyInPlace(collider._radius);
  54205. //run the callback
  54206. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54207. };
  54208. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54209. this._scene = scene;
  54210. };
  54211. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54212. //Legacy need no destruction method.
  54213. };
  54214. //No update in legacy mode
  54215. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54216. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54217. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54218. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54219. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54220. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54221. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54222. if (excludedMesh === void 0) { excludedMesh = null; }
  54223. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54224. if (collider._retry >= maximumRetry) {
  54225. finalPosition.copyFrom(position);
  54226. return;
  54227. }
  54228. // Check if this is a mesh else camera or -1
  54229. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54230. collider._initialize(position, velocity, closeDistance);
  54231. // Check all meshes
  54232. for (var index = 0; index < this._scene.meshes.length; index++) {
  54233. var mesh = this._scene.meshes[index];
  54234. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54235. mesh._checkCollision(collider);
  54236. }
  54237. }
  54238. if (!collider.collisionFound) {
  54239. position.addToRef(velocity, finalPosition);
  54240. return;
  54241. }
  54242. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54243. collider._getResponse(position, velocity);
  54244. }
  54245. if (velocity.length() <= closeDistance) {
  54246. finalPosition.copyFrom(position);
  54247. return;
  54248. }
  54249. collider._retry++;
  54250. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54251. };
  54252. return CollisionCoordinatorLegacy;
  54253. }());
  54254. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54255. })(BABYLON || (BABYLON = {}));
  54256. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54257. "use strict";
  54258. var BABYLON;
  54259. (function (BABYLON) {
  54260. /**
  54261. * A particle represents one of the element emitted by a particle system.
  54262. * This is mainly define by its coordinates, direction, velocity and age.
  54263. */
  54264. var Particle = /** @class */ (function () {
  54265. /**
  54266. * Creates a new instance Particle
  54267. * @param particleSystem the particle system the particle belongs to
  54268. */
  54269. function Particle(
  54270. /**
  54271. * particleSystem the particle system the particle belongs to.
  54272. */
  54273. particleSystem) {
  54274. this.particleSystem = particleSystem;
  54275. /**
  54276. * The world position of the particle in the scene.
  54277. */
  54278. this.position = BABYLON.Vector3.Zero();
  54279. /**
  54280. * The world direction of the particle in the scene.
  54281. */
  54282. this.direction = BABYLON.Vector3.Zero();
  54283. /**
  54284. * The color of the particle.
  54285. */
  54286. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54287. /**
  54288. * The color change of the particle per step.
  54289. */
  54290. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54291. /**
  54292. * Defines how long will the life of the particle be.
  54293. */
  54294. this.lifeTime = 1.0;
  54295. /**
  54296. * The current age of the particle.
  54297. */
  54298. this.age = 0;
  54299. /**
  54300. * The current size of the particle.
  54301. */
  54302. this.size = 0;
  54303. /**
  54304. * The current angle of the particle.
  54305. */
  54306. this.angle = 0;
  54307. /**
  54308. * Defines how fast is the angle changing.
  54309. */
  54310. this.angularSpeed = 0;
  54311. /**
  54312. * Defines the cell index used by the particle to be rendered from a sprite.
  54313. */
  54314. this.cellIndex = 0;
  54315. this._currentFrameCounter = 0;
  54316. if (!this.particleSystem.isAnimationSheetEnabled) {
  54317. return;
  54318. }
  54319. this.updateCellInfoFromSystem();
  54320. }
  54321. Particle.prototype.updateCellInfoFromSystem = function () {
  54322. this.cellIndex = this.particleSystem.startSpriteCellID;
  54323. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54324. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54325. }
  54326. else {
  54327. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54328. }
  54329. };
  54330. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54331. // (ageOffset / scaledUpdateSpeed) / available cells
  54332. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54333. this._currentFrameCounter += scaledUpdateSpeed;
  54334. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54335. this._currentFrameCounter = 0;
  54336. this.cellIndex++;
  54337. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54338. this.cellIndex = this.particleSystem.endSpriteCellID;
  54339. }
  54340. }
  54341. };
  54342. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54343. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54344. this.cellIndex++;
  54345. this._currentFrameCounter = 0;
  54346. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54347. if (this.particleSystem.spriteCellLoop) {
  54348. this.cellIndex = this.particleSystem.startSpriteCellID;
  54349. }
  54350. else {
  54351. this.cellIndex = this.particleSystem.endSpriteCellID;
  54352. }
  54353. }
  54354. }
  54355. else {
  54356. this._currentFrameCounter++;
  54357. }
  54358. };
  54359. /**
  54360. * Copy the properties of particle to another one.
  54361. * @param other the particle to copy the information to.
  54362. */
  54363. Particle.prototype.copyTo = function (other) {
  54364. other.position.copyFrom(this.position);
  54365. other.direction.copyFrom(this.direction);
  54366. other.color.copyFrom(this.color);
  54367. other.colorStep.copyFrom(this.colorStep);
  54368. other.lifeTime = this.lifeTime;
  54369. other.age = this.age;
  54370. other.size = this.size;
  54371. other.angle = this.angle;
  54372. other.angularSpeed = this.angularSpeed;
  54373. other.particleSystem = this.particleSystem;
  54374. other.cellIndex = this.cellIndex;
  54375. };
  54376. return Particle;
  54377. }());
  54378. BABYLON.Particle = Particle;
  54379. })(BABYLON || (BABYLON = {}));
  54380. //# sourceMappingURL=babylon.particle.js.map
  54381. "use strict";
  54382. var BABYLON;
  54383. (function (BABYLON) {
  54384. /**
  54385. * This represents a particle system in Babylon.
  54386. * 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.
  54387. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54388. * @example https://doc.babylonjs.com/babylon101/particles
  54389. */
  54390. var ParticleSystem = /** @class */ (function () {
  54391. /**
  54392. * Instantiates a particle system.
  54393. * 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.
  54394. * @param name The name of the particle system
  54395. * @param capacity The max number of particles alive at the same time
  54396. * @param scene The scene the particle system belongs to
  54397. * @param customEffect a custom effect used to change the way particles are rendered by default
  54398. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54399. * @param epsilon Offset used to render the particles
  54400. */
  54401. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54402. if (customEffect === void 0) { customEffect = null; }
  54403. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54404. if (epsilon === void 0) { epsilon = 0.01; }
  54405. var _this = this;
  54406. /**
  54407. * List of animations used by the particle system.
  54408. */
  54409. this.animations = [];
  54410. /**
  54411. * The rendering group used by the Particle system to chose when to render.
  54412. */
  54413. this.renderingGroupId = 0;
  54414. /**
  54415. * The emitter represents the Mesh or position we are attaching the particle system to.
  54416. */
  54417. this.emitter = null;
  54418. /**
  54419. * The maximum number of particles to emit per frame
  54420. */
  54421. this.emitRate = 10;
  54422. /**
  54423. * If you want to launch only a few particles at once, that can be done, as well.
  54424. */
  54425. this.manualEmitCount = -1;
  54426. /**
  54427. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54428. */
  54429. this.updateSpeed = 0.01;
  54430. /**
  54431. * The amount of time the particle system is running (depends of the overall update speed).
  54432. */
  54433. this.targetStopDuration = 0;
  54434. /**
  54435. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54436. */
  54437. this.disposeOnStop = false;
  54438. /**
  54439. * Minimum power of emitting particles.
  54440. */
  54441. this.minEmitPower = 1;
  54442. /**
  54443. * Maximum power of emitting particles.
  54444. */
  54445. this.maxEmitPower = 1;
  54446. /**
  54447. * Minimum life time of emitting particles.
  54448. */
  54449. this.minLifeTime = 1;
  54450. /**
  54451. * Maximum life time of emitting particles.
  54452. */
  54453. this.maxLifeTime = 1;
  54454. /**
  54455. * Minimum Size of emitting particles.
  54456. */
  54457. this.minSize = 1;
  54458. /**
  54459. * Maximum Size of emitting particles.
  54460. */
  54461. this.maxSize = 1;
  54462. /**
  54463. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54464. */
  54465. this.minAngularSpeed = 0;
  54466. /**
  54467. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54468. */
  54469. this.maxAngularSpeed = 0;
  54470. /**
  54471. * The layer mask we are rendering the particles through.
  54472. */
  54473. this.layerMask = 0x0FFFFFFF;
  54474. /**
  54475. * This can help using your own shader to render the particle system.
  54476. * The according effect will be created
  54477. */
  54478. this.customShader = null;
  54479. /**
  54480. * By default particle system starts as soon as they are created. This prevents the
  54481. * automatic start to happen and let you decide when to start emitting particles.
  54482. */
  54483. this.preventAutoStart = false;
  54484. /**
  54485. * Callback triggered when the particle animation is ending.
  54486. */
  54487. this.onAnimationEnd = null;
  54488. /**
  54489. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54490. */
  54491. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54492. /**
  54493. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54494. * to override the particles.
  54495. */
  54496. this.forceDepthWrite = false;
  54497. /**
  54498. * You can use gravity if you want to give an orientation to your particles.
  54499. */
  54500. this.gravity = BABYLON.Vector3.Zero();
  54501. /**
  54502. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54503. */
  54504. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54505. /**
  54506. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54507. */
  54508. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54509. /**
  54510. * Color the particle will have at the end of its lifetime.
  54511. */
  54512. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54513. /**
  54514. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  54515. */
  54516. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54517. /**
  54518. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  54519. */
  54520. this.spriteCellLoop = true;
  54521. /**
  54522. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  54523. */
  54524. this.spriteCellChangeSpeed = 0;
  54525. /**
  54526. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  54527. */
  54528. this.startSpriteCellID = 0;
  54529. /**
  54530. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  54531. */
  54532. this.endSpriteCellID = 0;
  54533. /**
  54534. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  54535. */
  54536. this.spriteCellWidth = 0;
  54537. /**
  54538. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  54539. */
  54540. this.spriteCellHeight = 0;
  54541. /**
  54542. * An event triggered when the system is disposed.
  54543. */
  54544. this.onDisposeObservable = new BABYLON.Observable();
  54545. this._particles = new Array();
  54546. this._stockParticles = new Array();
  54547. this._newPartsExcess = 0;
  54548. this._vertexBuffers = {};
  54549. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54550. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54551. this._scaledDirection = BABYLON.Vector3.Zero();
  54552. this._scaledGravity = BABYLON.Vector3.Zero();
  54553. this._currentRenderId = -1;
  54554. this._started = false;
  54555. this._stopped = false;
  54556. this._actualFrame = 0;
  54557. this._vertexBufferSize = 11;
  54558. // start of sub system methods
  54559. /**
  54560. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54561. * Its lifetime will start back at 0.
  54562. */
  54563. this.recycleParticle = function (particle) {
  54564. var lastParticle = _this._particles.pop();
  54565. if (lastParticle !== particle) {
  54566. lastParticle.copyTo(particle);
  54567. }
  54568. _this._stockParticles.push(lastParticle);
  54569. };
  54570. this._createParticle = function () {
  54571. var particle;
  54572. if (_this._stockParticles.length !== 0) {
  54573. particle = _this._stockParticles.pop();
  54574. particle.age = 0;
  54575. particle.cellIndex = _this.startSpriteCellID;
  54576. }
  54577. else {
  54578. particle = new BABYLON.Particle(_this);
  54579. }
  54580. return particle;
  54581. };
  54582. this._emitFromParticle = function (particle) {
  54583. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54584. return;
  54585. }
  54586. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54587. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54588. subSystem._rootParticleSystem = _this;
  54589. _this.activeSubSystems.push(subSystem);
  54590. subSystem.start();
  54591. };
  54592. this._appendParticleVertexes = null;
  54593. this.id = name;
  54594. this.name = name;
  54595. this._capacity = capacity;
  54596. this._epsilon = epsilon;
  54597. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54598. if (isAnimationSheetEnabled) {
  54599. this._vertexBufferSize = 12;
  54600. }
  54601. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54602. this._customEffect = customEffect;
  54603. scene.particleSystems.push(this);
  54604. this._createIndexBuffer();
  54605. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  54606. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  54607. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  54608. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  54609. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  54610. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  54611. if (this._isAnimationSheetEnabled) {
  54612. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  54613. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  54614. }
  54615. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54616. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54617. this._vertexBuffers["options"] = options;
  54618. // Default emitter type
  54619. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54620. this.updateFunction = function (particles) {
  54621. for (var index = 0; index < particles.length; index++) {
  54622. var particle = particles[index];
  54623. particle.age += _this._scaledUpdateSpeed;
  54624. if (particle.age >= particle.lifeTime) {
  54625. _this._emitFromParticle(particle);
  54626. _this.recycleParticle(particle);
  54627. index--;
  54628. continue;
  54629. }
  54630. else {
  54631. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54632. particle.color.addInPlace(_this._scaledColorStep);
  54633. if (particle.color.a < 0)
  54634. particle.color.a = 0;
  54635. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54636. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  54637. particle.position.addInPlace(_this._scaledDirection);
  54638. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54639. particle.direction.addInPlace(_this._scaledGravity);
  54640. if (_this._isAnimationSheetEnabled) {
  54641. particle.updateCellIndex(_this._scaledUpdateSpeed);
  54642. }
  54643. }
  54644. }
  54645. };
  54646. }
  54647. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54648. /**
  54649. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54650. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54651. */
  54652. get: function () {
  54653. if (this.particleEmitterType.direction1) {
  54654. return this.particleEmitterType.direction1;
  54655. }
  54656. return BABYLON.Vector3.Zero();
  54657. },
  54658. set: function (value) {
  54659. if (this.particleEmitterType.direction1) {
  54660. this.particleEmitterType.direction1 = value;
  54661. }
  54662. },
  54663. enumerable: true,
  54664. configurable: true
  54665. });
  54666. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54667. /**
  54668. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54669. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54670. */
  54671. get: function () {
  54672. if (this.particleEmitterType.direction2) {
  54673. return this.particleEmitterType.direction2;
  54674. }
  54675. return BABYLON.Vector3.Zero();
  54676. },
  54677. set: function (value) {
  54678. if (this.particleEmitterType.direction2) {
  54679. this.particleEmitterType.direction2 = value;
  54680. }
  54681. },
  54682. enumerable: true,
  54683. configurable: true
  54684. });
  54685. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54686. /**
  54687. * 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.
  54688. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54689. */
  54690. get: function () {
  54691. if (this.particleEmitterType.minEmitBox) {
  54692. return this.particleEmitterType.minEmitBox;
  54693. }
  54694. return BABYLON.Vector3.Zero();
  54695. },
  54696. set: function (value) {
  54697. if (this.particleEmitterType.minEmitBox) {
  54698. this.particleEmitterType.minEmitBox = value;
  54699. }
  54700. },
  54701. enumerable: true,
  54702. configurable: true
  54703. });
  54704. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54705. /**
  54706. * 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.
  54707. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54708. */
  54709. get: function () {
  54710. if (this.particleEmitterType.maxEmitBox) {
  54711. return this.particleEmitterType.maxEmitBox;
  54712. }
  54713. return BABYLON.Vector3.Zero();
  54714. },
  54715. set: function (value) {
  54716. if (this.particleEmitterType.maxEmitBox) {
  54717. this.particleEmitterType.maxEmitBox = value;
  54718. }
  54719. },
  54720. enumerable: true,
  54721. configurable: true
  54722. });
  54723. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54724. /**
  54725. * Sets a callback that will be triggered when the system is disposed.
  54726. */
  54727. set: function (callback) {
  54728. if (this._onDisposeObserver) {
  54729. this.onDisposeObservable.remove(this._onDisposeObserver);
  54730. }
  54731. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54732. },
  54733. enumerable: true,
  54734. configurable: true
  54735. });
  54736. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54737. /**
  54738. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  54739. */
  54740. get: function () {
  54741. return this._isAnimationSheetEnabled;
  54742. },
  54743. enumerable: true,
  54744. configurable: true
  54745. });
  54746. Object.defineProperty(ParticleSystem.prototype, "particles", {
  54747. //end of Sub-emitter
  54748. /**
  54749. * Gets the current list of active particles
  54750. */
  54751. get: function () {
  54752. return this._particles;
  54753. },
  54754. enumerable: true,
  54755. configurable: true
  54756. });
  54757. /**
  54758. * Returns the string "ParticleSystem"
  54759. * @returns a string containing the class name
  54760. */
  54761. ParticleSystem.prototype.getClassName = function () {
  54762. return "ParticleSystem";
  54763. };
  54764. ParticleSystem.prototype._createIndexBuffer = function () {
  54765. var indices = [];
  54766. var index = 0;
  54767. for (var count = 0; count < this._capacity; count++) {
  54768. indices.push(index);
  54769. indices.push(index + 1);
  54770. indices.push(index + 2);
  54771. indices.push(index);
  54772. indices.push(index + 2);
  54773. indices.push(index + 3);
  54774. index += 4;
  54775. }
  54776. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  54777. };
  54778. /**
  54779. * Gets the maximum number of particles active at the same time.
  54780. * @returns The max number of active particles.
  54781. */
  54782. ParticleSystem.prototype.getCapacity = function () {
  54783. return this._capacity;
  54784. };
  54785. /**
  54786. * Gets Wether there are still active particles in the system.
  54787. * @returns True if it is alive, otherwise false.
  54788. */
  54789. ParticleSystem.prototype.isAlive = function () {
  54790. return this._alive;
  54791. };
  54792. /**
  54793. * Gets Wether the system has been started.
  54794. * @returns True if it has been started, otherwise false.
  54795. */
  54796. ParticleSystem.prototype.isStarted = function () {
  54797. return this._started;
  54798. };
  54799. /**
  54800. * Starts the particle system and begins to emit.
  54801. */
  54802. ParticleSystem.prototype.start = function () {
  54803. this._started = true;
  54804. this._stopped = false;
  54805. this._actualFrame = 0;
  54806. if (this.subEmitters && this.subEmitters.length != 0) {
  54807. this.activeSubSystems = new Array();
  54808. }
  54809. };
  54810. /**
  54811. * Stops the particle system.
  54812. * @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.
  54813. */
  54814. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  54815. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  54816. this._stopped = true;
  54817. if (stopSubEmitters) {
  54818. this._stopSubEmitters();
  54819. }
  54820. };
  54821. // animation sheet
  54822. /**
  54823. * Remove all active particles
  54824. */
  54825. ParticleSystem.prototype.reset = function () {
  54826. this._stockParticles = [];
  54827. this._particles = [];
  54828. };
  54829. /**
  54830. * @ignore (for internal use only)
  54831. */
  54832. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  54833. var offset = index * this._vertexBufferSize;
  54834. this._vertexData[offset] = particle.position.x;
  54835. this._vertexData[offset + 1] = particle.position.y;
  54836. this._vertexData[offset + 2] = particle.position.z;
  54837. this._vertexData[offset + 3] = particle.color.r;
  54838. this._vertexData[offset + 4] = particle.color.g;
  54839. this._vertexData[offset + 5] = particle.color.b;
  54840. this._vertexData[offset + 6] = particle.color.a;
  54841. this._vertexData[offset + 7] = particle.angle;
  54842. this._vertexData[offset + 8] = particle.size;
  54843. this._vertexData[offset + 9] = offsetX;
  54844. this._vertexData[offset + 10] = offsetY;
  54845. };
  54846. /**
  54847. * @ignore (for internal use only)
  54848. */
  54849. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  54850. if (offsetX === 0)
  54851. offsetX = this._epsilon;
  54852. else if (offsetX === 1)
  54853. offsetX = 1 - this._epsilon;
  54854. if (offsetY === 0)
  54855. offsetY = this._epsilon;
  54856. else if (offsetY === 1)
  54857. offsetY = 1 - this._epsilon;
  54858. var offset = index * this._vertexBufferSize;
  54859. this._vertexData[offset] = particle.position.x;
  54860. this._vertexData[offset + 1] = particle.position.y;
  54861. this._vertexData[offset + 2] = particle.position.z;
  54862. this._vertexData[offset + 3] = particle.color.r;
  54863. this._vertexData[offset + 4] = particle.color.g;
  54864. this._vertexData[offset + 5] = particle.color.b;
  54865. this._vertexData[offset + 6] = particle.color.a;
  54866. this._vertexData[offset + 7] = particle.angle;
  54867. this._vertexData[offset + 8] = particle.size;
  54868. this._vertexData[offset + 9] = offsetX;
  54869. this._vertexData[offset + 10] = offsetY;
  54870. this._vertexData[offset + 11] = particle.cellIndex;
  54871. };
  54872. ParticleSystem.prototype._stopSubEmitters = function () {
  54873. if (!this.activeSubSystems) {
  54874. return;
  54875. }
  54876. this.activeSubSystems.forEach(function (subSystem) {
  54877. subSystem.stop(true);
  54878. });
  54879. this.activeSubSystems = new Array();
  54880. };
  54881. ParticleSystem.prototype._removeFromRoot = function () {
  54882. if (!this._rootParticleSystem) {
  54883. return;
  54884. }
  54885. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  54886. if (index !== -1) {
  54887. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  54888. }
  54889. };
  54890. // end of sub system methods
  54891. ParticleSystem.prototype._update = function (newParticles) {
  54892. // Update current
  54893. this._alive = this._particles.length > 0;
  54894. this.updateFunction(this._particles);
  54895. // Add new ones
  54896. var worldMatrix;
  54897. if (this.emitter.position) {
  54898. var emitterMesh = this.emitter;
  54899. worldMatrix = emitterMesh.getWorldMatrix();
  54900. }
  54901. else {
  54902. var emitterPosition = this.emitter;
  54903. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  54904. }
  54905. var particle;
  54906. for (var index = 0; index < newParticles; index++) {
  54907. if (this._particles.length === this._capacity) {
  54908. break;
  54909. }
  54910. particle = this._createParticle();
  54911. this._particles.push(particle);
  54912. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  54913. if (this.startPositionFunction) {
  54914. this.startPositionFunction(worldMatrix, particle.position, particle);
  54915. }
  54916. else {
  54917. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  54918. }
  54919. if (this.startDirectionFunction) {
  54920. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54921. }
  54922. else {
  54923. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54924. }
  54925. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  54926. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  54927. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  54928. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  54929. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  54930. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  54931. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  54932. }
  54933. };
  54934. ParticleSystem.prototype._getEffect = function () {
  54935. if (this._customEffect) {
  54936. return this._customEffect;
  54937. }
  54938. ;
  54939. var defines = [];
  54940. if (this._scene.clipPlane) {
  54941. defines.push("#define CLIPPLANE");
  54942. }
  54943. if (this._isAnimationSheetEnabled) {
  54944. defines.push("#define ANIMATESHEET");
  54945. }
  54946. // Effect
  54947. var join = defines.join("\n");
  54948. if (this._cachedDefines !== join) {
  54949. this._cachedDefines = join;
  54950. var attributesNamesOrOptions;
  54951. var effectCreationOption;
  54952. if (this._isAnimationSheetEnabled) {
  54953. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  54954. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  54955. }
  54956. else {
  54957. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  54958. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  54959. }
  54960. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  54961. }
  54962. return this._effect;
  54963. };
  54964. /**
  54965. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  54966. */
  54967. ParticleSystem.prototype.animate = function () {
  54968. if (!this._started)
  54969. return;
  54970. var effect = this._getEffect();
  54971. // Check
  54972. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  54973. return;
  54974. if (this._currentRenderId === this._scene.getRenderId()) {
  54975. return;
  54976. }
  54977. this._currentRenderId = this._scene.getRenderId();
  54978. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  54979. // determine the number of particles we need to create
  54980. var newParticles;
  54981. if (this.manualEmitCount > -1) {
  54982. newParticles = this.manualEmitCount;
  54983. this._newPartsExcess = 0;
  54984. this.manualEmitCount = 0;
  54985. }
  54986. else {
  54987. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  54988. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  54989. }
  54990. if (this._newPartsExcess > 1.0) {
  54991. newParticles += this._newPartsExcess >> 0;
  54992. this._newPartsExcess -= this._newPartsExcess >> 0;
  54993. }
  54994. this._alive = false;
  54995. if (!this._stopped) {
  54996. this._actualFrame += this._scaledUpdateSpeed;
  54997. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  54998. this.stop();
  54999. }
  55000. else {
  55001. newParticles = 0;
  55002. }
  55003. this._update(newParticles);
  55004. // Stopped?
  55005. if (this._stopped) {
  55006. if (!this._alive) {
  55007. this._started = false;
  55008. if (this.onAnimationEnd) {
  55009. this.onAnimationEnd();
  55010. }
  55011. if (this.disposeOnStop) {
  55012. this._scene._toBeDisposed.push(this);
  55013. }
  55014. }
  55015. }
  55016. // Animation sheet
  55017. if (this._isAnimationSheetEnabled) {
  55018. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55019. }
  55020. else {
  55021. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55022. }
  55023. // Update VBO
  55024. var offset = 0;
  55025. for (var index = 0; index < this._particles.length; index++) {
  55026. var particle = this._particles[index];
  55027. this._appendParticleVertexes(offset, particle);
  55028. offset += 4;
  55029. }
  55030. if (this._vertexBuffer) {
  55031. this._vertexBuffer.update(this._vertexData);
  55032. }
  55033. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55034. this.stop();
  55035. }
  55036. };
  55037. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55038. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55039. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55040. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55041. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55042. };
  55043. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55044. this._appendParticleVertex(offset++, particle, 0, 0);
  55045. this._appendParticleVertex(offset++, particle, 1, 0);
  55046. this._appendParticleVertex(offset++, particle, 1, 1);
  55047. this._appendParticleVertex(offset++, particle, 0, 1);
  55048. };
  55049. /**
  55050. * Rebuilds the particle system.
  55051. */
  55052. ParticleSystem.prototype.rebuild = function () {
  55053. this._createIndexBuffer();
  55054. if (this._vertexBuffer) {
  55055. this._vertexBuffer._rebuild();
  55056. }
  55057. };
  55058. /**
  55059. * Is this system ready to be used/rendered
  55060. * @return true if the system is ready
  55061. */
  55062. ParticleSystem.prototype.isReady = function () {
  55063. var effect = this._getEffect();
  55064. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55065. return false;
  55066. }
  55067. return true;
  55068. };
  55069. /**
  55070. * Renders the particle system in its current state.
  55071. * @returns the current number of particles
  55072. */
  55073. ParticleSystem.prototype.render = function () {
  55074. var effect = this._getEffect();
  55075. // Check
  55076. if (!this.isReady() || !this._particles.length) {
  55077. return 0;
  55078. }
  55079. var engine = this._scene.getEngine();
  55080. // Render
  55081. engine.enableEffect(effect);
  55082. engine.setState(false);
  55083. var viewMatrix = this._scene.getViewMatrix();
  55084. effect.setTexture("diffuseSampler", this.particleTexture);
  55085. effect.setMatrix("view", viewMatrix);
  55086. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55087. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55088. var baseSize = this.particleTexture.getBaseSize();
  55089. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55090. }
  55091. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55092. if (this._scene.clipPlane) {
  55093. var clipPlane = this._scene.clipPlane;
  55094. var invView = viewMatrix.clone();
  55095. invView.invert();
  55096. effect.setMatrix("invView", invView);
  55097. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55098. }
  55099. // VBOs
  55100. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55101. // Draw order
  55102. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55103. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55104. }
  55105. else {
  55106. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55107. }
  55108. if (this.forceDepthWrite) {
  55109. engine.setDepthWrite(true);
  55110. }
  55111. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55112. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55113. return this._particles.length;
  55114. };
  55115. /**
  55116. * Disposes the particle system and free the associated resources
  55117. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55118. */
  55119. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55120. if (disposeTexture === void 0) { disposeTexture = true; }
  55121. if (this._vertexBuffer) {
  55122. this._vertexBuffer.dispose();
  55123. this._vertexBuffer = null;
  55124. }
  55125. if (this._indexBuffer) {
  55126. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55127. this._indexBuffer = null;
  55128. }
  55129. if (disposeTexture && this.particleTexture) {
  55130. this.particleTexture.dispose();
  55131. this.particleTexture = null;
  55132. }
  55133. this._removeFromRoot();
  55134. // Remove from scene
  55135. var index = this._scene.particleSystems.indexOf(this);
  55136. if (index > -1) {
  55137. this._scene.particleSystems.splice(index, 1);
  55138. }
  55139. // Callback
  55140. this.onDisposeObservable.notifyObservers(this);
  55141. this.onDisposeObservable.clear();
  55142. };
  55143. /**
  55144. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55145. * @param radius The radius of the sphere to emit from
  55146. * @returns the emitter
  55147. */
  55148. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55149. if (radius === void 0) { radius = 1; }
  55150. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55151. this.particleEmitterType = particleEmitter;
  55152. return particleEmitter;
  55153. };
  55154. /**
  55155. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55156. * @param radius The radius of the sphere to emit from
  55157. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55158. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55159. * @returns the emitter
  55160. */
  55161. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55162. if (radius === void 0) { radius = 1; }
  55163. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55164. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55165. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55166. this.particleEmitterType = particleEmitter;
  55167. return particleEmitter;
  55168. };
  55169. /**
  55170. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55171. * @param radius The radius of the cone to emit from
  55172. * @param angle The base angle of the cone
  55173. * @returns the emitter
  55174. */
  55175. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55176. if (radius === void 0) { radius = 1; }
  55177. if (angle === void 0) { angle = Math.PI / 4; }
  55178. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55179. this.particleEmitterType = particleEmitter;
  55180. return particleEmitter;
  55181. };
  55182. // 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.
  55183. /**
  55184. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55185. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55186. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55187. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55188. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55189. * @returns the emitter
  55190. */
  55191. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55192. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55193. this.particleEmitterType = particleEmitter;
  55194. this.direction1 = direction1;
  55195. this.direction2 = direction2;
  55196. this.minEmitBox = minEmitBox;
  55197. this.maxEmitBox = maxEmitBox;
  55198. return particleEmitter;
  55199. };
  55200. // Clone
  55201. /**
  55202. * Clones the particle system.
  55203. * @param name The name of the cloned object
  55204. * @param newEmitter The new emitter to use
  55205. * @returns the cloned particle system
  55206. */
  55207. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55208. var custom = null;
  55209. var program = null;
  55210. if (this.customShader != null) {
  55211. program = this.customShader;
  55212. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55213. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55214. }
  55215. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55216. result.customShader = program;
  55217. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55218. if (newEmitter === undefined) {
  55219. newEmitter = this.emitter;
  55220. }
  55221. result.emitter = newEmitter;
  55222. if (this.particleTexture) {
  55223. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55224. }
  55225. if (!this.preventAutoStart) {
  55226. result.start();
  55227. }
  55228. return result;
  55229. };
  55230. /**
  55231. * Serializes the particle system to a JSON object.
  55232. * @returns the JSON object
  55233. */
  55234. ParticleSystem.prototype.serialize = function () {
  55235. var serializationObject = {};
  55236. serializationObject.name = this.name;
  55237. serializationObject.id = this.id;
  55238. // Emitter
  55239. if (this.emitter.position) {
  55240. var emitterMesh = this.emitter;
  55241. serializationObject.emitterId = emitterMesh.id;
  55242. }
  55243. else {
  55244. var emitterPosition = this.emitter;
  55245. serializationObject.emitter = emitterPosition.asArray();
  55246. }
  55247. serializationObject.capacity = this.getCapacity();
  55248. if (this.particleTexture) {
  55249. serializationObject.textureName = this.particleTexture.name;
  55250. }
  55251. // Animations
  55252. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55253. // Particle system
  55254. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55255. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55256. serializationObject.minSize = this.minSize;
  55257. serializationObject.maxSize = this.maxSize;
  55258. serializationObject.minEmitPower = this.minEmitPower;
  55259. serializationObject.maxEmitPower = this.maxEmitPower;
  55260. serializationObject.minLifeTime = this.minLifeTime;
  55261. serializationObject.maxLifeTime = this.maxLifeTime;
  55262. serializationObject.emitRate = this.emitRate;
  55263. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55264. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55265. serializationObject.gravity = this.gravity.asArray();
  55266. serializationObject.direction1 = this.direction1.asArray();
  55267. serializationObject.direction2 = this.direction2.asArray();
  55268. serializationObject.color1 = this.color1.asArray();
  55269. serializationObject.color2 = this.color2.asArray();
  55270. serializationObject.colorDead = this.colorDead.asArray();
  55271. serializationObject.updateSpeed = this.updateSpeed;
  55272. serializationObject.targetStopDuration = this.targetStopDuration;
  55273. serializationObject.textureMask = this.textureMask.asArray();
  55274. serializationObject.blendMode = this.blendMode;
  55275. serializationObject.customShader = this.customShader;
  55276. serializationObject.preventAutoStart = this.preventAutoStart;
  55277. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55278. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55279. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55280. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55281. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55282. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55283. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55284. // Emitter
  55285. if (this.particleEmitterType) {
  55286. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55287. }
  55288. return serializationObject;
  55289. };
  55290. /**
  55291. * Parses a JSON object to create a particle system.
  55292. * @param parsedParticleSystem The JSON object to parse
  55293. * @param scene The scene to create the particle system in
  55294. * @param rootUrl The root url to use to load external dependencies like texture
  55295. * @returns the Parsed particle system
  55296. */
  55297. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55298. var name = parsedParticleSystem.name;
  55299. var custom = null;
  55300. var program = null;
  55301. if (parsedParticleSystem.customShader) {
  55302. program = parsedParticleSystem.customShader;
  55303. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55304. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55305. }
  55306. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55307. particleSystem.customShader = program;
  55308. if (parsedParticleSystem.id) {
  55309. particleSystem.id = parsedParticleSystem.id;
  55310. }
  55311. // Auto start
  55312. if (parsedParticleSystem.preventAutoStart) {
  55313. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55314. }
  55315. // Texture
  55316. if (parsedParticleSystem.textureName) {
  55317. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55318. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55319. }
  55320. // Emitter
  55321. if (parsedParticleSystem.emitterId) {
  55322. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55323. }
  55324. else {
  55325. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55326. }
  55327. // Animations
  55328. if (parsedParticleSystem.animations) {
  55329. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55330. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55331. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55332. }
  55333. }
  55334. if (parsedParticleSystem.autoAnimate) {
  55335. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55336. }
  55337. // Particle system
  55338. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55339. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55340. particleSystem.minSize = parsedParticleSystem.minSize;
  55341. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55342. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55343. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55344. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55345. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55346. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55347. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55348. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55349. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55350. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55351. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55352. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55353. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55354. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55355. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55356. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55357. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55358. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55359. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55360. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55361. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55362. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55363. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55364. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55365. if (!particleSystem.preventAutoStart) {
  55366. particleSystem.start();
  55367. }
  55368. return particleSystem;
  55369. };
  55370. /**
  55371. * Source color is added to the destination color without alpha affecting the result.
  55372. */
  55373. ParticleSystem.BLENDMODE_ONEONE = 0;
  55374. /**
  55375. * Blend current color and particle color using particle’s alpha.
  55376. */
  55377. ParticleSystem.BLENDMODE_STANDARD = 1;
  55378. return ParticleSystem;
  55379. }());
  55380. BABYLON.ParticleSystem = ParticleSystem;
  55381. })(BABYLON || (BABYLON = {}));
  55382. //# sourceMappingURL=babylon.particleSystem.js.map
  55383. "use strict";
  55384. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55385. "use strict";
  55386. var BABYLON;
  55387. (function (BABYLON) {
  55388. /**
  55389. * Particle emitter emitting particles from the inside of a box.
  55390. * It emits the particles randomly between 2 given directions.
  55391. */
  55392. var BoxParticleEmitter = /** @class */ (function () {
  55393. /**
  55394. * Creates a new instance BoxParticleEmitter
  55395. */
  55396. function BoxParticleEmitter() {
  55397. /**
  55398. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55399. */
  55400. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55401. /**
  55402. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55403. */
  55404. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55405. /**
  55406. * 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.
  55407. */
  55408. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  55409. /**
  55410. * 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.
  55411. */
  55412. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55413. }
  55414. /**
  55415. * Called by the particle System when the direction is computed for the created particle.
  55416. * @param emitPower is the power of the particle (speed)
  55417. * @param worldMatrix is the world matrix of the particle system
  55418. * @param directionToUpdate is the direction vector to update with the result
  55419. * @param particle is the particle we are computed the direction for
  55420. */
  55421. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55422. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55423. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55424. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55425. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55426. };
  55427. /**
  55428. * Called by the particle System when the position is computed for the created particle.
  55429. * @param worldMatrix is the world matrix of the particle system
  55430. * @param positionToUpdate is the position vector to update with the result
  55431. * @param particle is the particle we are computed the position for
  55432. */
  55433. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55434. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55435. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55436. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55437. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55438. };
  55439. /**
  55440. * Clones the current emitter and returns a copy of it
  55441. * @returns the new emitter
  55442. */
  55443. BoxParticleEmitter.prototype.clone = function () {
  55444. var newOne = new BoxParticleEmitter();
  55445. BABYLON.Tools.DeepCopy(this, newOne);
  55446. return newOne;
  55447. };
  55448. /**
  55449. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55450. * @param effect defines the update shader
  55451. */
  55452. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55453. effect.setVector3("direction1", this.direction1);
  55454. effect.setVector3("direction2", this.direction2);
  55455. effect.setVector3("minEmitBox", this.minEmitBox);
  55456. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55457. };
  55458. /**
  55459. * Returns a string to use to update the GPU particles update shader
  55460. * @returns a string containng the defines string
  55461. */
  55462. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55463. return "#define BOXEMITTER";
  55464. };
  55465. /**
  55466. * Returns the string "BoxEmitter"
  55467. * @returns a string containing the class name
  55468. */
  55469. BoxParticleEmitter.prototype.getClassName = function () {
  55470. return "BoxEmitter";
  55471. };
  55472. /**
  55473. * Serializes the particle system to a JSON object.
  55474. * @returns the JSON object
  55475. */
  55476. BoxParticleEmitter.prototype.serialize = function () {
  55477. var serializationObject = {};
  55478. serializationObject.type = this.getClassName();
  55479. serializationObject.direction1 = this.direction1.asArray();
  55480. ;
  55481. serializationObject.direction2 = this.direction2.asArray();
  55482. ;
  55483. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55484. ;
  55485. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55486. ;
  55487. return serializationObject;
  55488. };
  55489. /**
  55490. * Parse properties from a JSON object
  55491. * @param serializationObject defines the JSON object
  55492. */
  55493. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  55494. this.direction1.copyFrom(serializationObject.direction1);
  55495. this.direction2.copyFrom(serializationObject.direction2);
  55496. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  55497. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  55498. };
  55499. return BoxParticleEmitter;
  55500. }());
  55501. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  55502. })(BABYLON || (BABYLON = {}));
  55503. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  55504. "use strict";
  55505. var BABYLON;
  55506. (function (BABYLON) {
  55507. /**
  55508. * Particle emitter emitting particles from the inside of a cone.
  55509. * It emits the particles alongside the cone volume from the base to the particle.
  55510. * The emission direction might be randomized.
  55511. */
  55512. var ConeParticleEmitter = /** @class */ (function () {
  55513. /**
  55514. * Creates a new instance ConeParticleEmitter
  55515. * @param radius the radius of the emission cone (1 by default)
  55516. * @param angles the cone base angle (PI by default)
  55517. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55518. */
  55519. function ConeParticleEmitter(radius,
  55520. /**
  55521. * The radius of the emission cone.
  55522. */
  55523. angle,
  55524. /**
  55525. * The cone base angle.
  55526. */
  55527. directionRandomizer) {
  55528. if (radius === void 0) { radius = 1; }
  55529. if (angle === void 0) { angle = Math.PI; }
  55530. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55531. this.angle = angle;
  55532. this.directionRandomizer = directionRandomizer;
  55533. this.radius = radius;
  55534. }
  55535. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  55536. /**
  55537. * Gets the radius of the emission cone.
  55538. */
  55539. get: function () {
  55540. return this._radius;
  55541. },
  55542. /**
  55543. * Sets the radius of the emission cone.
  55544. */
  55545. set: function (value) {
  55546. this._radius = value;
  55547. if (this.angle !== 0) {
  55548. this._height = value / Math.tan(this.angle / 2);
  55549. }
  55550. else {
  55551. this._height = 1;
  55552. }
  55553. },
  55554. enumerable: true,
  55555. configurable: true
  55556. });
  55557. /**
  55558. * Called by the particle System when the direction is computed for the created particle.
  55559. * @param emitPower is the power of the particle (speed)
  55560. * @param worldMatrix is the world matrix of the particle system
  55561. * @param directionToUpdate is the direction vector to update with the result
  55562. * @param particle is the particle we are computed the direction for
  55563. */
  55564. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55565. if (this.angle === 0) {
  55566. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  55567. }
  55568. else {
  55569. // measure the direction Vector from the emitter to the particle.
  55570. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55571. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55572. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55573. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55574. direction.x += randX;
  55575. direction.y += randY;
  55576. direction.z += randZ;
  55577. direction.normalize();
  55578. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55579. }
  55580. };
  55581. /**
  55582. * Called by the particle System when the position is computed for the created particle.
  55583. * @param worldMatrix is the world matrix of the particle system
  55584. * @param positionToUpdate is the position vector to update with the result
  55585. * @param particle is the particle we are computed the position for
  55586. */
  55587. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55588. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  55589. var h = BABYLON.Scalar.RandomRange(0, 1);
  55590. // Better distribution in a cone at normal angles.
  55591. h = 1 - h * h;
  55592. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  55593. radius = radius * h;
  55594. var randX = radius * Math.sin(s);
  55595. var randZ = radius * Math.cos(s);
  55596. var randY = h * this._height;
  55597. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55598. };
  55599. /**
  55600. * Clones the current emitter and returns a copy of it
  55601. * @returns the new emitter
  55602. */
  55603. ConeParticleEmitter.prototype.clone = function () {
  55604. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  55605. BABYLON.Tools.DeepCopy(this, newOne);
  55606. return newOne;
  55607. };
  55608. /**
  55609. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55610. * @param effect defines the update shader
  55611. */
  55612. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  55613. effect.setFloat("radius", this.radius);
  55614. effect.setFloat("angle", this.angle);
  55615. effect.setFloat("height", this._height);
  55616. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55617. };
  55618. /**
  55619. * Returns a string to use to update the GPU particles update shader
  55620. * @returns a string containng the defines string
  55621. */
  55622. ConeParticleEmitter.prototype.getEffectDefines = function () {
  55623. return "#define CONEEMITTER";
  55624. };
  55625. /**
  55626. * Returns the string "BoxEmitter"
  55627. * @returns a string containing the class name
  55628. */
  55629. ConeParticleEmitter.prototype.getClassName = function () {
  55630. return "ConeEmitter";
  55631. };
  55632. /**
  55633. * Serializes the particle system to a JSON object.
  55634. * @returns the JSON object
  55635. */
  55636. ConeParticleEmitter.prototype.serialize = function () {
  55637. var serializationObject = {};
  55638. serializationObject.type = this.getClassName();
  55639. serializationObject.radius = this.radius;
  55640. serializationObject.angle = this.angle;
  55641. serializationObject.directionRandomizer = this.directionRandomizer;
  55642. return serializationObject;
  55643. };
  55644. /**
  55645. * Parse properties from a JSON object
  55646. * @param serializationObject defines the JSON object
  55647. */
  55648. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  55649. this.radius = serializationObject.radius;
  55650. this.angle = serializationObject.angle;
  55651. this.directionRandomizer = serializationObject.directionRandomizer;
  55652. };
  55653. return ConeParticleEmitter;
  55654. }());
  55655. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  55656. })(BABYLON || (BABYLON = {}));
  55657. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  55658. "use strict";
  55659. var BABYLON;
  55660. (function (BABYLON) {
  55661. /**
  55662. * Particle emitter emitting particles from the inside of a sphere.
  55663. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  55664. */
  55665. var SphereParticleEmitter = /** @class */ (function () {
  55666. /**
  55667. * Creates a new instance SphereParticleEmitter
  55668. * @param radius the radius of the emission sphere (1 by default)
  55669. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55670. */
  55671. function SphereParticleEmitter(
  55672. /**
  55673. * The radius of the emission sphere.
  55674. */
  55675. radius,
  55676. /**
  55677. * How much to randomize the particle direction [0-1].
  55678. */
  55679. directionRandomizer) {
  55680. if (radius === void 0) { radius = 1; }
  55681. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55682. this.radius = radius;
  55683. this.directionRandomizer = directionRandomizer;
  55684. }
  55685. /**
  55686. * Called by the particle System when the direction is computed for the created particle.
  55687. * @param emitPower is the power of the particle (speed)
  55688. * @param worldMatrix is the world matrix of the particle system
  55689. * @param directionToUpdate is the direction vector to update with the result
  55690. * @param particle is the particle we are computed the direction for
  55691. */
  55692. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55693. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55694. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55695. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55696. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55697. direction.x += randX;
  55698. direction.y += randY;
  55699. direction.z += randZ;
  55700. direction.normalize();
  55701. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55702. };
  55703. /**
  55704. * Called by the particle System when the position is computed for the created particle.
  55705. * @param worldMatrix is the world matrix of the particle system
  55706. * @param positionToUpdate is the position vector to update with the result
  55707. * @param particle is the particle we are computed the position for
  55708. */
  55709. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55710. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  55711. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  55712. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  55713. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  55714. var randY = randRadius * Math.cos(theta);
  55715. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  55716. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55717. };
  55718. /**
  55719. * Clones the current emitter and returns a copy of it
  55720. * @returns the new emitter
  55721. */
  55722. SphereParticleEmitter.prototype.clone = function () {
  55723. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  55724. BABYLON.Tools.DeepCopy(this, newOne);
  55725. return newOne;
  55726. };
  55727. /**
  55728. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55729. * @param effect defines the update shader
  55730. */
  55731. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  55732. effect.setFloat("radius", this.radius);
  55733. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55734. };
  55735. /**
  55736. * Returns a string to use to update the GPU particles update shader
  55737. * @returns a string containng the defines string
  55738. */
  55739. SphereParticleEmitter.prototype.getEffectDefines = function () {
  55740. return "#define SPHEREEMITTER";
  55741. };
  55742. /**
  55743. * Returns the string "SphereParticleEmitter"
  55744. * @returns a string containing the class name
  55745. */
  55746. SphereParticleEmitter.prototype.getClassName = function () {
  55747. return "SphereParticleEmitter";
  55748. };
  55749. /**
  55750. * Serializes the particle system to a JSON object.
  55751. * @returns the JSON object
  55752. */
  55753. SphereParticleEmitter.prototype.serialize = function () {
  55754. var serializationObject = {};
  55755. serializationObject.type = this.getClassName();
  55756. serializationObject.radius = this.radius;
  55757. serializationObject.directionRandomizer = this.directionRandomizer;
  55758. return serializationObject;
  55759. };
  55760. /**
  55761. * Parse properties from a JSON object
  55762. * @param serializationObject defines the JSON object
  55763. */
  55764. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  55765. this.radius = serializationObject.radius;
  55766. this.directionRandomizer = serializationObject.directionRandomizer;
  55767. };
  55768. return SphereParticleEmitter;
  55769. }());
  55770. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  55771. /**
  55772. * Particle emitter emitting particles from the inside of a sphere.
  55773. * It emits the particles randomly between two vectors.
  55774. */
  55775. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  55776. __extends(SphereDirectedParticleEmitter, _super);
  55777. /**
  55778. * Creates a new instance SphereDirectedParticleEmitter
  55779. * @param radius the radius of the emission sphere (1 by default)
  55780. * @param direction1 the min limit of the emission direction (up vector by default)
  55781. * @param direction2 the max limit of the emission direction (up vector by default)
  55782. */
  55783. function SphereDirectedParticleEmitter(radius,
  55784. /**
  55785. * The min limit of the emission direction.
  55786. */
  55787. direction1,
  55788. /**
  55789. * The max limit of the emission direction.
  55790. */
  55791. direction2) {
  55792. if (radius === void 0) { radius = 1; }
  55793. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  55794. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  55795. var _this = _super.call(this, radius) || this;
  55796. _this.direction1 = direction1;
  55797. _this.direction2 = direction2;
  55798. return _this;
  55799. }
  55800. /**
  55801. * Called by the particle System when the direction is computed for the created particle.
  55802. * @param emitPower is the power of the particle (speed)
  55803. * @param worldMatrix is the world matrix of the particle system
  55804. * @param directionToUpdate is the direction vector to update with the result
  55805. * @param particle is the particle we are computed the direction for
  55806. */
  55807. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55808. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55809. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55810. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55811. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55812. };
  55813. /**
  55814. * Clones the current emitter and returns a copy of it
  55815. * @returns the new emitter
  55816. */
  55817. SphereDirectedParticleEmitter.prototype.clone = function () {
  55818. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  55819. BABYLON.Tools.DeepCopy(this, newOne);
  55820. return newOne;
  55821. };
  55822. /**
  55823. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55824. * @param effect defines the update shader
  55825. */
  55826. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  55827. effect.setFloat("radius", this.radius);
  55828. effect.setVector3("direction1", this.direction1);
  55829. effect.setVector3("direction2", this.direction2);
  55830. };
  55831. /**
  55832. * Returns a string to use to update the GPU particles update shader
  55833. * @returns a string containng the defines string
  55834. */
  55835. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  55836. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  55837. };
  55838. /**
  55839. * Returns the string "SphereDirectedParticleEmitter"
  55840. * @returns a string containing the class name
  55841. */
  55842. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  55843. return "SphereDirectedParticleEmitter";
  55844. };
  55845. /**
  55846. * Serializes the particle system to a JSON object.
  55847. * @returns the JSON object
  55848. */
  55849. SphereDirectedParticleEmitter.prototype.serialize = function () {
  55850. var serializationObject = _super.prototype.serialize.call(this);
  55851. ;
  55852. serializationObject.direction1 = this.direction1.asArray();
  55853. ;
  55854. serializationObject.direction2 = this.direction2.asArray();
  55855. ;
  55856. return serializationObject;
  55857. };
  55858. /**
  55859. * Parse properties from a JSON object
  55860. * @param serializationObject defines the JSON object
  55861. */
  55862. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  55863. _super.prototype.parse.call(this, serializationObject);
  55864. this.direction1.copyFrom(serializationObject.direction1);
  55865. this.direction2.copyFrom(serializationObject.direction2);
  55866. };
  55867. return SphereDirectedParticleEmitter;
  55868. }(SphereParticleEmitter));
  55869. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  55870. })(BABYLON || (BABYLON = {}));
  55871. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  55872. "use strict";
  55873. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55874. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55875. s = arguments[i];
  55876. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55877. t[p] = s[p];
  55878. }
  55879. return t;
  55880. };
  55881. var BABYLON;
  55882. (function (BABYLON) {
  55883. /**
  55884. * This represents a GPU particle system in Babylon
  55885. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  55886. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  55887. */
  55888. var GPUParticleSystem = /** @class */ (function () {
  55889. /**
  55890. * Instantiates a GPU particle system.
  55891. * 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.
  55892. * @param name The name of the particle system
  55893. * @param capacity The max number of particles alive at the same time
  55894. * @param scene The scene the particle system belongs to
  55895. */
  55896. function GPUParticleSystem(name, options, scene) {
  55897. /**
  55898. * The emitter represents the Mesh or position we are attaching the particle system to.
  55899. */
  55900. this.emitter = null;
  55901. /**
  55902. * The rendering group used by the Particle system to chose when to render.
  55903. */
  55904. this.renderingGroupId = 0;
  55905. /**
  55906. * The layer mask we are rendering the particles through.
  55907. */
  55908. this.layerMask = 0x0FFFFFFF;
  55909. this._targetIndex = 0;
  55910. this._currentRenderId = -1;
  55911. this._started = false;
  55912. this._stopped = false;
  55913. this._timeDelta = 0;
  55914. this._attributesStrideSize = 14;
  55915. this._actualFrame = 0;
  55916. /**
  55917. * List of animations used by the particle system.
  55918. */
  55919. this.animations = [];
  55920. /**
  55921. * An event triggered when the system is disposed.
  55922. */
  55923. this.onDisposeObservable = new BABYLON.Observable();
  55924. /**
  55925. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55926. */
  55927. this.updateSpeed = 0.01;
  55928. /**
  55929. * The amount of time the particle system is running (depends of the overall update speed).
  55930. */
  55931. this.targetStopDuration = 0;
  55932. /**
  55933. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55934. */
  55935. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55936. /**
  55937. * Minimum life time of emitting particles.
  55938. */
  55939. this.minLifeTime = 1;
  55940. /**
  55941. * Maximum life time of emitting particles.
  55942. */
  55943. this.maxLifeTime = 1;
  55944. /**
  55945. * Minimum Size of emitting particles.
  55946. */
  55947. this.minSize = 1;
  55948. /**
  55949. * Maximum Size of emitting particles.
  55950. */
  55951. this.maxSize = 1;
  55952. /**
  55953. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55954. */
  55955. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55956. /**
  55957. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55958. */
  55959. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55960. /**
  55961. * Color the particle will have at the end of its lifetime.
  55962. */
  55963. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  55964. /**
  55965. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  55966. */
  55967. this.emitRate = 100;
  55968. /**
  55969. * You can use gravity if you want to give an orientation to your particles.
  55970. */
  55971. this.gravity = BABYLON.Vector3.Zero();
  55972. /**
  55973. * Minimum power of emitting particles.
  55974. */
  55975. this.minEmitPower = 1;
  55976. /**
  55977. * Maximum power of emitting particles.
  55978. */
  55979. this.maxEmitPower = 1;
  55980. /**
  55981. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55982. * to override the particles.
  55983. */
  55984. this.forceDepthWrite = false;
  55985. this.id = name;
  55986. this.name = name;
  55987. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55988. this._engine = this._scene.getEngine();
  55989. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  55990. this._capacity = fullOptions.capacity;
  55991. this._activeCount = fullOptions.capacity;
  55992. this._currentActiveCount = 0;
  55993. this._scene.particleSystems.push(this);
  55994. this._updateEffectOptions = {
  55995. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  55996. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  55997. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  55998. uniformBuffersNames: [],
  55999. samplers: ["randomSampler"],
  56000. defines: "",
  56001. fallbacks: null,
  56002. onCompiled: null,
  56003. onError: null,
  56004. indexParameters: null,
  56005. maxSimultaneousLights: 0,
  56006. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  56007. };
  56008. // Random data
  56009. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56010. var d = [];
  56011. for (var i = 0; i < maxTextureSize; ++i) {
  56012. d.push(Math.random());
  56013. d.push(Math.random());
  56014. d.push(Math.random());
  56015. d.push(Math.random());
  56016. }
  56017. 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);
  56018. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56019. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56020. this._randomTextureSize = maxTextureSize;
  56021. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56022. }
  56023. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56024. /**
  56025. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56026. */
  56027. get: function () {
  56028. if (!BABYLON.Engine.LastCreatedEngine) {
  56029. return false;
  56030. }
  56031. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56032. },
  56033. enumerable: true,
  56034. configurable: true
  56035. });
  56036. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56037. /**
  56038. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56039. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56040. */
  56041. get: function () {
  56042. if (this.particleEmitterType.direction1) {
  56043. return this.particleEmitterType.direction1;
  56044. }
  56045. return BABYLON.Vector3.Zero();
  56046. },
  56047. set: function (value) {
  56048. if (this.particleEmitterType.direction1) {
  56049. this.particleEmitterType.direction1 = value;
  56050. }
  56051. },
  56052. enumerable: true,
  56053. configurable: true
  56054. });
  56055. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56056. /**
  56057. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56058. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56059. */
  56060. get: function () {
  56061. if (this.particleEmitterType.direction2) {
  56062. return this.particleEmitterType.direction2;
  56063. }
  56064. return BABYLON.Vector3.Zero();
  56065. },
  56066. set: function (value) {
  56067. if (this.particleEmitterType.direction2) {
  56068. this.particleEmitterType.direction2 = value;
  56069. }
  56070. },
  56071. enumerable: true,
  56072. configurable: true
  56073. });
  56074. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56075. /**
  56076. * 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.
  56077. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56078. */
  56079. get: function () {
  56080. if (this.particleEmitterType.minEmitBox) {
  56081. return this.particleEmitterType.minEmitBox;
  56082. }
  56083. return BABYLON.Vector3.Zero();
  56084. },
  56085. set: function (value) {
  56086. if (this.particleEmitterType.minEmitBox) {
  56087. this.particleEmitterType.minEmitBox = value;
  56088. }
  56089. },
  56090. enumerable: true,
  56091. configurable: true
  56092. });
  56093. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56094. /**
  56095. * 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.
  56096. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56097. */
  56098. get: function () {
  56099. if (this.particleEmitterType.maxEmitBox) {
  56100. return this.particleEmitterType.maxEmitBox;
  56101. }
  56102. return BABYLON.Vector3.Zero();
  56103. },
  56104. set: function (value) {
  56105. if (this.particleEmitterType.maxEmitBox) {
  56106. this.particleEmitterType.maxEmitBox = value;
  56107. }
  56108. },
  56109. enumerable: true,
  56110. configurable: true
  56111. });
  56112. /**
  56113. * Gets the maximum number of particles active at the same time.
  56114. * @returns The max number of active particles.
  56115. */
  56116. GPUParticleSystem.prototype.getCapacity = function () {
  56117. return this._capacity;
  56118. };
  56119. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56120. /**
  56121. * Gets or set the number of active particles
  56122. */
  56123. get: function () {
  56124. return this._activeCount;
  56125. },
  56126. set: function (value) {
  56127. this._activeCount = Math.min(value, this._capacity);
  56128. },
  56129. enumerable: true,
  56130. configurable: true
  56131. });
  56132. /**
  56133. * Is this system ready to be used/rendered
  56134. * @return true if the system is ready
  56135. */
  56136. GPUParticleSystem.prototype.isReady = function () {
  56137. if (!this._updateEffect) {
  56138. this._recreateUpdateEffect();
  56139. this._recreateRenderEffect();
  56140. return false;
  56141. }
  56142. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56143. return false;
  56144. }
  56145. return true;
  56146. };
  56147. /**
  56148. * Gets Wether the system has been started.
  56149. * @returns True if it has been started, otherwise false.
  56150. */
  56151. GPUParticleSystem.prototype.isStarted = function () {
  56152. return this._started;
  56153. };
  56154. /**
  56155. * Starts the particle system and begins to emit.
  56156. */
  56157. GPUParticleSystem.prototype.start = function () {
  56158. this._started = true;
  56159. this._stopped = false;
  56160. };
  56161. /**
  56162. * Stops the particle system.
  56163. */
  56164. GPUParticleSystem.prototype.stop = function () {
  56165. this._stopped = true;
  56166. };
  56167. /**
  56168. * Remove all active particles
  56169. */
  56170. GPUParticleSystem.prototype.reset = function () {
  56171. this._releaseBuffers();
  56172. this._releaseVAOs();
  56173. this._currentActiveCount = 0;
  56174. this._targetIndex = 0;
  56175. };
  56176. /**
  56177. * Returns the string "GPUParticleSystem"
  56178. * @returns a string containing the class name
  56179. */
  56180. GPUParticleSystem.prototype.getClassName = function () {
  56181. return "GPUParticleSystem";
  56182. };
  56183. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56184. var updateVertexBuffers = {};
  56185. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56186. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56187. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56188. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56189. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  56190. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  56191. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  56192. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56193. this._engine.bindArrayBuffer(null);
  56194. return vao;
  56195. };
  56196. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56197. var renderVertexBuffers = {};
  56198. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56199. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56200. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56201. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  56202. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  56203. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56204. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56205. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56206. this._engine.bindArrayBuffer(null);
  56207. return vao;
  56208. };
  56209. GPUParticleSystem.prototype._initialize = function (force) {
  56210. if (force === void 0) { force = false; }
  56211. if (this._buffer0 && !force) {
  56212. return;
  56213. }
  56214. var engine = this._scene.getEngine();
  56215. var data = new Array();
  56216. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56217. // position
  56218. data.push(0.0);
  56219. data.push(0.0);
  56220. data.push(0.0);
  56221. // Age and life
  56222. data.push(0.0); // create the particle as a dead one to create a new one at start
  56223. data.push(0.0);
  56224. // Seed
  56225. data.push(Math.random());
  56226. // Size
  56227. data.push(0.0);
  56228. // color
  56229. data.push(0.0);
  56230. data.push(0.0);
  56231. data.push(0.0);
  56232. data.push(0.0);
  56233. // direction
  56234. data.push(0.0);
  56235. data.push(0.0);
  56236. data.push(0.0);
  56237. }
  56238. // Sprite data
  56239. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56240. -0.5, 0.5, 0, 1,
  56241. -0.5, -0.5, 0, 0,
  56242. 0.5, -0.5, 1, 0]);
  56243. // Buffers
  56244. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56245. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56246. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56247. // Update VAO
  56248. this._updateVAO = [];
  56249. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56250. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56251. // Render VAO
  56252. this._renderVAO = [];
  56253. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56254. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56255. // Links
  56256. this._sourceBuffer = this._buffer0;
  56257. this._targetBuffer = this._buffer1;
  56258. };
  56259. /** @ignore */
  56260. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56261. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56262. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56263. return;
  56264. }
  56265. this._updateEffectOptions.defines = defines;
  56266. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56267. };
  56268. /** @ignore */
  56269. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56270. var defines = "";
  56271. if (this._scene.clipPlane) {
  56272. defines = "\n#define CLIPPLANE";
  56273. }
  56274. if (this._renderEffect && this._renderEffect.defines === defines) {
  56275. return;
  56276. }
  56277. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56278. };
  56279. /**
  56280. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56281. */
  56282. GPUParticleSystem.prototype.animate = function () {
  56283. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56284. this._actualFrame += this._timeDelta;
  56285. if (!this._stopped) {
  56286. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56287. this.stop();
  56288. }
  56289. }
  56290. };
  56291. /**
  56292. * Renders the particle system in its current state.
  56293. * @returns the current number of particles
  56294. */
  56295. GPUParticleSystem.prototype.render = function () {
  56296. if (!this._started) {
  56297. return 0;
  56298. }
  56299. this._recreateUpdateEffect();
  56300. this._recreateRenderEffect();
  56301. if (!this.isReady()) {
  56302. return 0;
  56303. }
  56304. if (this._currentRenderId === this._scene.getRenderId()) {
  56305. return 0;
  56306. }
  56307. this._currentRenderId = this._scene.getRenderId();
  56308. // Get everything ready to render
  56309. this._initialize();
  56310. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56311. // Enable update effect
  56312. this._engine.enableEffect(this._updateEffect);
  56313. this._engine.setState(false);
  56314. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56315. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56316. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56317. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56318. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56319. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56320. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56321. this._updateEffect.setDirectColor4("color1", this.color1);
  56322. this._updateEffect.setDirectColor4("color2", this.color2);
  56323. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56324. this._updateEffect.setVector3("gravity", this.gravity);
  56325. if (this.particleEmitterType) {
  56326. this.particleEmitterType.applyToShader(this._updateEffect);
  56327. }
  56328. var emitterWM;
  56329. if (this.emitter.position) {
  56330. var emitterMesh = this.emitter;
  56331. emitterWM = emitterMesh.getWorldMatrix();
  56332. }
  56333. else {
  56334. var emitterPosition = this.emitter;
  56335. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56336. }
  56337. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56338. // Bind source VAO
  56339. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56340. // Update
  56341. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56342. this._engine.setRasterizerState(false);
  56343. this._engine.beginTransformFeedback();
  56344. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56345. this._engine.endTransformFeedback();
  56346. this._engine.setRasterizerState(true);
  56347. this._engine.bindTransformFeedbackBuffer(null);
  56348. // Enable render effect
  56349. this._engine.enableEffect(this._renderEffect);
  56350. var viewMatrix = this._scene.getViewMatrix();
  56351. this._renderEffect.setMatrix("view", viewMatrix);
  56352. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56353. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56354. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56355. if (this._scene.clipPlane) {
  56356. var clipPlane = this._scene.clipPlane;
  56357. var invView = viewMatrix.clone();
  56358. invView.invert();
  56359. this._renderEffect.setMatrix("invView", invView);
  56360. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56361. }
  56362. // Draw order
  56363. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56364. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56365. }
  56366. else {
  56367. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56368. }
  56369. if (this.forceDepthWrite) {
  56370. this._engine.setDepthWrite(true);
  56371. }
  56372. // Bind source VAO
  56373. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56374. // Render
  56375. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56376. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56377. // Switch VAOs
  56378. this._targetIndex++;
  56379. if (this._targetIndex === 2) {
  56380. this._targetIndex = 0;
  56381. }
  56382. // Switch buffers
  56383. var tmpBuffer = this._sourceBuffer;
  56384. this._sourceBuffer = this._targetBuffer;
  56385. this._targetBuffer = tmpBuffer;
  56386. return this._currentActiveCount;
  56387. };
  56388. /**
  56389. * Rebuilds the particle system
  56390. */
  56391. GPUParticleSystem.prototype.rebuild = function () {
  56392. this._initialize(true);
  56393. };
  56394. GPUParticleSystem.prototype._releaseBuffers = function () {
  56395. if (this._buffer0) {
  56396. this._buffer0.dispose();
  56397. this._buffer0 = null;
  56398. }
  56399. if (this._buffer1) {
  56400. this._buffer1.dispose();
  56401. this._buffer1 = null;
  56402. }
  56403. if (this._spriteBuffer) {
  56404. this._spriteBuffer.dispose();
  56405. this._spriteBuffer = null;
  56406. }
  56407. };
  56408. GPUParticleSystem.prototype._releaseVAOs = function () {
  56409. if (!this._updateVAO) {
  56410. return;
  56411. }
  56412. for (var index = 0; index < this._updateVAO.length; index++) {
  56413. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56414. }
  56415. this._updateVAO = [];
  56416. for (var index = 0; index < this._renderVAO.length; index++) {
  56417. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56418. }
  56419. this._renderVAO = [];
  56420. };
  56421. /**
  56422. * Disposes the particle system and free the associated resources
  56423. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56424. */
  56425. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56426. if (disposeTexture === void 0) { disposeTexture = true; }
  56427. var index = this._scene.particleSystems.indexOf(this);
  56428. if (index > -1) {
  56429. this._scene.particleSystems.splice(index, 1);
  56430. }
  56431. this._releaseBuffers();
  56432. this._releaseVAOs();
  56433. if (this._randomTexture) {
  56434. this._randomTexture.dispose();
  56435. this._randomTexture = null;
  56436. }
  56437. if (disposeTexture && this.particleTexture) {
  56438. this.particleTexture.dispose();
  56439. this.particleTexture = null;
  56440. }
  56441. // Callback
  56442. this.onDisposeObservable.notifyObservers(this);
  56443. this.onDisposeObservable.clear();
  56444. };
  56445. /**
  56446. * Clones the particle system.
  56447. * @param name The name of the cloned object
  56448. * @param newEmitter The new emitter to use
  56449. * @returns the cloned particle system
  56450. */
  56451. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  56452. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  56453. BABYLON.Tools.DeepCopy(this, result);
  56454. if (newEmitter === undefined) {
  56455. newEmitter = this.emitter;
  56456. }
  56457. result.emitter = newEmitter;
  56458. if (this.particleTexture) {
  56459. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56460. }
  56461. return result;
  56462. };
  56463. /**
  56464. * Serializes the particle system to a JSON object.
  56465. * @returns the JSON object
  56466. */
  56467. GPUParticleSystem.prototype.serialize = function () {
  56468. var serializationObject = {};
  56469. serializationObject.name = this.name;
  56470. serializationObject.id = this.id;
  56471. // Emitter
  56472. if (this.emitter.position) {
  56473. var emitterMesh = this.emitter;
  56474. serializationObject.emitterId = emitterMesh.id;
  56475. }
  56476. else {
  56477. var emitterPosition = this.emitter;
  56478. serializationObject.emitter = emitterPosition.asArray();
  56479. }
  56480. serializationObject.capacity = this.getCapacity();
  56481. if (this.particleTexture) {
  56482. serializationObject.textureName = this.particleTexture.name;
  56483. }
  56484. // Animations
  56485. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56486. // Particle system
  56487. serializationObject.activeParticleCount = this.activeParticleCount;
  56488. serializationObject.randomTextureSize = this._randomTextureSize;
  56489. serializationObject.minSize = this.minSize;
  56490. serializationObject.maxSize = this.maxSize;
  56491. serializationObject.minEmitPower = this.minEmitPower;
  56492. serializationObject.maxEmitPower = this.maxEmitPower;
  56493. serializationObject.minLifeTime = this.minLifeTime;
  56494. serializationObject.maxLifeTime = this.maxLifeTime;
  56495. serializationObject.emitRate = this.emitRate;
  56496. serializationObject.gravity = this.gravity.asArray();
  56497. serializationObject.color1 = this.color1.asArray();
  56498. serializationObject.color2 = this.color2.asArray();
  56499. serializationObject.colorDead = this.colorDead.asArray();
  56500. serializationObject.updateSpeed = this.updateSpeed;
  56501. serializationObject.targetStopDuration = this.targetStopDuration;
  56502. serializationObject.blendMode = this.blendMode;
  56503. // Emitter
  56504. if (this.particleEmitterType) {
  56505. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56506. }
  56507. return serializationObject;
  56508. };
  56509. /**
  56510. * Parses a JSON object to create a GPU particle system.
  56511. * @param parsedParticleSystem The JSON object to parse
  56512. * @param scene The scene to create the particle system in
  56513. * @param rootUrl The root url to use to load external dependencies like texture
  56514. * @returns the parsed GPU particle system
  56515. */
  56516. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56517. var name = parsedParticleSystem.name;
  56518. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  56519. if (parsedParticleSystem.id) {
  56520. particleSystem.id = parsedParticleSystem.id;
  56521. }
  56522. // Texture
  56523. if (parsedParticleSystem.textureName) {
  56524. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56525. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56526. }
  56527. // Emitter
  56528. if (parsedParticleSystem.emitterId) {
  56529. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56530. }
  56531. else {
  56532. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56533. }
  56534. // Animations
  56535. if (parsedParticleSystem.animations) {
  56536. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56537. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56538. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56539. }
  56540. }
  56541. // Particle system
  56542. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  56543. particleSystem.minSize = parsedParticleSystem.minSize;
  56544. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56545. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56546. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56547. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56548. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56549. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56550. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56551. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56552. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56553. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56554. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56555. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56556. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56557. // Emitter
  56558. if (parsedParticleSystem.particleEmitterType) {
  56559. var emitterType = void 0;
  56560. switch (parsedParticleSystem.particleEmitterType.type) {
  56561. case "SphereEmitter":
  56562. emitterType = new BABYLON.SphereParticleEmitter();
  56563. break;
  56564. case "SphereDirectedParticleEmitter":
  56565. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56566. break;
  56567. case "ConeEmitter":
  56568. emitterType = new BABYLON.ConeParticleEmitter();
  56569. break;
  56570. case "BoxEmitter":
  56571. default:
  56572. emitterType = new BABYLON.BoxParticleEmitter();
  56573. break;
  56574. }
  56575. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56576. particleSystem.particleEmitterType = emitterType;
  56577. }
  56578. return particleSystem;
  56579. };
  56580. return GPUParticleSystem;
  56581. }());
  56582. BABYLON.GPUParticleSystem = GPUParticleSystem;
  56583. })(BABYLON || (BABYLON = {}));
  56584. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  56585. "use strict";
  56586. var BABYLON;
  56587. (function (BABYLON) {
  56588. /**
  56589. * Represents one particle of a solid particle system.
  56590. */
  56591. var SolidParticle = /** @class */ (function () {
  56592. /**
  56593. * Creates a Solid Particle object.
  56594. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  56595. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  56596. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  56597. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  56598. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  56599. * @param shapeId (integer) is the model shape identifier in the SPS.
  56600. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  56601. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  56602. */
  56603. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  56604. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  56605. /**
  56606. * particle global index
  56607. */
  56608. this.idx = 0;
  56609. /**
  56610. * The color of the particle
  56611. */
  56612. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56613. /**
  56614. * The world space position of the particle.
  56615. */
  56616. this.position = BABYLON.Vector3.Zero();
  56617. /**
  56618. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  56619. */
  56620. this.rotation = BABYLON.Vector3.Zero();
  56621. /**
  56622. * The scaling of the particle.
  56623. */
  56624. this.scaling = BABYLON.Vector3.One();
  56625. /**
  56626. * The uvs of the particle.
  56627. */
  56628. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  56629. /**
  56630. * The current speed of the particle.
  56631. */
  56632. this.velocity = BABYLON.Vector3.Zero();
  56633. /**
  56634. * The pivot point in the particle local space.
  56635. */
  56636. this.pivot = BABYLON.Vector3.Zero();
  56637. /**
  56638. * Must the particle be translated from its pivot point in its local space ?
  56639. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  56640. * Default : false
  56641. */
  56642. this.translateFromPivot = false;
  56643. /**
  56644. * Is the particle active or not ?
  56645. */
  56646. this.alive = true;
  56647. /**
  56648. * Is the particle visible or not ?
  56649. */
  56650. this.isVisible = true;
  56651. /**
  56652. * Index of this particle in the global "positions" array (Internal use)
  56653. */
  56654. this._pos = 0;
  56655. /**
  56656. * Index of this particle in the global "indices" array (Internal use)
  56657. */
  56658. this._ind = 0;
  56659. /**
  56660. * ModelShape id of this particle
  56661. */
  56662. this.shapeId = 0;
  56663. /**
  56664. * Index of the particle in its shape id (Internal use)
  56665. */
  56666. this.idxInShape = 0;
  56667. /**
  56668. * Still set as invisible in order to skip useless computations (Internal use)
  56669. */
  56670. this._stillInvisible = false;
  56671. /**
  56672. * Last computed particle rotation matrix
  56673. */
  56674. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  56675. /**
  56676. * Parent particle Id, if any.
  56677. * Default null.
  56678. */
  56679. this.parentId = null;
  56680. /**
  56681. * Internal global position in the SPS.
  56682. */
  56683. this._globalPosition = BABYLON.Vector3.Zero();
  56684. this.idx = particleIndex;
  56685. this._pos = positionIndex;
  56686. this._ind = indiceIndex;
  56687. this._model = model;
  56688. this.shapeId = shapeId;
  56689. this.idxInShape = idxInShape;
  56690. this._sps = sps;
  56691. if (modelBoundingInfo) {
  56692. this._modelBoundingInfo = modelBoundingInfo;
  56693. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  56694. }
  56695. }
  56696. Object.defineProperty(SolidParticle.prototype, "scale", {
  56697. /**
  56698. * Legacy support, changed scale to scaling
  56699. */
  56700. get: function () {
  56701. return this.scaling;
  56702. },
  56703. /**
  56704. * Legacy support, changed scale to scaling
  56705. */
  56706. set: function (scale) {
  56707. this.scaling = scale;
  56708. },
  56709. enumerable: true,
  56710. configurable: true
  56711. });
  56712. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56713. /**
  56714. * Legacy support, changed quaternion to rotationQuaternion
  56715. */
  56716. get: function () {
  56717. return this.rotationQuaternion;
  56718. },
  56719. /**
  56720. * Legacy support, changed quaternion to rotationQuaternion
  56721. */
  56722. set: function (q) {
  56723. this.rotationQuaternion = q;
  56724. },
  56725. enumerable: true,
  56726. configurable: true
  56727. });
  56728. /**
  56729. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  56730. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  56731. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  56732. * @returns true if it intersects
  56733. */
  56734. SolidParticle.prototype.intersectsMesh = function (target) {
  56735. if (!this._boundingInfo || !target._boundingInfo) {
  56736. return false;
  56737. }
  56738. if (this._sps._bSphereOnly) {
  56739. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  56740. }
  56741. return this._boundingInfo.intersects(target._boundingInfo, false);
  56742. };
  56743. return SolidParticle;
  56744. }());
  56745. BABYLON.SolidParticle = SolidParticle;
  56746. /**
  56747. * Represents the shape of the model used by one particle of a solid particle system.
  56748. * SPS internal tool, don't use it manually.
  56749. */
  56750. var ModelShape = /** @class */ (function () {
  56751. /**
  56752. * 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.
  56753. * SPS internal tool, don't use it manually.
  56754. * @ignore
  56755. */
  56756. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  56757. /**
  56758. * length of the shape in the model indices array (internal use)
  56759. */
  56760. this._indicesLength = 0;
  56761. this.shapeID = id;
  56762. this._shape = shape;
  56763. this._indicesLength = indicesLength;
  56764. this._shapeUV = shapeUV;
  56765. this._positionFunction = posFunction;
  56766. this._vertexFunction = vtxFunction;
  56767. }
  56768. return ModelShape;
  56769. }());
  56770. BABYLON.ModelShape = ModelShape;
  56771. /**
  56772. * Represents a Depth Sorted Particle in the solid particle system.
  56773. */
  56774. var DepthSortedParticle = /** @class */ (function () {
  56775. function DepthSortedParticle() {
  56776. /**
  56777. * Index of the particle in the "indices" array
  56778. */
  56779. this.ind = 0;
  56780. /**
  56781. * Length of the particle shape in the "indices" array
  56782. */
  56783. this.indicesLength = 0;
  56784. /**
  56785. * Squared distance from the particle to the camera
  56786. */
  56787. this.sqDistance = 0.0;
  56788. }
  56789. return DepthSortedParticle;
  56790. }());
  56791. BABYLON.DepthSortedParticle = DepthSortedParticle;
  56792. })(BABYLON || (BABYLON = {}));
  56793. //# sourceMappingURL=babylon.solidParticle.js.map
  56794. "use strict";
  56795. var BABYLON;
  56796. (function (BABYLON) {
  56797. /**
  56798. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  56799. *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.
  56800. * The SPS is also a particle system. It provides some methods to manage the particles.
  56801. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  56802. *
  56803. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56804. */
  56805. var SolidParticleSystem = /** @class */ (function () {
  56806. /**
  56807. * Creates a SPS (Solid Particle System) object.
  56808. * @param name (String) is the SPS name, this will be the underlying mesh name.
  56809. * @param scene (Scene) is the scene in which the SPS is added.
  56810. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  56811. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  56812. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  56813. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  56814. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  56815. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  56816. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  56817. */
  56818. function SolidParticleSystem(name, scene, options) {
  56819. /**
  56820. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56821. * Example : var p = SPS.particles[i];
  56822. */
  56823. this.particles = new Array();
  56824. /**
  56825. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56826. */
  56827. this.nbParticles = 0;
  56828. /**
  56829. * If the particles must ever face the camera (default false). Useful for planar particles.
  56830. */
  56831. this.billboard = false;
  56832. /**
  56833. * Recompute normals when adding a shape
  56834. */
  56835. this.recomputeNormals = true;
  56836. /**
  56837. * This a counter ofr your own usage. It's not set by any SPS functions.
  56838. */
  56839. this.counter = 0;
  56840. /**
  56841. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56842. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56843. */
  56844. this.vars = {};
  56845. /**
  56846. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  56847. */
  56848. this._bSphereOnly = false;
  56849. /**
  56850. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  56851. */
  56852. this._bSphereRadiusFactor = 1.0;
  56853. this._positions = new Array();
  56854. this._indices = new Array();
  56855. this._normals = new Array();
  56856. this._colors = new Array();
  56857. this._uvs = new Array();
  56858. this._index = 0; // indices index
  56859. this._updatable = true;
  56860. this._pickable = false;
  56861. this._isVisibilityBoxLocked = false;
  56862. this._alwaysVisible = false;
  56863. this._depthSort = false;
  56864. this._shapeCounter = 0;
  56865. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  56866. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56867. this._computeParticleColor = true;
  56868. this._computeParticleTexture = true;
  56869. this._computeParticleRotation = true;
  56870. this._computeParticleVertex = false;
  56871. this._computeBoundingBox = false;
  56872. this._depthSortParticles = true;
  56873. this._cam_axisZ = BABYLON.Vector3.Zero();
  56874. this._cam_axisY = BABYLON.Vector3.Zero();
  56875. this._cam_axisX = BABYLON.Vector3.Zero();
  56876. this._axisZ = BABYLON.Axis.Z;
  56877. this._camDir = BABYLON.Vector3.Zero();
  56878. this._camInvertedPosition = BABYLON.Vector3.Zero();
  56879. this._rotMatrix = new BABYLON.Matrix();
  56880. this._invertMatrix = new BABYLON.Matrix();
  56881. this._rotated = BABYLON.Vector3.Zero();
  56882. this._quaternion = new BABYLON.Quaternion();
  56883. this._vertex = BABYLON.Vector3.Zero();
  56884. this._normal = BABYLON.Vector3.Zero();
  56885. this._yaw = 0.0;
  56886. this._pitch = 0.0;
  56887. this._roll = 0.0;
  56888. this._halfroll = 0.0;
  56889. this._halfpitch = 0.0;
  56890. this._halfyaw = 0.0;
  56891. this._sinRoll = 0.0;
  56892. this._cosRoll = 0.0;
  56893. this._sinPitch = 0.0;
  56894. this._cosPitch = 0.0;
  56895. this._sinYaw = 0.0;
  56896. this._cosYaw = 0.0;
  56897. this._mustUnrotateFixedNormals = false;
  56898. this._minimum = BABYLON.Vector3.Zero();
  56899. this._maximum = BABYLON.Vector3.Zero();
  56900. this._minBbox = BABYLON.Vector3.Zero();
  56901. this._maxBbox = BABYLON.Vector3.Zero();
  56902. this._particlesIntersect = false;
  56903. this._depthSortFunction = function (p1, p2) {
  56904. return (p2.sqDistance - p1.sqDistance);
  56905. };
  56906. this._needs32Bits = false;
  56907. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  56908. this._scaledPivot = BABYLON.Vector3.Zero();
  56909. this._particleHasParent = false;
  56910. this.name = name;
  56911. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56912. this._camera = scene.activeCamera;
  56913. this._pickable = options ? options.isPickable : false;
  56914. this._depthSort = options ? options.enableDepthSort : false;
  56915. this._particlesIntersect = options ? options.particleIntersection : false;
  56916. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  56917. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  56918. if (options && options.updatable) {
  56919. this._updatable = options.updatable;
  56920. }
  56921. else {
  56922. this._updatable = true;
  56923. }
  56924. if (this._pickable) {
  56925. this.pickedParticles = [];
  56926. }
  56927. if (this._depthSort) {
  56928. this.depthSortedParticles = [];
  56929. }
  56930. }
  56931. /**
  56932. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56933. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56934. * @returns the created mesh
  56935. */
  56936. SolidParticleSystem.prototype.buildMesh = function () {
  56937. if (this.nbParticles === 0) {
  56938. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56939. this.addShape(triangle, 1);
  56940. triangle.dispose();
  56941. }
  56942. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  56943. this._positions32 = new Float32Array(this._positions);
  56944. this._uvs32 = new Float32Array(this._uvs);
  56945. this._colors32 = new Float32Array(this._colors);
  56946. if (this.recomputeNormals) {
  56947. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  56948. }
  56949. this._normals32 = new Float32Array(this._normals);
  56950. this._fixedNormal32 = new Float32Array(this._normals);
  56951. if (this._mustUnrotateFixedNormals) {
  56952. this._unrotateFixedNormals();
  56953. }
  56954. var vertexData = new BABYLON.VertexData();
  56955. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  56956. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56957. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56958. if (this._uvs32) {
  56959. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56960. ;
  56961. }
  56962. if (this._colors32) {
  56963. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56964. }
  56965. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56966. vertexData.applyToMesh(mesh, this._updatable);
  56967. this.mesh = mesh;
  56968. this.mesh.isPickable = this._pickable;
  56969. // free memory
  56970. if (!this._depthSort) {
  56971. this._indices = null;
  56972. }
  56973. this._positions = null;
  56974. this._normals = null;
  56975. this._uvs = null;
  56976. this._colors = null;
  56977. if (!this._updatable) {
  56978. this.particles.length = 0;
  56979. }
  56980. return mesh;
  56981. };
  56982. /**
  56983. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56984. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56985. * Thus the particles generated from `digest()` have their property `position` set yet.
  56986. * @param mesh ( Mesh ) is the mesh to be digested
  56987. * @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
  56988. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56989. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56990. * @returns the current SPS
  56991. */
  56992. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56993. var size = (options && options.facetNb) || 1;
  56994. var number = (options && options.number) || 0;
  56995. var delta = (options && options.delta) || 0;
  56996. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56997. var meshInd = mesh.getIndices();
  56998. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56999. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57000. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57001. var f = 0; // facet counter
  57002. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57003. // compute size from number
  57004. if (number) {
  57005. number = (number > totalFacets) ? totalFacets : number;
  57006. size = Math.round(totalFacets / number);
  57007. delta = 0;
  57008. }
  57009. else {
  57010. size = (size > totalFacets) ? totalFacets : size;
  57011. }
  57012. var facetPos = []; // submesh positions
  57013. var facetInd = []; // submesh indices
  57014. var facetUV = []; // submesh UV
  57015. var facetCol = []; // submesh colors
  57016. var barycenter = BABYLON.Vector3.Zero();
  57017. var sizeO = size;
  57018. while (f < totalFacets) {
  57019. size = sizeO + Math.floor((1 + delta) * Math.random());
  57020. if (f > totalFacets - size) {
  57021. size = totalFacets - f;
  57022. }
  57023. // reset temp arrays
  57024. facetPos.length = 0;
  57025. facetInd.length = 0;
  57026. facetUV.length = 0;
  57027. facetCol.length = 0;
  57028. // iterate over "size" facets
  57029. var fi = 0;
  57030. for (var j = f * 3; j < (f + size) * 3; j++) {
  57031. facetInd.push(fi);
  57032. var i = meshInd[j];
  57033. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57034. if (meshUV) {
  57035. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57036. }
  57037. if (meshCol) {
  57038. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57039. }
  57040. fi++;
  57041. }
  57042. // create a model shape for each single particle
  57043. var idx = this.nbParticles;
  57044. var shape = this._posToShape(facetPos);
  57045. var shapeUV = this._uvsToShapeUV(facetUV);
  57046. // compute the barycenter of the shape
  57047. var v;
  57048. for (v = 0; v < shape.length; v++) {
  57049. barycenter.addInPlace(shape[v]);
  57050. }
  57051. barycenter.scaleInPlace(1 / shape.length);
  57052. // shift the shape from its barycenter to the origin
  57053. for (v = 0; v < shape.length; v++) {
  57054. shape[v].subtractInPlace(barycenter);
  57055. }
  57056. var bInfo;
  57057. if (this._particlesIntersect) {
  57058. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57059. }
  57060. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57061. // add the particle in the SPS
  57062. var currentPos = this._positions.length;
  57063. var currentInd = this._indices.length;
  57064. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57065. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57066. // initialize the particle position
  57067. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57068. this._index += shape.length;
  57069. idx++;
  57070. this.nbParticles++;
  57071. this._shapeCounter++;
  57072. f += size;
  57073. }
  57074. return this;
  57075. };
  57076. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57077. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57078. var index = 0;
  57079. var idx = 0;
  57080. for (var p = 0; p < this.particles.length; p++) {
  57081. this._particle = this.particles[p];
  57082. this._shape = this._particle._model._shape;
  57083. if (this._particle.rotationQuaternion) {
  57084. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57085. }
  57086. else {
  57087. this._yaw = this._particle.rotation.y;
  57088. this._pitch = this._particle.rotation.x;
  57089. this._roll = this._particle.rotation.z;
  57090. this._quaternionRotationYPR();
  57091. }
  57092. this._quaternionToRotationMatrix();
  57093. this._rotMatrix.invertToRef(this._invertMatrix);
  57094. for (var pt = 0; pt < this._shape.length; pt++) {
  57095. idx = index + pt * 3;
  57096. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57097. this._fixedNormal32[idx] = this._normal.x;
  57098. this._fixedNormal32[idx + 1] = this._normal.y;
  57099. this._fixedNormal32[idx + 2] = this._normal.z;
  57100. }
  57101. index = idx + 3;
  57102. }
  57103. };
  57104. //reset copy
  57105. SolidParticleSystem.prototype._resetCopy = function () {
  57106. this._copy.position.x = 0;
  57107. this._copy.position.y = 0;
  57108. this._copy.position.z = 0;
  57109. this._copy.rotation.x = 0;
  57110. this._copy.rotation.y = 0;
  57111. this._copy.rotation.z = 0;
  57112. this._copy.rotationQuaternion = null;
  57113. this._copy.scaling.x = 1.0;
  57114. this._copy.scaling.y = 1.0;
  57115. this._copy.scaling.z = 1.0;
  57116. this._copy.uvs.x = 0;
  57117. this._copy.uvs.y = 0;
  57118. this._copy.uvs.z = 1.0;
  57119. this._copy.uvs.w = 1.0;
  57120. this._copy.color = null;
  57121. this._copy.translateFromPivot = false;
  57122. };
  57123. // _meshBuilder : inserts the shape model in the global SPS mesh
  57124. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57125. var i;
  57126. var u = 0;
  57127. var c = 0;
  57128. var n = 0;
  57129. this._resetCopy();
  57130. if (options && options.positionFunction) {
  57131. options.positionFunction(this._copy, idx, idxInShape);
  57132. this._mustUnrotateFixedNormals = true;
  57133. }
  57134. if (this._copy.rotationQuaternion) {
  57135. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57136. }
  57137. else {
  57138. this._yaw = this._copy.rotation.y;
  57139. this._pitch = this._copy.rotation.x;
  57140. this._roll = this._copy.rotation.z;
  57141. this._quaternionRotationYPR();
  57142. }
  57143. this._quaternionToRotationMatrix();
  57144. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57145. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57146. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57147. if (this._copy.translateFromPivot) {
  57148. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57149. }
  57150. else {
  57151. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57152. }
  57153. for (i = 0; i < shape.length; i++) {
  57154. this._vertex.x = shape[i].x;
  57155. this._vertex.y = shape[i].y;
  57156. this._vertex.z = shape[i].z;
  57157. if (options && options.vertexFunction) {
  57158. options.vertexFunction(this._copy, this._vertex, i);
  57159. }
  57160. this._vertex.x *= this._copy.scaling.x;
  57161. this._vertex.y *= this._copy.scaling.y;
  57162. this._vertex.z *= this._copy.scaling.z;
  57163. this._vertex.x -= this._scaledPivot.x;
  57164. this._vertex.y -= this._scaledPivot.y;
  57165. this._vertex.z -= this._scaledPivot.z;
  57166. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57167. this._rotated.addInPlace(this._pivotBackTranslation);
  57168. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57169. if (meshUV) {
  57170. 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);
  57171. u += 2;
  57172. }
  57173. if (this._copy.color) {
  57174. this._color = this._copy.color;
  57175. }
  57176. else if (meshCol && meshCol[c] !== undefined) {
  57177. this._color.r = meshCol[c];
  57178. this._color.g = meshCol[c + 1];
  57179. this._color.b = meshCol[c + 2];
  57180. this._color.a = meshCol[c + 3];
  57181. }
  57182. else {
  57183. this._color.r = 1.0;
  57184. this._color.g = 1.0;
  57185. this._color.b = 1.0;
  57186. this._color.a = 1.0;
  57187. }
  57188. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57189. c += 4;
  57190. if (!this.recomputeNormals && meshNor) {
  57191. this._normal.x = meshNor[n];
  57192. this._normal.y = meshNor[n + 1];
  57193. this._normal.z = meshNor[n + 2];
  57194. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57195. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57196. n += 3;
  57197. }
  57198. }
  57199. for (i = 0; i < meshInd.length; i++) {
  57200. var current_ind = p + meshInd[i];
  57201. indices.push(current_ind);
  57202. if (current_ind > 65535) {
  57203. this._needs32Bits = true;
  57204. }
  57205. }
  57206. if (this._pickable) {
  57207. var nbfaces = meshInd.length / 3;
  57208. for (i = 0; i < nbfaces; i++) {
  57209. this.pickedParticles.push({ idx: idx, faceId: i });
  57210. }
  57211. }
  57212. if (this._depthSort) {
  57213. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57214. }
  57215. return this._copy;
  57216. };
  57217. // returns a shape array from positions array
  57218. SolidParticleSystem.prototype._posToShape = function (positions) {
  57219. var shape = [];
  57220. for (var i = 0; i < positions.length; i += 3) {
  57221. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57222. }
  57223. return shape;
  57224. };
  57225. // returns a shapeUV array from a Vector4 uvs
  57226. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57227. var shapeUV = [];
  57228. if (uvs) {
  57229. for (var i = 0; i < uvs.length; i++)
  57230. shapeUV.push(uvs[i]);
  57231. }
  57232. return shapeUV;
  57233. };
  57234. // adds a new particle object in the particles array
  57235. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57236. if (bInfo === void 0) { bInfo = null; }
  57237. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57238. this.particles.push(sp);
  57239. return sp;
  57240. };
  57241. /**
  57242. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57243. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57244. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57245. * @param nb (positive integer) the number of particles to be created from this model
  57246. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57247. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57248. * @returns the number of shapes in the system
  57249. */
  57250. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57251. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57252. var meshInd = mesh.getIndices();
  57253. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57254. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57255. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57256. var bbInfo;
  57257. if (this._particlesIntersect) {
  57258. bbInfo = mesh.getBoundingInfo();
  57259. }
  57260. var shape = this._posToShape(meshPos);
  57261. var shapeUV = this._uvsToShapeUV(meshUV);
  57262. var posfunc = options ? options.positionFunction : null;
  57263. var vtxfunc = options ? options.vertexFunction : null;
  57264. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57265. // particles
  57266. var sp;
  57267. var currentCopy;
  57268. var idx = this.nbParticles;
  57269. for (var i = 0; i < nb; i++) {
  57270. var currentPos = this._positions.length;
  57271. var currentInd = this._indices.length;
  57272. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57273. if (this._updatable) {
  57274. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57275. sp.position.copyFrom(currentCopy.position);
  57276. sp.rotation.copyFrom(currentCopy.rotation);
  57277. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57278. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57279. }
  57280. if (currentCopy.color && sp.color) {
  57281. sp.color.copyFrom(currentCopy.color);
  57282. }
  57283. sp.scaling.copyFrom(currentCopy.scaling);
  57284. sp.uvs.copyFrom(currentCopy.uvs);
  57285. }
  57286. this._index += shape.length;
  57287. idx++;
  57288. }
  57289. this.nbParticles += nb;
  57290. this._shapeCounter++;
  57291. return this._shapeCounter - 1;
  57292. };
  57293. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57294. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57295. this._resetCopy();
  57296. if (particle._model._positionFunction) {
  57297. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57298. }
  57299. if (this._copy.rotationQuaternion) {
  57300. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57301. }
  57302. else {
  57303. this._yaw = this._copy.rotation.y;
  57304. this._pitch = this._copy.rotation.x;
  57305. this._roll = this._copy.rotation.z;
  57306. this._quaternionRotationYPR();
  57307. }
  57308. this._quaternionToRotationMatrix();
  57309. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57310. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57311. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57312. if (this._copy.translateFromPivot) {
  57313. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57314. }
  57315. else {
  57316. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57317. }
  57318. this._shape = particle._model._shape;
  57319. for (var pt = 0; pt < this._shape.length; pt++) {
  57320. this._vertex.x = this._shape[pt].x;
  57321. this._vertex.y = this._shape[pt].y;
  57322. this._vertex.z = this._shape[pt].z;
  57323. if (particle._model._vertexFunction) {
  57324. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57325. }
  57326. this._vertex.x *= this._copy.scaling.x;
  57327. this._vertex.y *= this._copy.scaling.y;
  57328. this._vertex.z *= this._copy.scaling.z;
  57329. this._vertex.x -= this._scaledPivot.x;
  57330. this._vertex.y -= this._scaledPivot.y;
  57331. this._vertex.z -= this._scaledPivot.z;
  57332. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57333. this._rotated.addInPlace(this._pivotBackTranslation);
  57334. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57335. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57336. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57337. }
  57338. particle.position.x = 0.0;
  57339. particle.position.y = 0.0;
  57340. particle.position.z = 0.0;
  57341. particle.rotation.x = 0.0;
  57342. particle.rotation.y = 0.0;
  57343. particle.rotation.z = 0.0;
  57344. particle.rotationQuaternion = null;
  57345. particle.scaling.x = 1.0;
  57346. particle.scaling.y = 1.0;
  57347. particle.scaling.z = 1.0;
  57348. particle.uvs.x = 0.0;
  57349. particle.uvs.y = 0.0;
  57350. particle.uvs.z = 1.0;
  57351. particle.uvs.w = 1.0;
  57352. particle.pivot.x = 0.0;
  57353. particle.pivot.y = 0.0;
  57354. particle.pivot.z = 0.0;
  57355. particle.translateFromPivot = false;
  57356. particle.parentId = null;
  57357. };
  57358. /**
  57359. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57360. * @returns the SPS.
  57361. */
  57362. SolidParticleSystem.prototype.rebuildMesh = function () {
  57363. for (var p = 0; p < this.particles.length; p++) {
  57364. this._rebuildParticle(this.particles[p]);
  57365. }
  57366. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57367. return this;
  57368. };
  57369. /**
  57370. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57371. * This method calls `updateParticle()` for each particle of the SPS.
  57372. * For an animated SPS, it is usually called within the render loop.
  57373. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57374. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57375. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57376. * @returns the SPS.
  57377. */
  57378. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57379. if (start === void 0) { start = 0; }
  57380. if (end === void 0) { end = this.nbParticles - 1; }
  57381. if (update === void 0) { update = true; }
  57382. if (!this._updatable) {
  57383. return this;
  57384. }
  57385. // custom beforeUpdate
  57386. this.beforeUpdateParticles(start, end, update);
  57387. this._cam_axisX.x = 1.0;
  57388. this._cam_axisX.y = 0.0;
  57389. this._cam_axisX.z = 0.0;
  57390. this._cam_axisY.x = 0.0;
  57391. this._cam_axisY.y = 1.0;
  57392. this._cam_axisY.z = 0.0;
  57393. this._cam_axisZ.x = 0.0;
  57394. this._cam_axisZ.y = 0.0;
  57395. this._cam_axisZ.z = 1.0;
  57396. // cases when the World Matrix is to be computed first
  57397. if (this.billboard || this._depthSort) {
  57398. this.mesh.computeWorldMatrix(true);
  57399. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57400. }
  57401. // if the particles will always face the camera
  57402. if (this.billboard) {
  57403. // compute the camera position and un-rotate it by the current mesh rotation
  57404. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57405. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57406. this._cam_axisZ.normalize();
  57407. // same for camera up vector extracted from the cam view matrix
  57408. var view = this._camera.getViewMatrix(true);
  57409. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57410. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57411. this._cam_axisY.normalize();
  57412. this._cam_axisX.normalize();
  57413. }
  57414. // if depthSort, compute the camera global position in the mesh local system
  57415. if (this._depthSort) {
  57416. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57417. }
  57418. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57419. var idx = 0; // current position index in the global array positions32
  57420. var index = 0; // position start index in the global array positions32 of the current particle
  57421. var colidx = 0; // current color index in the global array colors32
  57422. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57423. var uvidx = 0; // current uv index in the global array uvs32
  57424. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57425. var pt = 0; // current index in the particle model shape
  57426. if (this.mesh.isFacetDataEnabled) {
  57427. this._computeBoundingBox = true;
  57428. }
  57429. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57430. if (this._computeBoundingBox) {
  57431. if (start == 0 && end == this.nbParticles - 1) {
  57432. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57433. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57434. }
  57435. else {
  57436. if (this.mesh._boundingInfo) {
  57437. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  57438. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  57439. }
  57440. }
  57441. }
  57442. // particle loop
  57443. index = this.particles[start]._pos;
  57444. var vpos = (index / 3) | 0;
  57445. colorIndex = vpos * 4;
  57446. uvIndex = vpos * 2;
  57447. for (var p = start; p <= end; p++) {
  57448. this._particle = this.particles[p];
  57449. this._shape = this._particle._model._shape;
  57450. this._shapeUV = this._particle._model._shapeUV;
  57451. // call to custom user function to update the particle properties
  57452. this.updateParticle(this._particle);
  57453. // camera-particle distance for depth sorting
  57454. if (this._depthSort && this._depthSortParticles) {
  57455. var dsp = this.depthSortedParticles[p];
  57456. dsp.ind = this._particle._ind;
  57457. dsp.indicesLength = this._particle._model._indicesLength;
  57458. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  57459. }
  57460. // skip the computations for inactive or already invisible particles
  57461. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  57462. // increment indexes for the next particle
  57463. pt = this._shape.length;
  57464. index += pt * 3;
  57465. colorIndex += pt * 4;
  57466. uvIndex += pt * 2;
  57467. continue;
  57468. }
  57469. if (this._particle.isVisible) {
  57470. this._particle._stillInvisible = false; // un-mark permanent invisibility
  57471. this._particleHasParent = (this._particle.parentId !== null);
  57472. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57473. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57474. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57475. // particle rotation matrix
  57476. if (this.billboard) {
  57477. this._particle.rotation.x = 0.0;
  57478. this._particle.rotation.y = 0.0;
  57479. }
  57480. if (this._computeParticleRotation || this.billboard) {
  57481. if (this._particle.rotationQuaternion) {
  57482. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57483. }
  57484. else {
  57485. this._yaw = this._particle.rotation.y;
  57486. this._pitch = this._particle.rotation.x;
  57487. this._roll = this._particle.rotation.z;
  57488. this._quaternionRotationYPR();
  57489. }
  57490. this._quaternionToRotationMatrix();
  57491. }
  57492. if (this._particleHasParent) {
  57493. this._parent = this.particles[this._particle.parentId];
  57494. 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];
  57495. 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];
  57496. 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];
  57497. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  57498. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  57499. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  57500. if (this._computeParticleRotation || this.billboard) {
  57501. 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];
  57502. 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];
  57503. 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];
  57504. 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];
  57505. 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];
  57506. 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];
  57507. 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];
  57508. 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];
  57509. 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];
  57510. }
  57511. }
  57512. else {
  57513. this._particle._globalPosition.x = this._particle.position.x;
  57514. this._particle._globalPosition.y = this._particle.position.y;
  57515. this._particle._globalPosition.z = this._particle.position.z;
  57516. if (this._computeParticleRotation || this.billboard) {
  57517. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  57518. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  57519. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  57520. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  57521. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  57522. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  57523. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  57524. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  57525. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  57526. }
  57527. }
  57528. if (this._particle.translateFromPivot) {
  57529. this._pivotBackTranslation.x = 0.0;
  57530. this._pivotBackTranslation.y = 0.0;
  57531. this._pivotBackTranslation.z = 0.0;
  57532. }
  57533. else {
  57534. this._pivotBackTranslation.x = this._scaledPivot.x;
  57535. this._pivotBackTranslation.y = this._scaledPivot.y;
  57536. this._pivotBackTranslation.z = this._scaledPivot.z;
  57537. }
  57538. // particle vertex loop
  57539. for (pt = 0; pt < this._shape.length; pt++) {
  57540. idx = index + pt * 3;
  57541. colidx = colorIndex + pt * 4;
  57542. uvidx = uvIndex + pt * 2;
  57543. this._vertex.x = this._shape[pt].x;
  57544. this._vertex.y = this._shape[pt].y;
  57545. this._vertex.z = this._shape[pt].z;
  57546. if (this._computeParticleVertex) {
  57547. this.updateParticleVertex(this._particle, this._vertex, pt);
  57548. }
  57549. // positions
  57550. this._vertex.x *= this._particle.scaling.x;
  57551. this._vertex.y *= this._particle.scaling.y;
  57552. this._vertex.z *= this._particle.scaling.z;
  57553. this._vertex.x -= this._scaledPivot.x;
  57554. this._vertex.y -= this._scaledPivot.y;
  57555. this._vertex.z -= this._scaledPivot.z;
  57556. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57557. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57558. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57559. this._rotated.x += this._pivotBackTranslation.x;
  57560. this._rotated.y += this._pivotBackTranslation.y;
  57561. this._rotated.z += this._pivotBackTranslation.z;
  57562. 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;
  57563. 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;
  57564. 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;
  57565. if (this._computeBoundingBox) {
  57566. if (this._positions32[idx] < this._minimum.x) {
  57567. this._minimum.x = this._positions32[idx];
  57568. }
  57569. if (this._positions32[idx] > this._maximum.x) {
  57570. this._maximum.x = this._positions32[idx];
  57571. }
  57572. if (this._positions32[idx + 1] < this._minimum.y) {
  57573. this._minimum.y = this._positions32[idx + 1];
  57574. }
  57575. if (this._positions32[idx + 1] > this._maximum.y) {
  57576. this._maximum.y = this._positions32[idx + 1];
  57577. }
  57578. if (this._positions32[idx + 2] < this._minimum.z) {
  57579. this._minimum.z = this._positions32[idx + 2];
  57580. }
  57581. if (this._positions32[idx + 2] > this._maximum.z) {
  57582. this._maximum.z = this._positions32[idx + 2];
  57583. }
  57584. }
  57585. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  57586. if (!this._computeParticleVertex) {
  57587. this._normal.x = this._fixedNormal32[idx];
  57588. this._normal.y = this._fixedNormal32[idx + 1];
  57589. this._normal.z = this._fixedNormal32[idx + 2];
  57590. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  57591. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  57592. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  57593. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57594. 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;
  57595. 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;
  57596. }
  57597. if (this._computeParticleColor && this._particle.color) {
  57598. this._colors32[colidx] = this._particle.color.r;
  57599. this._colors32[colidx + 1] = this._particle.color.g;
  57600. this._colors32[colidx + 2] = this._particle.color.b;
  57601. this._colors32[colidx + 3] = this._particle.color.a;
  57602. }
  57603. if (this._computeParticleTexture) {
  57604. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57605. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57606. }
  57607. }
  57608. }
  57609. else {
  57610. this._particle._stillInvisible = true; // mark the particle as invisible
  57611. for (pt = 0; pt < this._shape.length; pt++) {
  57612. idx = index + pt * 3;
  57613. colidx = colorIndex + pt * 4;
  57614. uvidx = uvIndex + pt * 2;
  57615. this._positions32[idx] = 0.0;
  57616. this._positions32[idx + 1] = 0.0;
  57617. this._positions32[idx + 2] = 0.0;
  57618. this._normals32[idx] = 0.0;
  57619. this._normals32[idx + 1] = 0.0;
  57620. this._normals32[idx + 2] = 0.0;
  57621. if (this._computeParticleColor && this._particle.color) {
  57622. this._colors32[colidx] = this._particle.color.r;
  57623. this._colors32[colidx + 1] = this._particle.color.g;
  57624. this._colors32[colidx + 2] = this._particle.color.b;
  57625. this._colors32[colidx + 3] = this._particle.color.a;
  57626. }
  57627. if (this._computeParticleTexture) {
  57628. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57629. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57630. }
  57631. }
  57632. }
  57633. // if the particle intersections must be computed : update the bbInfo
  57634. if (this._particlesIntersect) {
  57635. var bInfo = this._particle._boundingInfo;
  57636. var bBox = bInfo.boundingBox;
  57637. var bSphere = bInfo.boundingSphere;
  57638. if (!this._bSphereOnly) {
  57639. // place, scale and rotate the particle bbox within the SPS local system, then update it
  57640. for (var b = 0; b < bBox.vectors.length; b++) {
  57641. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  57642. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  57643. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  57644. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57645. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57646. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57647. 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;
  57648. 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;
  57649. 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;
  57650. }
  57651. bBox._update(this.mesh._worldMatrix);
  57652. }
  57653. // place and scale the particle bouding sphere in the SPS local system, then update it
  57654. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  57655. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  57656. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  57657. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  57658. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  57659. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  57660. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  57661. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  57662. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  57663. 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));
  57664. bSphere._update(this.mesh._worldMatrix);
  57665. }
  57666. // increment indexes for the next particle
  57667. index = idx + 3;
  57668. colorIndex = colidx + 4;
  57669. uvIndex = uvidx + 2;
  57670. }
  57671. // if the VBO must be updated
  57672. if (update) {
  57673. if (this._computeParticleColor) {
  57674. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57675. }
  57676. if (this._computeParticleTexture) {
  57677. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57678. }
  57679. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57680. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  57681. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  57682. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57683. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  57684. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  57685. for (var i = 0; i < this._normals32.length; i++) {
  57686. this._fixedNormal32[i] = this._normals32[i];
  57687. }
  57688. }
  57689. if (!this.mesh.areNormalsFrozen) {
  57690. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57691. }
  57692. }
  57693. if (this._depthSort && this._depthSortParticles) {
  57694. this.depthSortedParticles.sort(this._depthSortFunction);
  57695. var dspl = this.depthSortedParticles.length;
  57696. var sorted = 0;
  57697. var lind = 0;
  57698. var sind = 0;
  57699. var sid = 0;
  57700. for (sorted = 0; sorted < dspl; sorted++) {
  57701. lind = this.depthSortedParticles[sorted].indicesLength;
  57702. sind = this.depthSortedParticles[sorted].ind;
  57703. for (var i = 0; i < lind; i++) {
  57704. this._indices32[sid] = this._indices[sind + i];
  57705. sid++;
  57706. }
  57707. }
  57708. this.mesh.updateIndices(this._indices32);
  57709. }
  57710. }
  57711. if (this._computeBoundingBox) {
  57712. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57713. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57714. }
  57715. this.afterUpdateParticles(start, end, update);
  57716. return this;
  57717. };
  57718. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57719. this._halfroll = this._roll * 0.5;
  57720. this._halfpitch = this._pitch * 0.5;
  57721. this._halfyaw = this._yaw * 0.5;
  57722. this._sinRoll = Math.sin(this._halfroll);
  57723. this._cosRoll = Math.cos(this._halfroll);
  57724. this._sinPitch = Math.sin(this._halfpitch);
  57725. this._cosPitch = Math.cos(this._halfpitch);
  57726. this._sinYaw = Math.sin(this._halfyaw);
  57727. this._cosYaw = Math.cos(this._halfyaw);
  57728. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  57729. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  57730. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  57731. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  57732. };
  57733. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57734. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57735. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57736. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57737. this._rotMatrix.m[3] = 0;
  57738. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57739. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57740. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57741. this._rotMatrix.m[7] = 0;
  57742. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57743. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57744. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57745. this._rotMatrix.m[11] = 0;
  57746. this._rotMatrix.m[12] = 0;
  57747. this._rotMatrix.m[13] = 0;
  57748. this._rotMatrix.m[14] = 0;
  57749. this._rotMatrix.m[15] = 1.0;
  57750. };
  57751. /**
  57752. * Disposes the SPS.
  57753. */
  57754. SolidParticleSystem.prototype.dispose = function () {
  57755. this.mesh.dispose();
  57756. this.vars = null;
  57757. // drop references to internal big arrays for the GC
  57758. this._positions = null;
  57759. this._indices = null;
  57760. this._normals = null;
  57761. this._uvs = null;
  57762. this._colors = null;
  57763. this._indices32 = null;
  57764. this._positions32 = null;
  57765. this._normals32 = null;
  57766. this._fixedNormal32 = null;
  57767. this._uvs32 = null;
  57768. this._colors32 = null;
  57769. this.pickedParticles = null;
  57770. };
  57771. /**
  57772. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57773. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57774. * @returns the SPS.
  57775. */
  57776. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57777. if (!this._isVisibilityBoxLocked) {
  57778. this.mesh.refreshBoundingInfo();
  57779. }
  57780. return this;
  57781. };
  57782. /**
  57783. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57784. * @param size the size (float) of the visibility box
  57785. * note : this doesn't lock the SPS mesh bounding box.
  57786. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57787. */
  57788. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57789. var vis = size / 2;
  57790. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57791. };
  57792. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57793. /**
  57794. * Gets whether the SPS as always visible or not
  57795. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57796. */
  57797. get: function () {
  57798. return this._alwaysVisible;
  57799. },
  57800. /**
  57801. * Sets the SPS as always visible or not
  57802. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57803. */
  57804. set: function (val) {
  57805. this._alwaysVisible = val;
  57806. this.mesh.alwaysSelectAsActiveMesh = val;
  57807. },
  57808. enumerable: true,
  57809. configurable: true
  57810. });
  57811. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57812. /**
  57813. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57814. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57815. */
  57816. get: function () {
  57817. return this._isVisibilityBoxLocked;
  57818. },
  57819. /**
  57820. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57821. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57822. */
  57823. set: function (val) {
  57824. this._isVisibilityBoxLocked = val;
  57825. var boundingInfo = this.mesh.getBoundingInfo();
  57826. boundingInfo.isLocked = val;
  57827. },
  57828. enumerable: true,
  57829. configurable: true
  57830. });
  57831. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57832. /**
  57833. * Gets if `setParticles()` computes the particle rotations or not.
  57834. * Default value : true. The SPS is faster when it's set to false.
  57835. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57836. */
  57837. get: function () {
  57838. return this._computeParticleRotation;
  57839. },
  57840. /**
  57841. * Tells to `setParticles()` to compute the particle rotations or not.
  57842. * Default value : true. The SPS is faster when it's set to false.
  57843. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57844. */
  57845. set: function (val) {
  57846. this._computeParticleRotation = val;
  57847. },
  57848. enumerable: true,
  57849. configurable: true
  57850. });
  57851. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57852. /**
  57853. * Gets if `setParticles()` computes the particle colors or not.
  57854. * Default value : true. The SPS is faster when it's set to false.
  57855. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57856. */
  57857. get: function () {
  57858. return this._computeParticleColor;
  57859. },
  57860. /**
  57861. * Tells to `setParticles()` to compute the particle colors or not.
  57862. * Default value : true. The SPS is faster when it's set to false.
  57863. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57864. */
  57865. set: function (val) {
  57866. this._computeParticleColor = val;
  57867. },
  57868. enumerable: true,
  57869. configurable: true
  57870. });
  57871. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57872. /**
  57873. * Gets if `setParticles()` computes the particle textures or not.
  57874. * Default value : true. The SPS is faster when it's set to false.
  57875. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57876. */
  57877. get: function () {
  57878. return this._computeParticleTexture;
  57879. },
  57880. set: function (val) {
  57881. this._computeParticleTexture = val;
  57882. },
  57883. enumerable: true,
  57884. configurable: true
  57885. });
  57886. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57887. /**
  57888. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  57889. * Default value : false. The SPS is faster when it's set to false.
  57890. * Note : the particle custom vertex positions aren't stored values.
  57891. */
  57892. get: function () {
  57893. return this._computeParticleVertex;
  57894. },
  57895. /**
  57896. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57897. * Default value : false. The SPS is faster when it's set to false.
  57898. * Note : the particle custom vertex positions aren't stored values.
  57899. */
  57900. set: function (val) {
  57901. this._computeParticleVertex = val;
  57902. },
  57903. enumerable: true,
  57904. configurable: true
  57905. });
  57906. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57907. /**
  57908. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  57909. */
  57910. get: function () {
  57911. return this._computeBoundingBox;
  57912. },
  57913. /**
  57914. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57915. */
  57916. set: function (val) {
  57917. this._computeBoundingBox = val;
  57918. },
  57919. enumerable: true,
  57920. configurable: true
  57921. });
  57922. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  57923. /**
  57924. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  57925. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57926. * Default : `true`
  57927. */
  57928. get: function () {
  57929. return this._depthSortParticles;
  57930. },
  57931. /**
  57932. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  57933. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57934. * Default : `true`
  57935. */
  57936. set: function (val) {
  57937. this._depthSortParticles = val;
  57938. },
  57939. enumerable: true,
  57940. configurable: true
  57941. });
  57942. // =======================================================================
  57943. // Particle behavior logic
  57944. // these following methods may be overwritten by the user to fit his needs
  57945. /**
  57946. * This function does nothing. It may be overwritten to set all the particle first values.
  57947. * The SPS doesn't call this function, you may have to call it by your own.
  57948. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57949. */
  57950. SolidParticleSystem.prototype.initParticles = function () {
  57951. };
  57952. /**
  57953. * This function does nothing. It may be overwritten to recycle a particle.
  57954. * The SPS doesn't call this function, you may have to call it by your own.
  57955. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57956. * @param particle The particle to recycle
  57957. * @returns the recycled particle
  57958. */
  57959. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57960. return particle;
  57961. };
  57962. /**
  57963. * Updates a particle : this function should be overwritten by the user.
  57964. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57965. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57966. * @example : just set a particle position or velocity and recycle conditions
  57967. * @param particle The particle to update
  57968. * @returns the updated particle
  57969. */
  57970. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57971. return particle;
  57972. };
  57973. /**
  57974. * Updates a vertex of a particle : it can be overwritten by the user.
  57975. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57976. * @param particle the current particle
  57977. * @param vertex the current index of the current particle
  57978. * @param pt the index of the current vertex in the particle shape
  57979. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57980. * @example : just set a vertex particle position
  57981. * @returns the updated vertex
  57982. */
  57983. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57984. return vertex;
  57985. };
  57986. /**
  57987. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57988. * This does nothing and may be overwritten by the user.
  57989. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57990. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57991. * @param update the boolean update value actually passed to setParticles()
  57992. */
  57993. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57994. };
  57995. /**
  57996. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57997. * This will be passed three parameters.
  57998. * This does nothing and may be overwritten by the user.
  57999. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58000. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58001. * @param update the boolean update value actually passed to setParticles()
  58002. */
  58003. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58004. };
  58005. return SolidParticleSystem;
  58006. }());
  58007. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58008. })(BABYLON || (BABYLON = {}));
  58009. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58010. "use strict";
  58011. var BABYLON;
  58012. (function (BABYLON) {
  58013. var ShaderMaterial = /** @class */ (function (_super) {
  58014. __extends(ShaderMaterial, _super);
  58015. function ShaderMaterial(name, scene, shaderPath, options) {
  58016. var _this = _super.call(this, name, scene) || this;
  58017. _this._textures = {};
  58018. _this._textureArrays = {};
  58019. _this._floats = {};
  58020. _this._ints = {};
  58021. _this._floatsArrays = {};
  58022. _this._colors3 = {};
  58023. _this._colors3Arrays = {};
  58024. _this._colors4 = {};
  58025. _this._vectors2 = {};
  58026. _this._vectors3 = {};
  58027. _this._vectors4 = {};
  58028. _this._matrices = {};
  58029. _this._matrices3x3 = {};
  58030. _this._matrices2x2 = {};
  58031. _this._vectors2Arrays = {};
  58032. _this._vectors3Arrays = {};
  58033. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58034. _this._shaderPath = shaderPath;
  58035. options.needAlphaBlending = options.needAlphaBlending || false;
  58036. options.needAlphaTesting = options.needAlphaTesting || false;
  58037. options.attributes = options.attributes || ["position", "normal", "uv"];
  58038. options.uniforms = options.uniforms || ["worldViewProjection"];
  58039. options.uniformBuffers = options.uniformBuffers || [];
  58040. options.samplers = options.samplers || [];
  58041. options.defines = options.defines || [];
  58042. _this._options = options;
  58043. return _this;
  58044. }
  58045. ShaderMaterial.prototype.getClassName = function () {
  58046. return "ShaderMaterial";
  58047. };
  58048. ShaderMaterial.prototype.needAlphaBlending = function () {
  58049. return this._options.needAlphaBlending;
  58050. };
  58051. ShaderMaterial.prototype.needAlphaTesting = function () {
  58052. return this._options.needAlphaTesting;
  58053. };
  58054. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58055. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58056. this._options.uniforms.push(uniformName);
  58057. }
  58058. };
  58059. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58060. if (this._options.samplers.indexOf(name) === -1) {
  58061. this._options.samplers.push(name);
  58062. }
  58063. this._textures[name] = texture;
  58064. return this;
  58065. };
  58066. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58067. if (this._options.samplers.indexOf(name) === -1) {
  58068. this._options.samplers.push(name);
  58069. }
  58070. this._checkUniform(name);
  58071. this._textureArrays[name] = textures;
  58072. return this;
  58073. };
  58074. ShaderMaterial.prototype.setFloat = function (name, value) {
  58075. this._checkUniform(name);
  58076. this._floats[name] = value;
  58077. return this;
  58078. };
  58079. ShaderMaterial.prototype.setInt = function (name, value) {
  58080. this._checkUniform(name);
  58081. this._ints[name] = value;
  58082. return this;
  58083. };
  58084. ShaderMaterial.prototype.setFloats = function (name, value) {
  58085. this._checkUniform(name);
  58086. this._floatsArrays[name] = value;
  58087. return this;
  58088. };
  58089. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58090. this._checkUniform(name);
  58091. this._colors3[name] = value;
  58092. return this;
  58093. };
  58094. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58095. this._checkUniform(name);
  58096. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58097. color.toArray(arr, arr.length);
  58098. return arr;
  58099. }, []);
  58100. return this;
  58101. };
  58102. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58103. this._checkUniform(name);
  58104. this._colors4[name] = value;
  58105. return this;
  58106. };
  58107. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58108. this._checkUniform(name);
  58109. this._vectors2[name] = value;
  58110. return this;
  58111. };
  58112. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58113. this._checkUniform(name);
  58114. this._vectors3[name] = value;
  58115. return this;
  58116. };
  58117. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58118. this._checkUniform(name);
  58119. this._vectors4[name] = value;
  58120. return this;
  58121. };
  58122. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58123. this._checkUniform(name);
  58124. this._matrices[name] = value;
  58125. return this;
  58126. };
  58127. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58128. this._checkUniform(name);
  58129. this._matrices3x3[name] = value;
  58130. return this;
  58131. };
  58132. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58133. this._checkUniform(name);
  58134. this._matrices2x2[name] = value;
  58135. return this;
  58136. };
  58137. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58138. this._checkUniform(name);
  58139. this._vectors2Arrays[name] = value;
  58140. return this;
  58141. };
  58142. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58143. this._checkUniform(name);
  58144. this._vectors3Arrays[name] = value;
  58145. return this;
  58146. };
  58147. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58148. if (!mesh) {
  58149. return true;
  58150. }
  58151. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58152. return false;
  58153. }
  58154. return false;
  58155. };
  58156. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58157. var scene = this.getScene();
  58158. var engine = scene.getEngine();
  58159. if (!this.checkReadyOnEveryCall) {
  58160. if (this._renderId === scene.getRenderId()) {
  58161. if (this._checkCache(scene, mesh, useInstances)) {
  58162. return true;
  58163. }
  58164. }
  58165. }
  58166. // Instances
  58167. var defines = [];
  58168. var attribs = [];
  58169. var fallbacks = new BABYLON.EffectFallbacks();
  58170. if (useInstances) {
  58171. defines.push("#define INSTANCES");
  58172. }
  58173. for (var index = 0; index < this._options.defines.length; index++) {
  58174. defines.push(this._options.defines[index]);
  58175. }
  58176. for (var index = 0; index < this._options.attributes.length; index++) {
  58177. attribs.push(this._options.attributes[index]);
  58178. }
  58179. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58180. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58181. defines.push("#define VERTEXCOLOR");
  58182. }
  58183. // Bones
  58184. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58185. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58186. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58187. if (mesh.numBoneInfluencers > 4) {
  58188. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58189. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58190. }
  58191. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58192. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58193. fallbacks.addCPUSkinningFallback(0, mesh);
  58194. if (this._options.uniforms.indexOf("mBones") === -1) {
  58195. this._options.uniforms.push("mBones");
  58196. }
  58197. }
  58198. else {
  58199. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58200. }
  58201. // Textures
  58202. for (var name in this._textures) {
  58203. if (!this._textures[name].isReady()) {
  58204. return false;
  58205. }
  58206. }
  58207. // Alpha test
  58208. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58209. defines.push("#define ALPHATEST");
  58210. }
  58211. var previousEffect = this._effect;
  58212. var join = defines.join("\n");
  58213. this._effect = engine.createEffect(this._shaderPath, {
  58214. attributes: attribs,
  58215. uniformsNames: this._options.uniforms,
  58216. uniformBuffersNames: this._options.uniformBuffers,
  58217. samplers: this._options.samplers,
  58218. defines: join,
  58219. fallbacks: fallbacks,
  58220. onCompiled: this.onCompiled,
  58221. onError: this.onError
  58222. }, engine);
  58223. if (!this._effect.isReady()) {
  58224. return false;
  58225. }
  58226. if (previousEffect !== this._effect) {
  58227. scene.resetCachedMaterial();
  58228. }
  58229. this._renderId = scene.getRenderId();
  58230. return true;
  58231. };
  58232. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58233. var scene = this.getScene();
  58234. if (!this._effect) {
  58235. return;
  58236. }
  58237. if (this._options.uniforms.indexOf("world") !== -1) {
  58238. this._effect.setMatrix("world", world);
  58239. }
  58240. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58241. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58242. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58243. }
  58244. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58245. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58246. }
  58247. };
  58248. ShaderMaterial.prototype.bind = function (world, mesh) {
  58249. // Std values
  58250. this.bindOnlyWorldMatrix(world);
  58251. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58252. if (this._options.uniforms.indexOf("view") !== -1) {
  58253. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58254. }
  58255. if (this._options.uniforms.indexOf("projection") !== -1) {
  58256. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58257. }
  58258. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58259. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58260. }
  58261. // Bones
  58262. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58263. var name;
  58264. // Texture
  58265. for (name in this._textures) {
  58266. this._effect.setTexture(name, this._textures[name]);
  58267. }
  58268. // Texture arrays
  58269. for (name in this._textureArrays) {
  58270. this._effect.setTextureArray(name, this._textureArrays[name]);
  58271. }
  58272. // Int
  58273. for (name in this._ints) {
  58274. this._effect.setInt(name, this._ints[name]);
  58275. }
  58276. // Float
  58277. for (name in this._floats) {
  58278. this._effect.setFloat(name, this._floats[name]);
  58279. }
  58280. // Floats
  58281. for (name in this._floatsArrays) {
  58282. this._effect.setArray(name, this._floatsArrays[name]);
  58283. }
  58284. // Color3
  58285. for (name in this._colors3) {
  58286. this._effect.setColor3(name, this._colors3[name]);
  58287. }
  58288. for (name in this._colors3Arrays) {
  58289. this._effect.setArray3(name, this._colors3Arrays[name]);
  58290. }
  58291. // Color4
  58292. for (name in this._colors4) {
  58293. var color = this._colors4[name];
  58294. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58295. }
  58296. // Vector2
  58297. for (name in this._vectors2) {
  58298. this._effect.setVector2(name, this._vectors2[name]);
  58299. }
  58300. // Vector3
  58301. for (name in this._vectors3) {
  58302. this._effect.setVector3(name, this._vectors3[name]);
  58303. }
  58304. // Vector4
  58305. for (name in this._vectors4) {
  58306. this._effect.setVector4(name, this._vectors4[name]);
  58307. }
  58308. // Matrix
  58309. for (name in this._matrices) {
  58310. this._effect.setMatrix(name, this._matrices[name]);
  58311. }
  58312. // Matrix 3x3
  58313. for (name in this._matrices3x3) {
  58314. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58315. }
  58316. // Matrix 2x2
  58317. for (name in this._matrices2x2) {
  58318. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58319. }
  58320. // Vector2Array
  58321. for (name in this._vectors2Arrays) {
  58322. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58323. }
  58324. // Vector3Array
  58325. for (name in this._vectors3Arrays) {
  58326. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58327. }
  58328. }
  58329. this._afterBind(mesh);
  58330. };
  58331. ShaderMaterial.prototype.getActiveTextures = function () {
  58332. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58333. for (var name in this._textures) {
  58334. activeTextures.push(this._textures[name]);
  58335. }
  58336. for (var name in this._textureArrays) {
  58337. var array = this._textureArrays[name];
  58338. for (var index = 0; index < array.length; index++) {
  58339. activeTextures.push(array[index]);
  58340. }
  58341. }
  58342. return activeTextures;
  58343. };
  58344. ShaderMaterial.prototype.hasTexture = function (texture) {
  58345. if (_super.prototype.hasTexture.call(this, texture)) {
  58346. return true;
  58347. }
  58348. for (var name in this._textures) {
  58349. if (this._textures[name] === texture) {
  58350. return true;
  58351. }
  58352. }
  58353. for (var name in this._textureArrays) {
  58354. var array = this._textureArrays[name];
  58355. for (var index = 0; index < array.length; index++) {
  58356. if (array[index] === texture) {
  58357. return true;
  58358. }
  58359. }
  58360. }
  58361. return false;
  58362. };
  58363. ShaderMaterial.prototype.clone = function (name) {
  58364. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58365. return newShaderMaterial;
  58366. };
  58367. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58368. if (forceDisposeTextures) {
  58369. var name;
  58370. for (name in this._textures) {
  58371. this._textures[name].dispose();
  58372. }
  58373. for (name in this._textureArrays) {
  58374. var array = this._textureArrays[name];
  58375. for (var index = 0; index < array.length; index++) {
  58376. array[index].dispose();
  58377. }
  58378. }
  58379. }
  58380. this._textures = {};
  58381. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58382. };
  58383. ShaderMaterial.prototype.serialize = function () {
  58384. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58385. serializationObject.customType = "BABYLON.ShaderMaterial";
  58386. serializationObject.options = this._options;
  58387. serializationObject.shaderPath = this._shaderPath;
  58388. var name;
  58389. // Texture
  58390. serializationObject.textures = {};
  58391. for (name in this._textures) {
  58392. serializationObject.textures[name] = this._textures[name].serialize();
  58393. }
  58394. // Texture arrays
  58395. serializationObject.textureArrays = {};
  58396. for (name in this._textureArrays) {
  58397. serializationObject.textureArrays[name] = [];
  58398. var array = this._textureArrays[name];
  58399. for (var index = 0; index < array.length; index++) {
  58400. serializationObject.textureArrays[name].push(array[index].serialize());
  58401. }
  58402. }
  58403. // Float
  58404. serializationObject.floats = {};
  58405. for (name in this._floats) {
  58406. serializationObject.floats[name] = this._floats[name];
  58407. }
  58408. // Float s
  58409. serializationObject.FloatArrays = {};
  58410. for (name in this._floatsArrays) {
  58411. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58412. }
  58413. // Color3
  58414. serializationObject.colors3 = {};
  58415. for (name in this._colors3) {
  58416. serializationObject.colors3[name] = this._colors3[name].asArray();
  58417. }
  58418. // Color3 array
  58419. serializationObject.colors3Arrays = {};
  58420. for (name in this._colors3Arrays) {
  58421. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58422. }
  58423. // Color4
  58424. serializationObject.colors4 = {};
  58425. for (name in this._colors4) {
  58426. serializationObject.colors4[name] = this._colors4[name].asArray();
  58427. }
  58428. // Vector2
  58429. serializationObject.vectors2 = {};
  58430. for (name in this._vectors2) {
  58431. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58432. }
  58433. // Vector3
  58434. serializationObject.vectors3 = {};
  58435. for (name in this._vectors3) {
  58436. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58437. }
  58438. // Vector4
  58439. serializationObject.vectors4 = {};
  58440. for (name in this._vectors4) {
  58441. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58442. }
  58443. // Matrix
  58444. serializationObject.matrices = {};
  58445. for (name in this._matrices) {
  58446. serializationObject.matrices[name] = this._matrices[name].asArray();
  58447. }
  58448. // Matrix 3x3
  58449. serializationObject.matrices3x3 = {};
  58450. for (name in this._matrices3x3) {
  58451. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58452. }
  58453. // Matrix 2x2
  58454. serializationObject.matrices2x2 = {};
  58455. for (name in this._matrices2x2) {
  58456. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58457. }
  58458. // Vector2Array
  58459. serializationObject.vectors2Arrays = {};
  58460. for (name in this._vectors2Arrays) {
  58461. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58462. }
  58463. // Vector3Array
  58464. serializationObject.vectors3Arrays = {};
  58465. for (name in this._vectors3Arrays) {
  58466. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58467. }
  58468. return serializationObject;
  58469. };
  58470. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58471. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58472. var name;
  58473. // Texture
  58474. for (name in source.textures) {
  58475. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58476. }
  58477. // Texture arrays
  58478. for (name in source.textureArrays) {
  58479. var array = source.textureArrays[name];
  58480. var textureArray = new Array();
  58481. for (var index = 0; index < array.length; index++) {
  58482. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58483. }
  58484. material.setTextureArray(name, textureArray);
  58485. }
  58486. // Float
  58487. for (name in source.floats) {
  58488. material.setFloat(name, source.floats[name]);
  58489. }
  58490. // Float s
  58491. for (name in source.floatsArrays) {
  58492. material.setFloats(name, source.floatsArrays[name]);
  58493. }
  58494. // Color3
  58495. for (name in source.colors3) {
  58496. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58497. }
  58498. // Color3 arrays
  58499. for (name in source.colors3Arrays) {
  58500. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58501. if (i % 3 === 0) {
  58502. arr.push([num]);
  58503. }
  58504. else {
  58505. arr[arr.length - 1].push(num);
  58506. }
  58507. return arr;
  58508. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58509. material.setColor3Array(name, colors);
  58510. }
  58511. // Color4
  58512. for (name in source.colors4) {
  58513. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58514. }
  58515. // Vector2
  58516. for (name in source.vectors2) {
  58517. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58518. }
  58519. // Vector3
  58520. for (name in source.vectors3) {
  58521. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58522. }
  58523. // Vector4
  58524. for (name in source.vectors4) {
  58525. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58526. }
  58527. // Matrix
  58528. for (name in source.matrices) {
  58529. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58530. }
  58531. // Matrix 3x3
  58532. for (name in source.matrices3x3) {
  58533. material.setMatrix3x3(name, source.matrices3x3[name]);
  58534. }
  58535. // Matrix 2x2
  58536. for (name in source.matrices2x2) {
  58537. material.setMatrix2x2(name, source.matrices2x2[name]);
  58538. }
  58539. // Vector2Array
  58540. for (name in source.vectors2Arrays) {
  58541. material.setArray2(name, source.vectors2Arrays[name]);
  58542. }
  58543. // Vector3Array
  58544. for (name in source.vectors3Arrays) {
  58545. material.setArray3(name, source.vectors3Arrays[name]);
  58546. }
  58547. return material;
  58548. };
  58549. return ShaderMaterial;
  58550. }(BABYLON.Material));
  58551. BABYLON.ShaderMaterial = ShaderMaterial;
  58552. })(BABYLON || (BABYLON = {}));
  58553. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58554. "use strict";
  58555. var BABYLON;
  58556. (function (BABYLON) {
  58557. var GroundMesh = /** @class */ (function (_super) {
  58558. __extends(GroundMesh, _super);
  58559. function GroundMesh(name, scene) {
  58560. var _this = _super.call(this, name, scene) || this;
  58561. _this.generateOctree = false;
  58562. return _this;
  58563. }
  58564. GroundMesh.prototype.getClassName = function () {
  58565. return "GroundMesh";
  58566. };
  58567. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58568. get: function () {
  58569. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58570. },
  58571. enumerable: true,
  58572. configurable: true
  58573. });
  58574. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58575. get: function () {
  58576. return this._subdivisionsX;
  58577. },
  58578. enumerable: true,
  58579. configurable: true
  58580. });
  58581. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58582. get: function () {
  58583. return this._subdivisionsY;
  58584. },
  58585. enumerable: true,
  58586. configurable: true
  58587. });
  58588. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58589. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58590. this._subdivisionsX = chunksCount;
  58591. this._subdivisionsY = chunksCount;
  58592. this.subdivide(chunksCount);
  58593. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58594. };
  58595. /**
  58596. * Returns a height (y) value in the Worl system :
  58597. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58598. * Returns the ground y position if (x, z) are outside the ground surface.
  58599. */
  58600. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58601. var world = this.getWorldMatrix();
  58602. var invMat = BABYLON.Tmp.Matrix[5];
  58603. world.invertToRef(invMat);
  58604. var tmpVect = BABYLON.Tmp.Vector3[8];
  58605. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58606. x = tmpVect.x;
  58607. z = tmpVect.z;
  58608. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58609. return this.position.y;
  58610. }
  58611. if (!this._heightQuads || this._heightQuads.length == 0) {
  58612. this._initHeightQuads();
  58613. this._computeHeightQuads();
  58614. }
  58615. var facet = this._getFacetAt(x, z);
  58616. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58617. // return y in the World system
  58618. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58619. return tmpVect.y;
  58620. };
  58621. /**
  58622. * Returns a normalized vector (Vector3) orthogonal to the ground
  58623. * at the ground coordinates (x, z) expressed in the World system.
  58624. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58625. */
  58626. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58627. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58628. this.getNormalAtCoordinatesToRef(x, z, normal);
  58629. return normal;
  58630. };
  58631. /**
  58632. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58633. * at the ground coordinates (x, z) expressed in the World system.
  58634. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58635. * Returns the GroundMesh.
  58636. */
  58637. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58638. var world = this.getWorldMatrix();
  58639. var tmpMat = BABYLON.Tmp.Matrix[5];
  58640. world.invertToRef(tmpMat);
  58641. var tmpVect = BABYLON.Tmp.Vector3[8];
  58642. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58643. x = tmpVect.x;
  58644. z = tmpVect.z;
  58645. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58646. return this;
  58647. }
  58648. if (!this._heightQuads || this._heightQuads.length == 0) {
  58649. this._initHeightQuads();
  58650. this._computeHeightQuads();
  58651. }
  58652. var facet = this._getFacetAt(x, z);
  58653. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58654. return this;
  58655. };
  58656. /**
  58657. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58658. * if the ground has been updated.
  58659. * This can be used in the render loop.
  58660. * Returns the GroundMesh.
  58661. */
  58662. GroundMesh.prototype.updateCoordinateHeights = function () {
  58663. if (!this._heightQuads || this._heightQuads.length == 0) {
  58664. this._initHeightQuads();
  58665. }
  58666. this._computeHeightQuads();
  58667. return this;
  58668. };
  58669. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58670. GroundMesh.prototype._getFacetAt = function (x, z) {
  58671. // retrieve col and row from x, z coordinates in the ground local system
  58672. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58673. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58674. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58675. var facet;
  58676. if (z < quad.slope.x * x + quad.slope.y) {
  58677. facet = quad.facet1;
  58678. }
  58679. else {
  58680. facet = quad.facet2;
  58681. }
  58682. return facet;
  58683. };
  58684. // Creates and populates the heightMap array with "facet" elements :
  58685. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58686. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58687. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58688. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58689. // Returns the GroundMesh.
  58690. GroundMesh.prototype._initHeightQuads = function () {
  58691. var subdivisionsX = this._subdivisionsX;
  58692. var subdivisionsY = this._subdivisionsY;
  58693. this._heightQuads = new Array();
  58694. for (var row = 0; row < subdivisionsY; row++) {
  58695. for (var col = 0; col < subdivisionsX; col++) {
  58696. 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) };
  58697. this._heightQuads[row * subdivisionsX + col] = quad;
  58698. }
  58699. }
  58700. return this;
  58701. };
  58702. // Compute each quad element values and update the the heightMap array :
  58703. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58704. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58705. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58706. // Returns the GroundMesh.
  58707. GroundMesh.prototype._computeHeightQuads = function () {
  58708. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58709. if (!positions) {
  58710. return this;
  58711. }
  58712. var v1 = BABYLON.Tmp.Vector3[3];
  58713. var v2 = BABYLON.Tmp.Vector3[2];
  58714. var v3 = BABYLON.Tmp.Vector3[1];
  58715. var v4 = BABYLON.Tmp.Vector3[0];
  58716. var v1v2 = BABYLON.Tmp.Vector3[4];
  58717. var v1v3 = BABYLON.Tmp.Vector3[5];
  58718. var v1v4 = BABYLON.Tmp.Vector3[6];
  58719. var norm1 = BABYLON.Tmp.Vector3[7];
  58720. var norm2 = BABYLON.Tmp.Vector3[8];
  58721. var i = 0;
  58722. var j = 0;
  58723. var k = 0;
  58724. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58725. var h = 0;
  58726. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58727. var d2 = 0;
  58728. var subdivisionsX = this._subdivisionsX;
  58729. var subdivisionsY = this._subdivisionsY;
  58730. for (var row = 0; row < subdivisionsY; row++) {
  58731. for (var col = 0; col < subdivisionsX; col++) {
  58732. i = col * 3;
  58733. j = row * (subdivisionsX + 1) * 3;
  58734. k = (row + 1) * (subdivisionsX + 1) * 3;
  58735. v1.x = positions[j + i];
  58736. v1.y = positions[j + i + 1];
  58737. v1.z = positions[j + i + 2];
  58738. v2.x = positions[j + i + 3];
  58739. v2.y = positions[j + i + 4];
  58740. v2.z = positions[j + i + 5];
  58741. v3.x = positions[k + i];
  58742. v3.y = positions[k + i + 1];
  58743. v3.z = positions[k + i + 2];
  58744. v4.x = positions[k + i + 3];
  58745. v4.y = positions[k + i + 4];
  58746. v4.z = positions[k + i + 5];
  58747. // 2D slope V1V4
  58748. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58749. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58750. // facet equations :
  58751. // we compute each facet normal vector
  58752. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58753. // we compute the value d by applying the equation to v1 which belongs to the plane
  58754. // then we store the facet equation in a Vector4
  58755. v2.subtractToRef(v1, v1v2);
  58756. v3.subtractToRef(v1, v1v3);
  58757. v4.subtractToRef(v1, v1v4);
  58758. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58759. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58760. norm1.normalize();
  58761. norm2.normalize();
  58762. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58763. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58764. var quad = this._heightQuads[row * subdivisionsX + col];
  58765. quad.slope.copyFromFloats(cd, h);
  58766. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58767. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58768. }
  58769. }
  58770. return this;
  58771. };
  58772. GroundMesh.prototype.serialize = function (serializationObject) {
  58773. _super.prototype.serialize.call(this, serializationObject);
  58774. serializationObject.subdivisionsX = this._subdivisionsX;
  58775. serializationObject.subdivisionsY = this._subdivisionsY;
  58776. serializationObject.minX = this._minX;
  58777. serializationObject.maxX = this._maxX;
  58778. serializationObject.minZ = this._minZ;
  58779. serializationObject.maxZ = this._maxZ;
  58780. serializationObject.width = this._width;
  58781. serializationObject.height = this._height;
  58782. };
  58783. GroundMesh.Parse = function (parsedMesh, scene) {
  58784. var result = new GroundMesh(parsedMesh.name, scene);
  58785. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58786. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58787. result._minX = parsedMesh.minX;
  58788. result._maxX = parsedMesh.maxX;
  58789. result._minZ = parsedMesh.minZ;
  58790. result._maxZ = parsedMesh.maxZ;
  58791. result._width = parsedMesh.width;
  58792. result._height = parsedMesh.height;
  58793. return result;
  58794. };
  58795. return GroundMesh;
  58796. }(BABYLON.Mesh));
  58797. BABYLON.GroundMesh = GroundMesh;
  58798. })(BABYLON || (BABYLON = {}));
  58799. //# sourceMappingURL=babylon.groundMesh.js.map
  58800. "use strict";
  58801. var BABYLON;
  58802. (function (BABYLON) {
  58803. /**
  58804. * Creates an instance based on a source mesh.
  58805. */
  58806. var InstancedMesh = /** @class */ (function (_super) {
  58807. __extends(InstancedMesh, _super);
  58808. function InstancedMesh(name, source) {
  58809. var _this = _super.call(this, name, source.getScene()) || this;
  58810. source.instances.push(_this);
  58811. _this._sourceMesh = source;
  58812. _this.position.copyFrom(source.position);
  58813. _this.rotation.copyFrom(source.rotation);
  58814. _this.scaling.copyFrom(source.scaling);
  58815. if (source.rotationQuaternion) {
  58816. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58817. }
  58818. _this.infiniteDistance = source.infiniteDistance;
  58819. _this.setPivotMatrix(source.getPivotMatrix());
  58820. _this.refreshBoundingInfo();
  58821. _this._syncSubMeshes();
  58822. return _this;
  58823. }
  58824. /**
  58825. * Returns the string "InstancedMesh".
  58826. */
  58827. InstancedMesh.prototype.getClassName = function () {
  58828. return "InstancedMesh";
  58829. };
  58830. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58831. // Methods
  58832. get: function () {
  58833. return this._sourceMesh.receiveShadows;
  58834. },
  58835. enumerable: true,
  58836. configurable: true
  58837. });
  58838. Object.defineProperty(InstancedMesh.prototype, "material", {
  58839. get: function () {
  58840. return this._sourceMesh.material;
  58841. },
  58842. enumerable: true,
  58843. configurable: true
  58844. });
  58845. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58846. get: function () {
  58847. return this._sourceMesh.visibility;
  58848. },
  58849. enumerable: true,
  58850. configurable: true
  58851. });
  58852. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58853. get: function () {
  58854. return this._sourceMesh.skeleton;
  58855. },
  58856. enumerable: true,
  58857. configurable: true
  58858. });
  58859. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58860. get: function () {
  58861. return this._sourceMesh.renderingGroupId;
  58862. },
  58863. set: function (value) {
  58864. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58865. return;
  58866. }
  58867. //no-op with warning
  58868. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58869. },
  58870. enumerable: true,
  58871. configurable: true
  58872. });
  58873. /**
  58874. * Returns the total number of vertices (integer).
  58875. */
  58876. InstancedMesh.prototype.getTotalVertices = function () {
  58877. return this._sourceMesh.getTotalVertices();
  58878. };
  58879. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58880. get: function () {
  58881. return this._sourceMesh;
  58882. },
  58883. enumerable: true,
  58884. configurable: true
  58885. });
  58886. /**
  58887. * Is this node ready to be used/rendered
  58888. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58889. * @return {boolean} is it ready
  58890. */
  58891. InstancedMesh.prototype.isReady = function (completeCheck) {
  58892. if (completeCheck === void 0) { completeCheck = false; }
  58893. return this._sourceMesh.isReady(completeCheck, true);
  58894. };
  58895. /**
  58896. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58897. */
  58898. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58899. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58900. };
  58901. /**
  58902. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58903. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58904. * The `data` are either a numeric array either a Float32Array.
  58905. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58906. * 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).
  58907. * Note that a new underlying VertexBuffer object is created each call.
  58908. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58909. *
  58910. * Possible `kind` values :
  58911. * - BABYLON.VertexBuffer.PositionKind
  58912. * - BABYLON.VertexBuffer.UVKind
  58913. * - BABYLON.VertexBuffer.UV2Kind
  58914. * - BABYLON.VertexBuffer.UV3Kind
  58915. * - BABYLON.VertexBuffer.UV4Kind
  58916. * - BABYLON.VertexBuffer.UV5Kind
  58917. * - BABYLON.VertexBuffer.UV6Kind
  58918. * - BABYLON.VertexBuffer.ColorKind
  58919. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58920. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58921. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58922. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58923. *
  58924. * Returns the Mesh.
  58925. */
  58926. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58927. if (this.sourceMesh) {
  58928. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58929. }
  58930. return this.sourceMesh;
  58931. };
  58932. /**
  58933. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58934. * If the mesh has no geometry, it is simply returned as it is.
  58935. * The `data` are either a numeric array either a Float32Array.
  58936. * No new underlying VertexBuffer object is created.
  58937. * 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.
  58938. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58939. *
  58940. * Possible `kind` values :
  58941. * - BABYLON.VertexBuffer.PositionKind
  58942. * - BABYLON.VertexBuffer.UVKind
  58943. * - BABYLON.VertexBuffer.UV2Kind
  58944. * - BABYLON.VertexBuffer.UV3Kind
  58945. * - BABYLON.VertexBuffer.UV4Kind
  58946. * - BABYLON.VertexBuffer.UV5Kind
  58947. * - BABYLON.VertexBuffer.UV6Kind
  58948. * - BABYLON.VertexBuffer.ColorKind
  58949. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58950. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58951. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58952. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58953. *
  58954. * Returns the Mesh.
  58955. */
  58956. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58957. if (this.sourceMesh) {
  58958. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58959. }
  58960. return this.sourceMesh;
  58961. };
  58962. /**
  58963. * Sets the mesh indices.
  58964. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58965. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58966. * This method creates a new index buffer each call.
  58967. * Returns the Mesh.
  58968. */
  58969. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58970. if (totalVertices === void 0) { totalVertices = null; }
  58971. if (this.sourceMesh) {
  58972. this.sourceMesh.setIndices(indices, totalVertices);
  58973. }
  58974. return this.sourceMesh;
  58975. };
  58976. /**
  58977. * Boolean : True if the mesh owns the requested kind of data.
  58978. */
  58979. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58980. return this._sourceMesh.isVerticesDataPresent(kind);
  58981. };
  58982. /**
  58983. * Returns an array of indices (IndicesArray).
  58984. */
  58985. InstancedMesh.prototype.getIndices = function () {
  58986. return this._sourceMesh.getIndices();
  58987. };
  58988. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58989. get: function () {
  58990. return this._sourceMesh._positions;
  58991. },
  58992. enumerable: true,
  58993. configurable: true
  58994. });
  58995. /**
  58996. * Sets a new updated BoundingInfo to the mesh.
  58997. * Returns the mesh.
  58998. */
  58999. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59000. var meshBB = this._sourceMesh.getBoundingInfo();
  59001. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59002. this._updateBoundingInfo();
  59003. return this;
  59004. };
  59005. InstancedMesh.prototype._preActivate = function () {
  59006. if (this._currentLOD) {
  59007. this._currentLOD._preActivate();
  59008. }
  59009. return this;
  59010. };
  59011. InstancedMesh.prototype._activate = function (renderId) {
  59012. if (this._currentLOD) {
  59013. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59014. }
  59015. return this;
  59016. };
  59017. /**
  59018. * Returns the current associated LOD AbstractMesh.
  59019. */
  59020. InstancedMesh.prototype.getLOD = function (camera) {
  59021. if (!camera) {
  59022. return this;
  59023. }
  59024. var boundingInfo = this.getBoundingInfo();
  59025. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59026. if (this._currentLOD === this.sourceMesh) {
  59027. return this;
  59028. }
  59029. return this._currentLOD;
  59030. };
  59031. InstancedMesh.prototype._syncSubMeshes = function () {
  59032. this.releaseSubMeshes();
  59033. if (this._sourceMesh.subMeshes) {
  59034. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59035. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59036. }
  59037. }
  59038. return this;
  59039. };
  59040. InstancedMesh.prototype._generatePointsArray = function () {
  59041. return this._sourceMesh._generatePointsArray();
  59042. };
  59043. /**
  59044. * Creates a new InstancedMesh from the current mesh.
  59045. * - name (string) : the cloned mesh name
  59046. * - newParent (optional Node) : the optional Node to parent the clone to.
  59047. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59048. *
  59049. * Returns the clone.
  59050. */
  59051. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59052. var result = this._sourceMesh.createInstance(name);
  59053. // Deep copy
  59054. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59055. // Bounding info
  59056. this.refreshBoundingInfo();
  59057. // Parent
  59058. if (newParent) {
  59059. result.parent = newParent;
  59060. }
  59061. if (!doNotCloneChildren) {
  59062. // Children
  59063. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59064. var mesh = this.getScene().meshes[index];
  59065. if (mesh.parent === this) {
  59066. mesh.clone(mesh.name, result);
  59067. }
  59068. }
  59069. }
  59070. result.computeWorldMatrix(true);
  59071. return result;
  59072. };
  59073. /**
  59074. * Disposes the InstancedMesh.
  59075. * Returns nothing.
  59076. */
  59077. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59078. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59079. // Remove from mesh
  59080. var index = this._sourceMesh.instances.indexOf(this);
  59081. this._sourceMesh.instances.splice(index, 1);
  59082. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59083. };
  59084. return InstancedMesh;
  59085. }(BABYLON.AbstractMesh));
  59086. BABYLON.InstancedMesh = InstancedMesh;
  59087. })(BABYLON || (BABYLON = {}));
  59088. //# sourceMappingURL=babylon.instancedMesh.js.map
  59089. "use strict";
  59090. var BABYLON;
  59091. (function (BABYLON) {
  59092. var LinesMesh = /** @class */ (function (_super) {
  59093. __extends(LinesMesh, _super);
  59094. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59095. if (scene === void 0) { scene = null; }
  59096. if (parent === void 0) { parent = null; }
  59097. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59098. _this.useVertexColor = useVertexColor;
  59099. _this.useVertexAlpha = useVertexAlpha;
  59100. _this.color = new BABYLON.Color3(1, 1, 1);
  59101. _this.alpha = 1;
  59102. if (source) {
  59103. _this.color = source.color.clone();
  59104. _this.alpha = source.alpha;
  59105. _this.useVertexColor = source.useVertexColor;
  59106. _this.useVertexAlpha = source.useVertexAlpha;
  59107. }
  59108. _this._intersectionThreshold = 0.1;
  59109. var defines = [];
  59110. var options = {
  59111. attributes: [BABYLON.VertexBuffer.PositionKind],
  59112. uniforms: ["world", "viewProjection"],
  59113. needAlphaBlending: true,
  59114. defines: defines
  59115. };
  59116. if (useVertexAlpha === false) {
  59117. options.needAlphaBlending = false;
  59118. }
  59119. if (!useVertexColor) {
  59120. options.uniforms.push("color");
  59121. }
  59122. else {
  59123. options.defines.push("#define VERTEXCOLOR");
  59124. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59125. }
  59126. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59127. return _this;
  59128. }
  59129. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59130. /**
  59131. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59132. * This margin is expressed in world space coordinates, so its value may vary.
  59133. * Default value is 0.1
  59134. * @returns the intersection Threshold value.
  59135. */
  59136. get: function () {
  59137. return this._intersectionThreshold;
  59138. },
  59139. /**
  59140. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59141. * This margin is expressed in world space coordinates, so its value may vary.
  59142. * @param value the new threshold to apply
  59143. */
  59144. set: function (value) {
  59145. if (this._intersectionThreshold === value) {
  59146. return;
  59147. }
  59148. this._intersectionThreshold = value;
  59149. if (this.geometry) {
  59150. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59151. }
  59152. },
  59153. enumerable: true,
  59154. configurable: true
  59155. });
  59156. /**
  59157. * Returns the string "LineMesh"
  59158. */
  59159. LinesMesh.prototype.getClassName = function () {
  59160. return "LinesMesh";
  59161. };
  59162. Object.defineProperty(LinesMesh.prototype, "material", {
  59163. get: function () {
  59164. return this._colorShader;
  59165. },
  59166. set: function (value) {
  59167. // Do nothing
  59168. },
  59169. enumerable: true,
  59170. configurable: true
  59171. });
  59172. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59173. get: function () {
  59174. return false;
  59175. },
  59176. enumerable: true,
  59177. configurable: true
  59178. });
  59179. LinesMesh.prototype.createInstance = function (name) {
  59180. throw new Error("LinesMeshes do not support createInstance.");
  59181. };
  59182. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59183. if (!this._geometry) {
  59184. return this;
  59185. }
  59186. // VBOs
  59187. this._geometry._bind(this._colorShader.getEffect());
  59188. // Color
  59189. if (!this.useVertexColor) {
  59190. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59191. }
  59192. return this;
  59193. };
  59194. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59195. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59196. return this;
  59197. }
  59198. var engine = this.getScene().getEngine();
  59199. // Draw order
  59200. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59201. return this;
  59202. };
  59203. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59204. this._colorShader.dispose();
  59205. _super.prototype.dispose.call(this, doNotRecurse);
  59206. };
  59207. /**
  59208. * Returns a new LineMesh object cloned from the current one.
  59209. */
  59210. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59211. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59212. };
  59213. return LinesMesh;
  59214. }(BABYLON.Mesh));
  59215. BABYLON.LinesMesh = LinesMesh;
  59216. })(BABYLON || (BABYLON = {}));
  59217. //# sourceMappingURL=babylon.linesMesh.js.map
  59218. "use strict";
  59219. var BABYLON;
  59220. (function (BABYLON) {
  59221. /**
  59222. * Class containing static functions to help procedurally build meshes
  59223. */
  59224. var MeshBuilder = /** @class */ (function () {
  59225. function MeshBuilder() {
  59226. }
  59227. MeshBuilder.updateSideOrientation = function (orientation) {
  59228. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59229. return BABYLON.Mesh.DOUBLESIDE;
  59230. }
  59231. if (orientation === undefined || orientation === null) {
  59232. return BABYLON.Mesh.FRONTSIDE;
  59233. }
  59234. return orientation;
  59235. };
  59236. /**
  59237. * Creates a box mesh
  59238. * * The parameter `size` sets the size (float) of each box side (default 1)
  59239. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59240. * * 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)
  59241. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59242. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59243. * * 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
  59244. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59245. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59246. * @param name defines the name of the mesh
  59247. * @param options defines the options used to create the mesh
  59248. * @param scene defines the hosting scene
  59249. * @returns the box mesh
  59250. */
  59251. MeshBuilder.CreateBox = function (name, options, scene) {
  59252. if (scene === void 0) { scene = null; }
  59253. var box = new BABYLON.Mesh(name, scene);
  59254. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59255. box._originalBuilderSideOrientation = options.sideOrientation;
  59256. var vertexData = BABYLON.VertexData.CreateBox(options);
  59257. vertexData.applyToMesh(box, options.updatable);
  59258. return box;
  59259. };
  59260. /**
  59261. * Creates a sphere mesh
  59262. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59263. * * 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`)
  59264. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59265. * * 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
  59266. * * 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)
  59267. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59268. * * 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
  59269. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59270. * @param name defines the name of the mesh
  59271. * @param options defines the options used to create the mesh
  59272. * @param scene defines the hosting scene
  59273. * @returns the sphere mesh
  59274. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59275. */
  59276. MeshBuilder.CreateSphere = function (name, options, scene) {
  59277. var sphere = new BABYLON.Mesh(name, scene);
  59278. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59279. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59280. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59281. vertexData.applyToMesh(sphere, options.updatable);
  59282. return sphere;
  59283. };
  59284. /**
  59285. * Creates a plane polygonal mesh. By default, this is a disc
  59286. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59287. * * 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
  59288. * * 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
  59289. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59290. * * 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
  59291. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59292. * @param name defines the name of the mesh
  59293. * @param options defines the options used to create the mesh
  59294. * @param scene defines the hosting scene
  59295. * @returns the plane polygonal mesh
  59296. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  59297. */
  59298. MeshBuilder.CreateDisc = function (name, options, scene) {
  59299. if (scene === void 0) { scene = null; }
  59300. var disc = new BABYLON.Mesh(name, scene);
  59301. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59302. disc._originalBuilderSideOrientation = options.sideOrientation;
  59303. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59304. vertexData.applyToMesh(disc, options.updatable);
  59305. return disc;
  59306. };
  59307. /**
  59308. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59309. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59310. * * 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`)
  59311. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59312. * * 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
  59313. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59314. * * 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
  59315. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59316. * @param name defines the name of the mesh
  59317. * @param options defines the options used to create the mesh
  59318. * @param scene defines the hosting scene
  59319. * @returns the icosahedron mesh
  59320. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  59321. */
  59322. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59323. var sphere = new BABYLON.Mesh(name, scene);
  59324. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59325. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59326. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59327. vertexData.applyToMesh(sphere, options.updatable);
  59328. return sphere;
  59329. };
  59330. ;
  59331. /**
  59332. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59333. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59334. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59335. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59336. * * 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
  59337. * * 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
  59338. * * 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
  59339. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59340. * * 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
  59341. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59342. * * 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
  59343. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59344. * * 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
  59345. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59346. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59347. * @param name defines the name of the mesh
  59348. * @param options defines the options used to create the mesh
  59349. * @param scene defines the hosting scene
  59350. * @returns the ribbon mesh
  59351. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59352. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59353. */
  59354. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59355. if (scene === void 0) { scene = null; }
  59356. var pathArray = options.pathArray;
  59357. var closeArray = options.closeArray;
  59358. var closePath = options.closePath;
  59359. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59360. var instance = options.instance;
  59361. var updatable = options.updatable;
  59362. if (instance) {
  59363. // positionFunction : ribbon case
  59364. // only pathArray and sideOrientation parameters are taken into account for positions update
  59365. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59366. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59367. var positionFunction = function (positions) {
  59368. var minlg = pathArray[0].length;
  59369. var i = 0;
  59370. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59371. for (var si = 1; si <= ns; si++) {
  59372. for (var p = 0; p < pathArray.length; p++) {
  59373. var path = pathArray[p];
  59374. var l = path.length;
  59375. minlg = (minlg < l) ? minlg : l;
  59376. var j = 0;
  59377. while (j < minlg) {
  59378. positions[i] = path[j].x;
  59379. positions[i + 1] = path[j].y;
  59380. positions[i + 2] = path[j].z;
  59381. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59382. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59383. }
  59384. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59385. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59386. }
  59387. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59388. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59389. }
  59390. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59391. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59392. }
  59393. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59394. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59395. }
  59396. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59397. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59398. }
  59399. j++;
  59400. i += 3;
  59401. }
  59402. if (instance._closePath) {
  59403. positions[i] = path[0].x;
  59404. positions[i + 1] = path[0].y;
  59405. positions[i + 2] = path[0].z;
  59406. i += 3;
  59407. }
  59408. }
  59409. }
  59410. };
  59411. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59412. positionFunction(positions);
  59413. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59414. instance._boundingInfo.update(instance._worldMatrix);
  59415. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59416. if (options.colors) {
  59417. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59418. for (var c = 0; c < options.colors.length; c++) {
  59419. colors[c * 4] = options.colors[c].r;
  59420. colors[c * 4 + 1] = options.colors[c].g;
  59421. colors[c * 4 + 2] = options.colors[c].b;
  59422. colors[c * 4 + 3] = options.colors[c].a;
  59423. }
  59424. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59425. }
  59426. if (options.uvs) {
  59427. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59428. for (var i = 0; i < options.uvs.length; i++) {
  59429. uvs[i * 2] = options.uvs[i].x;
  59430. uvs[i * 2 + 1] = options.uvs[i].y;
  59431. }
  59432. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59433. }
  59434. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59435. var indices = instance.getIndices();
  59436. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59437. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59438. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  59439. if (instance._closePath) {
  59440. var indexFirst = 0;
  59441. var indexLast = 0;
  59442. for (var p = 0; p < pathArray.length; p++) {
  59443. indexFirst = instance._idx[p] * 3;
  59444. if (p + 1 < pathArray.length) {
  59445. indexLast = (instance._idx[p + 1] - 1) * 3;
  59446. }
  59447. else {
  59448. indexLast = normals.length - 3;
  59449. }
  59450. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  59451. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  59452. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  59453. normals[indexLast] = normals[indexFirst];
  59454. normals[indexLast + 1] = normals[indexFirst + 1];
  59455. normals[indexLast + 2] = normals[indexFirst + 2];
  59456. }
  59457. }
  59458. if (!(instance.areNormalsFrozen)) {
  59459. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  59460. }
  59461. }
  59462. return instance;
  59463. }
  59464. else {
  59465. var ribbon = new BABYLON.Mesh(name, scene);
  59466. ribbon._originalBuilderSideOrientation = sideOrientation;
  59467. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  59468. if (closePath) {
  59469. ribbon._idx = vertexData._idx;
  59470. }
  59471. ribbon._closePath = closePath;
  59472. ribbon._closeArray = closeArray;
  59473. vertexData.applyToMesh(ribbon, updatable);
  59474. return ribbon;
  59475. }
  59476. };
  59477. /**
  59478. * Creates a cylinder or a cone mesh
  59479. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  59480. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  59481. * * 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.
  59482. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  59483. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  59484. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  59485. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  59486. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  59487. * * 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).
  59488. * * 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
  59489. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  59490. * * 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
  59491. * * 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.
  59492. * * If `enclose` is false, a ring surface is one element.
  59493. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  59494. * * 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
  59495. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59496. * * 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
  59497. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59498. * @param name defines the name of the mesh
  59499. * @param options defines the options used to create the mesh
  59500. * @param scene defines the hosting scene
  59501. * @returns the cylinder mesh
  59502. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  59503. */
  59504. MeshBuilder.CreateCylinder = function (name, options, scene) {
  59505. var cylinder = new BABYLON.Mesh(name, scene);
  59506. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59507. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  59508. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  59509. vertexData.applyToMesh(cylinder, options.updatable);
  59510. return cylinder;
  59511. };
  59512. /**
  59513. * Creates a torus mesh
  59514. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  59515. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  59516. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  59517. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59518. * * 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
  59519. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59520. * @param name defines the name of the mesh
  59521. * @param options defines the options used to create the mesh
  59522. * @param scene defines the hosting scene
  59523. * @returns the torus mesh
  59524. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  59525. */
  59526. MeshBuilder.CreateTorus = function (name, options, scene) {
  59527. var torus = new BABYLON.Mesh(name, scene);
  59528. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59529. torus._originalBuilderSideOrientation = options.sideOrientation;
  59530. var vertexData = BABYLON.VertexData.CreateTorus(options);
  59531. vertexData.applyToMesh(torus, options.updatable);
  59532. return torus;
  59533. };
  59534. /**
  59535. * Creates a torus knot mesh
  59536. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  59537. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  59538. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  59539. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  59540. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59541. * * 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
  59542. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59543. * @param name defines the name of the mesh
  59544. * @param options defines the options used to create the mesh
  59545. * @param scene defines the hosting scene
  59546. * @returns the torus knot mesh
  59547. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  59548. */
  59549. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  59550. var torusKnot = new BABYLON.Mesh(name, scene);
  59551. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59552. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  59553. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  59554. vertexData.applyToMesh(torusKnot, options.updatable);
  59555. return torusKnot;
  59556. };
  59557. /**
  59558. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  59559. * * 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
  59560. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  59561. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  59562. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  59563. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  59564. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  59565. * * 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
  59566. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  59567. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59568. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  59569. * @param name defines the name of the new line system
  59570. * @param options defines the options used to create the line system
  59571. * @param scene defines the hosting scene
  59572. * @returns a new line system mesh
  59573. */
  59574. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  59575. var instance = options.instance;
  59576. var lines = options.lines;
  59577. var colors = options.colors;
  59578. if (instance) {
  59579. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59580. var vertexColor;
  59581. var lineColors;
  59582. if (colors) {
  59583. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59584. }
  59585. var i = 0;
  59586. var c = 0;
  59587. for (var l = 0; l < lines.length; l++) {
  59588. var points = lines[l];
  59589. for (var p = 0; p < points.length; p++) {
  59590. positions[i] = points[p].x;
  59591. positions[i + 1] = points[p].y;
  59592. positions[i + 2] = points[p].z;
  59593. if (colors && vertexColor) {
  59594. lineColors = colors[l];
  59595. vertexColor[c] = lineColors[p].r;
  59596. vertexColor[c + 1] = lineColors[p].g;
  59597. vertexColor[c + 2] = lineColors[p].b;
  59598. vertexColor[c + 3] = lineColors[p].a;
  59599. c += 4;
  59600. }
  59601. i += 3;
  59602. }
  59603. }
  59604. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59605. if (colors && vertexColor) {
  59606. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  59607. }
  59608. return instance;
  59609. }
  59610. // line system creation
  59611. var useVertexColor = (colors) ? true : false;
  59612. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  59613. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  59614. vertexData.applyToMesh(lineSystem, options.updatable);
  59615. return lineSystem;
  59616. };
  59617. /**
  59618. * Creates a line mesh
  59619. * 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
  59620. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59621. * * The parameter `points` is an array successive Vector3
  59622. * * 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
  59623. * * The optional parameter `colors` is an array of successive Color4, one per line point
  59624. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  59625. * * When updating an instance, remember that only point positions can change, not the number of points
  59626. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59627. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  59628. * @param name defines the name of the new line system
  59629. * @param options defines the options used to create the line system
  59630. * @param scene defines the hosting scene
  59631. * @returns a new line mesh
  59632. */
  59633. MeshBuilder.CreateLines = function (name, options, scene) {
  59634. if (scene === void 0) { scene = null; }
  59635. var colors = (options.colors) ? [options.colors] : null;
  59636. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  59637. return lines;
  59638. };
  59639. /**
  59640. * Creates a dashed line mesh
  59641. * * 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
  59642. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59643. * * The parameter `points` is an array successive Vector3
  59644. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  59645. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  59646. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  59647. * * 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
  59648. * * When updating an instance, remember that only point positions can change, not the number of points
  59649. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59650. * @param name defines the name of the mesh
  59651. * @param options defines the options used to create the mesh
  59652. * @param scene defines the hosting scene
  59653. * @returns the dashed line mesh
  59654. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  59655. */
  59656. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  59657. if (scene === void 0) { scene = null; }
  59658. var points = options.points;
  59659. var instance = options.instance;
  59660. var gapSize = options.gapSize || 1;
  59661. var dashSize = options.dashSize || 3;
  59662. if (instance) {
  59663. var positionFunction = function (positions) {
  59664. var curvect = BABYLON.Vector3.Zero();
  59665. var nbSeg = positions.length / 6;
  59666. var lg = 0;
  59667. var nb = 0;
  59668. var shft = 0;
  59669. var dashshft = 0;
  59670. var curshft = 0;
  59671. var p = 0;
  59672. var i = 0;
  59673. var j = 0;
  59674. for (i = 0; i < points.length - 1; i++) {
  59675. points[i + 1].subtractToRef(points[i], curvect);
  59676. lg += curvect.length();
  59677. }
  59678. shft = lg / nbSeg;
  59679. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  59680. for (i = 0; i < points.length - 1; i++) {
  59681. points[i + 1].subtractToRef(points[i], curvect);
  59682. nb = Math.floor(curvect.length() / shft);
  59683. curvect.normalize();
  59684. j = 0;
  59685. while (j < nb && p < positions.length) {
  59686. curshft = shft * j;
  59687. positions[p] = points[i].x + curshft * curvect.x;
  59688. positions[p + 1] = points[i].y + curshft * curvect.y;
  59689. positions[p + 2] = points[i].z + curshft * curvect.z;
  59690. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  59691. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  59692. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  59693. p += 6;
  59694. j++;
  59695. }
  59696. }
  59697. while (p < positions.length) {
  59698. positions[p] = points[i].x;
  59699. positions[p + 1] = points[i].y;
  59700. positions[p + 2] = points[i].z;
  59701. p += 3;
  59702. }
  59703. };
  59704. instance.updateMeshPositions(positionFunction, false);
  59705. return instance;
  59706. }
  59707. // dashed lines creation
  59708. var dashedLines = new BABYLON.LinesMesh(name, scene);
  59709. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  59710. vertexData.applyToMesh(dashedLines, options.updatable);
  59711. dashedLines.dashSize = dashSize;
  59712. dashedLines.gapSize = gapSize;
  59713. return dashedLines;
  59714. };
  59715. /**
  59716. * 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.
  59717. * * 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.
  59718. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59719. * * 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.
  59720. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  59721. * * 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
  59722. * * 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
  59723. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59724. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59725. * * 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
  59726. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59727. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59728. * @param name defines the name of the mesh
  59729. * @param options defines the options used to create the mesh
  59730. * @param scene defines the hosting scene
  59731. * @returns the extruded shape mesh
  59732. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59733. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59734. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  59735. */
  59736. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  59737. if (scene === void 0) { scene = null; }
  59738. var path = options.path;
  59739. var shape = options.shape;
  59740. var scale = options.scale || 1;
  59741. var rotation = options.rotation || 0;
  59742. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59743. var updatable = options.updatable;
  59744. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59745. var instance = options.instance || null;
  59746. var invertUV = options.invertUV || false;
  59747. 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);
  59748. };
  59749. /**
  59750. * Creates an custom extruded shape mesh.
  59751. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  59752. * * 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.
  59753. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59754. * * 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
  59755. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  59756. * * 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
  59757. * * It must returns a float value that will be the scale value applied to the shape on each path point
  59758. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  59759. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  59760. * * 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
  59761. * * 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
  59762. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  59763. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59764. * * 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
  59765. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59766. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59767. * @param name defines the name of the mesh
  59768. * @param options defines the options used to create the mesh
  59769. * @param scene defines the hosting scene
  59770. * @returns the custom extruded shape mesh
  59771. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  59772. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59773. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59774. */
  59775. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  59776. var path = options.path;
  59777. var shape = options.shape;
  59778. var scaleFunction = options.scaleFunction || (function () { return 1; });
  59779. var rotationFunction = options.rotationFunction || (function () { return 0; });
  59780. var ribbonCloseArray = options.ribbonCloseArray || false;
  59781. var ribbonClosePath = options.ribbonClosePath || false;
  59782. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59783. var updatable = options.updatable;
  59784. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59785. var instance = options.instance;
  59786. var invertUV = options.invertUV || false;
  59787. 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);
  59788. };
  59789. /**
  59790. * Creates lathe mesh.
  59791. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  59792. * * 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
  59793. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  59794. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  59795. * * 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
  59796. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  59797. * * 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
  59798. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59799. * * 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
  59800. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59801. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59802. * @param name defines the name of the mesh
  59803. * @param options defines the options used to create the mesh
  59804. * @param scene defines the hosting scene
  59805. * @returns the lathe mesh
  59806. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  59807. */
  59808. MeshBuilder.CreateLathe = function (name, options, scene) {
  59809. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  59810. var closed = (options.closed === undefined) ? true : options.closed;
  59811. var shape = options.shape;
  59812. var radius = options.radius || 1;
  59813. var tessellation = options.tessellation || 64;
  59814. var updatable = options.updatable;
  59815. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59816. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59817. var pi2 = Math.PI * 2;
  59818. var paths = new Array();
  59819. var invertUV = options.invertUV || false;
  59820. var i = 0;
  59821. var p = 0;
  59822. var step = pi2 / tessellation * arc;
  59823. var rotated;
  59824. var path = new Array();
  59825. ;
  59826. for (i = 0; i <= tessellation; i++) {
  59827. var path = [];
  59828. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  59829. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  59830. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  59831. }
  59832. for (p = 0; p < shape.length; p++) {
  59833. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  59834. path.push(rotated);
  59835. }
  59836. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  59837. 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));
  59838. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  59839. }
  59840. paths.push(path);
  59841. }
  59842. // lathe ribbon
  59843. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59844. return lathe;
  59845. };
  59846. /**
  59847. * Creates a plane mesh
  59848. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  59849. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  59850. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  59851. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59852. * * 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
  59853. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59854. * @param name defines the name of the mesh
  59855. * @param options defines the options used to create the mesh
  59856. * @param scene defines the hosting scene
  59857. * @returns the plane mesh
  59858. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59859. */
  59860. MeshBuilder.CreatePlane = function (name, options, scene) {
  59861. var plane = new BABYLON.Mesh(name, scene);
  59862. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59863. plane._originalBuilderSideOrientation = options.sideOrientation;
  59864. var vertexData = BABYLON.VertexData.CreatePlane(options);
  59865. vertexData.applyToMesh(plane, options.updatable);
  59866. if (options.sourcePlane) {
  59867. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  59868. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  59869. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  59870. plane.rotate(vectorProduct, product);
  59871. }
  59872. return plane;
  59873. };
  59874. /**
  59875. * Creates a ground mesh
  59876. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  59877. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  59878. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59879. * @param name defines the name of the mesh
  59880. * @param options defines the options used to create the mesh
  59881. * @param scene defines the hosting scene
  59882. * @returns the ground mesh
  59883. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59884. */
  59885. MeshBuilder.CreateGround = function (name, options, scene) {
  59886. var ground = new BABYLON.GroundMesh(name, scene);
  59887. ground._setReady(false);
  59888. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  59889. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  59890. ground._width = options.width || 1;
  59891. ground._height = options.height || 1;
  59892. ground._maxX = ground._width / 2;
  59893. ground._maxZ = ground._height / 2;
  59894. ground._minX = -ground._maxX;
  59895. ground._minZ = -ground._maxZ;
  59896. var vertexData = BABYLON.VertexData.CreateGround(options);
  59897. vertexData.applyToMesh(ground, options.updatable);
  59898. ground._setReady(true);
  59899. return ground;
  59900. };
  59901. /**
  59902. * Creates a tiled ground mesh
  59903. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  59904. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  59905. * * 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
  59906. * * 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
  59907. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59908. * @param name defines the name of the mesh
  59909. * @param options defines the options used to create the mesh
  59910. * @param scene defines the hosting scene
  59911. * @returns the tiled ground mesh
  59912. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  59913. */
  59914. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  59915. var tiledGround = new BABYLON.Mesh(name, scene);
  59916. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  59917. vertexData.applyToMesh(tiledGround, options.updatable);
  59918. return tiledGround;
  59919. };
  59920. /**
  59921. * Creates a ground mesh from a height map
  59922. * * The parameter `url` sets the URL of the height map image resource.
  59923. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  59924. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  59925. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  59926. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  59927. * * 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.
  59928. * * 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).
  59929. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59930. * @param name defines the name of the mesh
  59931. * @param url defines the url to the height map
  59932. * @param options defines the options used to create the mesh
  59933. * @param scene defines the hosting scene
  59934. * @returns the ground mesh
  59935. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  59936. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  59937. */
  59938. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  59939. var width = options.width || 10.0;
  59940. var height = options.height || 10.0;
  59941. var subdivisions = options.subdivisions || 1 | 0;
  59942. var minHeight = options.minHeight || 0.0;
  59943. var maxHeight = options.maxHeight || 1.0;
  59944. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  59945. var updatable = options.updatable;
  59946. var onReady = options.onReady;
  59947. var ground = new BABYLON.GroundMesh(name, scene);
  59948. ground._subdivisionsX = subdivisions;
  59949. ground._subdivisionsY = subdivisions;
  59950. ground._width = width;
  59951. ground._height = height;
  59952. ground._maxX = ground._width / 2.0;
  59953. ground._maxZ = ground._height / 2.0;
  59954. ground._minX = -ground._maxX;
  59955. ground._minZ = -ground._maxZ;
  59956. ground._setReady(false);
  59957. var onload = function (img) {
  59958. // Getting height map data
  59959. var canvas = document.createElement("canvas");
  59960. var context = canvas.getContext("2d");
  59961. if (!context) {
  59962. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  59963. }
  59964. if (scene.isDisposed) {
  59965. return;
  59966. }
  59967. var bufferWidth = img.width;
  59968. var bufferHeight = img.height;
  59969. canvas.width = bufferWidth;
  59970. canvas.height = bufferHeight;
  59971. context.drawImage(img, 0, 0);
  59972. // Create VertexData from map data
  59973. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  59974. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  59975. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  59976. width: width, height: height,
  59977. subdivisions: subdivisions,
  59978. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  59979. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  59980. });
  59981. vertexData.applyToMesh(ground, updatable);
  59982. //execute ready callback, if set
  59983. if (onReady) {
  59984. onReady(ground);
  59985. }
  59986. ground._setReady(true);
  59987. };
  59988. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  59989. return ground;
  59990. };
  59991. /**
  59992. * Creates a polygon mesh
  59993. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  59994. * * 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
  59995. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59996. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59997. * * 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)
  59998. * * Remember you can only change the shape positions, not their number when updating a polygon
  59999. * @param name defines the name of the mesh
  60000. * @param options defines the options used to create the mesh
  60001. * @param scene defines the hosting scene
  60002. * @returns the polygon mesh
  60003. */
  60004. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60005. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60006. var shape = options.shape;
  60007. var holes = options.holes || [];
  60008. var depth = options.depth || 0;
  60009. var contours = [];
  60010. var hole = [];
  60011. for (var i = 0; i < shape.length; i++) {
  60012. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60013. }
  60014. var epsilon = 0.00000001;
  60015. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60016. contours.pop();
  60017. }
  60018. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60019. for (var hNb = 0; hNb < holes.length; hNb++) {
  60020. hole = [];
  60021. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60022. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60023. }
  60024. polygonTriangulation.addHole(hole);
  60025. }
  60026. var polygon = polygonTriangulation.build(options.updatable, depth);
  60027. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60028. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60029. vertexData.applyToMesh(polygon, options.updatable);
  60030. return polygon;
  60031. };
  60032. ;
  60033. /**
  60034. * Creates an extruded polygon mesh, with depth in the Y direction.
  60035. * * 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)
  60036. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60037. * @param name defines the name of the mesh
  60038. * @param options defines the options used to create the mesh
  60039. * @param scene defines the hosting scene
  60040. * @returns the polygon mesh
  60041. */
  60042. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60043. return MeshBuilder.CreatePolygon(name, options, scene);
  60044. };
  60045. ;
  60046. /**
  60047. * Creates a tube mesh.
  60048. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60049. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60050. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60051. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60052. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60053. * * 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)
  60054. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60055. * * 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
  60056. * * 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
  60057. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60058. * * 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
  60059. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60060. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60061. * @param name defines the name of the mesh
  60062. * @param options defines the options used to create the mesh
  60063. * @param scene defines the hosting scene
  60064. * @returns the tube mesh
  60065. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60066. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60067. */
  60068. MeshBuilder.CreateTube = function (name, options, scene) {
  60069. var path = options.path;
  60070. var instance = options.instance;
  60071. var radius = 1.0;
  60072. if (instance) {
  60073. radius = instance.radius;
  60074. }
  60075. if (options.radius !== undefined) {
  60076. radius = options.radius;
  60077. }
  60078. ;
  60079. var tessellation = options.tessellation || 64 | 0;
  60080. var radiusFunction = options.radiusFunction || null;
  60081. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60082. var invertUV = options.invertUV || false;
  60083. var updatable = options.updatable;
  60084. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60085. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60086. // tube geometry
  60087. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60088. var tangents = path3D.getTangents();
  60089. var normals = path3D.getNormals();
  60090. var distances = path3D.getDistances();
  60091. var pi2 = Math.PI * 2;
  60092. var step = pi2 / tessellation * arc;
  60093. var returnRadius = function () { return radius; };
  60094. var radiusFunctionFinal = radiusFunction || returnRadius;
  60095. var circlePath;
  60096. var rad;
  60097. var normal;
  60098. var rotated;
  60099. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60100. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60101. for (var i = 0; i < path.length; i++) {
  60102. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60103. circlePath = Array(); // current circle array
  60104. normal = normals[i]; // current normal
  60105. for (var t = 0; t < tessellation; t++) {
  60106. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60107. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60108. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60109. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60110. circlePath[t] = rotated;
  60111. }
  60112. circlePaths[index] = circlePath;
  60113. index++;
  60114. }
  60115. // cap
  60116. var capPath = function (nbPoints, pathIndex) {
  60117. var pointCap = Array();
  60118. for (var i = 0; i < nbPoints; i++) {
  60119. pointCap.push(path[pathIndex]);
  60120. }
  60121. return pointCap;
  60122. };
  60123. switch (cap) {
  60124. case BABYLON.Mesh.NO_CAP:
  60125. break;
  60126. case BABYLON.Mesh.CAP_START:
  60127. circlePaths[0] = capPath(tessellation, 0);
  60128. circlePaths[1] = circlePaths[2].slice(0);
  60129. break;
  60130. case BABYLON.Mesh.CAP_END:
  60131. circlePaths[index] = circlePaths[index - 1].slice(0);
  60132. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60133. break;
  60134. case BABYLON.Mesh.CAP_ALL:
  60135. circlePaths[0] = capPath(tessellation, 0);
  60136. circlePaths[1] = circlePaths[2].slice(0);
  60137. circlePaths[index] = circlePaths[index - 1].slice(0);
  60138. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60139. break;
  60140. default:
  60141. break;
  60142. }
  60143. return circlePaths;
  60144. };
  60145. var path3D;
  60146. var pathArray;
  60147. if (instance) {
  60148. var arc = options.arc || instance.arc;
  60149. path3D = (instance.path3D).update(path);
  60150. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60151. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60152. instance.path3D = path3D;
  60153. instance.pathArray = pathArray;
  60154. instance.arc = arc;
  60155. instance.radius = radius;
  60156. return instance;
  60157. }
  60158. // tube creation
  60159. path3D = new BABYLON.Path3D(path);
  60160. var newPathArray = new Array();
  60161. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60162. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60163. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60164. tube.pathArray = pathArray;
  60165. tube.path3D = path3D;
  60166. tube.tessellation = tessellation;
  60167. tube.cap = cap;
  60168. tube.arc = options.arc;
  60169. tube.radius = radius;
  60170. return tube;
  60171. };
  60172. /**
  60173. * Creates a polyhedron mesh
  60174. * * 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
  60175. * * The parameter `size` (positive float, default 1) sets the polygon size
  60176. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60177. * * 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`
  60178. * * 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
  60179. * * 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)`)
  60180. * * 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
  60181. * * 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
  60182. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60183. * * 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
  60184. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60185. * @param name defines the name of the mesh
  60186. * @param options defines the options used to create the mesh
  60187. * @param scene defines the hosting scene
  60188. * @returns the polyhedron mesh
  60189. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  60190. */
  60191. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60192. var polyhedron = new BABYLON.Mesh(name, scene);
  60193. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60194. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60195. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60196. vertexData.applyToMesh(polyhedron, options.updatable);
  60197. return polyhedron;
  60198. };
  60199. /**
  60200. * Creates a decal mesh.
  60201. * 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
  60202. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60203. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60204. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60205. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60206. * @param name defines the name of the mesh
  60207. * @param sourceMesh defines the mesh where the decal must be applied
  60208. * @param options defines the options used to create the mesh
  60209. * @param scene defines the hosting scene
  60210. * @returns the decal mesh
  60211. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60212. */
  60213. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60214. var indices = sourceMesh.getIndices();
  60215. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60216. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60217. var position = options.position || BABYLON.Vector3.Zero();
  60218. var normal = options.normal || BABYLON.Vector3.Up();
  60219. var size = options.size || BABYLON.Vector3.One();
  60220. var angle = options.angle || 0;
  60221. // Getting correct rotation
  60222. if (!normal) {
  60223. var target = new BABYLON.Vector3(0, 0, 1);
  60224. var camera = sourceMesh.getScene().activeCamera;
  60225. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60226. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60227. }
  60228. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60229. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60230. var pitch = Math.atan2(normal.y, len);
  60231. // Matrix
  60232. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60233. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60234. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60235. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60236. var vertexData = new BABYLON.VertexData();
  60237. vertexData.indices = [];
  60238. vertexData.positions = [];
  60239. vertexData.normals = [];
  60240. vertexData.uvs = [];
  60241. var currentVertexDataIndex = 0;
  60242. var extractDecalVector3 = function (indexId) {
  60243. var result = new BABYLON.PositionNormalVertex();
  60244. if (!indices || !positions || !normals) {
  60245. return result;
  60246. }
  60247. var vertexId = indices[indexId];
  60248. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60249. // Send vector to decal local world
  60250. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60251. // Get normal
  60252. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60253. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60254. return result;
  60255. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60256. var clip = function (vertices, axis) {
  60257. if (vertices.length === 0) {
  60258. return vertices;
  60259. }
  60260. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60261. var clipVertices = function (v0, v1) {
  60262. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60263. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60264. };
  60265. var result = new Array();
  60266. for (var index = 0; index < vertices.length; index += 3) {
  60267. var v1Out;
  60268. var v2Out;
  60269. var v3Out;
  60270. var total = 0;
  60271. var nV1 = null;
  60272. var nV2 = null;
  60273. var nV3 = null;
  60274. var nV4 = null;
  60275. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60276. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60277. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60278. v1Out = d1 > 0;
  60279. v2Out = d2 > 0;
  60280. v3Out = d3 > 0;
  60281. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60282. switch (total) {
  60283. case 0:
  60284. result.push(vertices[index]);
  60285. result.push(vertices[index + 1]);
  60286. result.push(vertices[index + 2]);
  60287. break;
  60288. case 1:
  60289. if (v1Out) {
  60290. nV1 = vertices[index + 1];
  60291. nV2 = vertices[index + 2];
  60292. nV3 = clipVertices(vertices[index], nV1);
  60293. nV4 = clipVertices(vertices[index], nV2);
  60294. }
  60295. if (v2Out) {
  60296. nV1 = vertices[index];
  60297. nV2 = vertices[index + 2];
  60298. nV3 = clipVertices(vertices[index + 1], nV1);
  60299. nV4 = clipVertices(vertices[index + 1], nV2);
  60300. result.push(nV3);
  60301. result.push(nV2.clone());
  60302. result.push(nV1.clone());
  60303. result.push(nV2.clone());
  60304. result.push(nV3.clone());
  60305. result.push(nV4);
  60306. break;
  60307. }
  60308. if (v3Out) {
  60309. nV1 = vertices[index];
  60310. nV2 = vertices[index + 1];
  60311. nV3 = clipVertices(vertices[index + 2], nV1);
  60312. nV4 = clipVertices(vertices[index + 2], nV2);
  60313. }
  60314. if (nV1 && nV2 && nV3 && nV4) {
  60315. result.push(nV1.clone());
  60316. result.push(nV2.clone());
  60317. result.push(nV3);
  60318. result.push(nV4);
  60319. result.push(nV3.clone());
  60320. result.push(nV2.clone());
  60321. }
  60322. break;
  60323. case 2:
  60324. if (!v1Out) {
  60325. nV1 = vertices[index].clone();
  60326. nV2 = clipVertices(nV1, vertices[index + 1]);
  60327. nV3 = clipVertices(nV1, vertices[index + 2]);
  60328. result.push(nV1);
  60329. result.push(nV2);
  60330. result.push(nV3);
  60331. }
  60332. if (!v2Out) {
  60333. nV1 = vertices[index + 1].clone();
  60334. nV2 = clipVertices(nV1, vertices[index + 2]);
  60335. nV3 = clipVertices(nV1, vertices[index]);
  60336. result.push(nV1);
  60337. result.push(nV2);
  60338. result.push(nV3);
  60339. }
  60340. if (!v3Out) {
  60341. nV1 = vertices[index + 2].clone();
  60342. nV2 = clipVertices(nV1, vertices[index]);
  60343. nV3 = clipVertices(nV1, vertices[index + 1]);
  60344. result.push(nV1);
  60345. result.push(nV2);
  60346. result.push(nV3);
  60347. }
  60348. break;
  60349. case 3:
  60350. break;
  60351. }
  60352. }
  60353. return result;
  60354. };
  60355. for (var index = 0; index < indices.length; index += 3) {
  60356. var faceVertices = new Array();
  60357. faceVertices.push(extractDecalVector3(index));
  60358. faceVertices.push(extractDecalVector3(index + 1));
  60359. faceVertices.push(extractDecalVector3(index + 2));
  60360. // Clip
  60361. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60362. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60363. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60364. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60365. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60366. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60367. if (faceVertices.length === 0) {
  60368. continue;
  60369. }
  60370. // Add UVs and get back to world
  60371. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60372. var vertex = faceVertices[vIndex];
  60373. //TODO check for Int32Array | Uint32Array | Uint16Array
  60374. vertexData.indices.push(currentVertexDataIndex);
  60375. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60376. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60377. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60378. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60379. currentVertexDataIndex++;
  60380. }
  60381. }
  60382. // Return mesh
  60383. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60384. vertexData.applyToMesh(decal);
  60385. decal.position = position.clone();
  60386. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60387. return decal;
  60388. };
  60389. // Privates
  60390. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60391. // extrusion geometry
  60392. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60393. var tangents = path3D.getTangents();
  60394. var normals = path3D.getNormals();
  60395. var binormals = path3D.getBinormals();
  60396. var distances = path3D.getDistances();
  60397. var angle = 0;
  60398. var returnScale = function () { return scale !== null ? scale : 1; };
  60399. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60400. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60401. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60402. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60403. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60404. for (var i = 0; i < curve.length; i++) {
  60405. var shapePath = new Array();
  60406. var angleStep = rotate(i, distances[i]);
  60407. var scaleRatio = scl(i, distances[i]);
  60408. for (var p = 0; p < shape.length; p++) {
  60409. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60410. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60411. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60412. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60413. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60414. shapePath[p] = rotated;
  60415. }
  60416. shapePaths[index] = shapePath;
  60417. angle += angleStep;
  60418. index++;
  60419. }
  60420. // cap
  60421. var capPath = function (shapePath) {
  60422. var pointCap = Array();
  60423. var barycenter = BABYLON.Vector3.Zero();
  60424. var i;
  60425. for (i = 0; i < shapePath.length; i++) {
  60426. barycenter.addInPlace(shapePath[i]);
  60427. }
  60428. barycenter.scaleInPlace(1.0 / shapePath.length);
  60429. for (i = 0; i < shapePath.length; i++) {
  60430. pointCap.push(barycenter);
  60431. }
  60432. return pointCap;
  60433. };
  60434. switch (cap) {
  60435. case BABYLON.Mesh.NO_CAP:
  60436. break;
  60437. case BABYLON.Mesh.CAP_START:
  60438. shapePaths[0] = capPath(shapePaths[2]);
  60439. shapePaths[1] = shapePaths[2];
  60440. break;
  60441. case BABYLON.Mesh.CAP_END:
  60442. shapePaths[index] = shapePaths[index - 1];
  60443. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60444. break;
  60445. case BABYLON.Mesh.CAP_ALL:
  60446. shapePaths[0] = capPath(shapePaths[2]);
  60447. shapePaths[1] = shapePaths[2];
  60448. shapePaths[index] = shapePaths[index - 1];
  60449. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60450. break;
  60451. default:
  60452. break;
  60453. }
  60454. return shapePaths;
  60455. };
  60456. var path3D;
  60457. var pathArray;
  60458. if (instance) {
  60459. path3D = (instance.path3D).update(curve);
  60460. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  60461. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  60462. return instance;
  60463. }
  60464. // extruded shape creation
  60465. path3D = new BABYLON.Path3D(curve);
  60466. var newShapePaths = new Array();
  60467. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60468. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  60469. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  60470. extrudedGeneric.pathArray = pathArray;
  60471. extrudedGeneric.path3D = path3D;
  60472. extrudedGeneric.cap = cap;
  60473. return extrudedGeneric;
  60474. };
  60475. return MeshBuilder;
  60476. }());
  60477. BABYLON.MeshBuilder = MeshBuilder;
  60478. })(BABYLON || (BABYLON = {}));
  60479. //# sourceMappingURL=babylon.meshBuilder.js.map
  60480. "use strict";
  60481. var BABYLON;
  60482. (function (BABYLON) {
  60483. /**
  60484. * Draco compression (https://google.github.io/draco/)
  60485. */
  60486. var DracoCompression = /** @class */ (function () {
  60487. /**
  60488. * Constructor
  60489. */
  60490. function DracoCompression() {
  60491. }
  60492. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  60493. /**
  60494. * Returns true if the decoder is available.
  60495. */
  60496. get: function () {
  60497. return (typeof DracoDecoderModule !== "undefined" ||
  60498. (typeof WebAssembly === "object" && !!DracoCompression.Configuration.decoderWasm) ||
  60499. !!DracoCompression.Configuration.decoder);
  60500. },
  60501. enumerable: true,
  60502. configurable: true
  60503. });
  60504. /**
  60505. * Stop all async operations and release resources.
  60506. */
  60507. DracoCompression.prototype.dispose = function () {
  60508. };
  60509. /**
  60510. * Decode Draco compressed mesh data to vertex data.
  60511. * @param data The array buffer view for the Draco compression data
  60512. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  60513. * @returns A promise that resolves with the decoded vertex data
  60514. */
  60515. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  60516. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  60517. var module = wrappedModule.module;
  60518. var vertexData = new BABYLON.VertexData();
  60519. var buffer = new module.DecoderBuffer();
  60520. buffer.Init(data, data.byteLength);
  60521. var decoder = new module.Decoder();
  60522. var geometry;
  60523. var status;
  60524. try {
  60525. var type = decoder.GetEncodedGeometryType(buffer);
  60526. switch (type) {
  60527. case module.TRIANGULAR_MESH:
  60528. geometry = new module.Mesh();
  60529. status = decoder.DecodeBufferToMesh(buffer, geometry);
  60530. break;
  60531. case module.POINT_CLOUD:
  60532. geometry = new module.PointCloud();
  60533. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  60534. break;
  60535. default:
  60536. throw new Error("Invalid geometry type " + type);
  60537. }
  60538. if (!status.ok() || !geometry.ptr) {
  60539. throw new Error(status.error_msg());
  60540. }
  60541. var numPoints = geometry.num_points();
  60542. if (type === module.TRIANGULAR_MESH) {
  60543. var numFaces = geometry.num_faces();
  60544. var faceIndices = new module.DracoInt32Array();
  60545. try {
  60546. var indices = new Uint32Array(numFaces * 3);
  60547. for (var i = 0; i < numFaces; i++) {
  60548. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  60549. var offset = i * 3;
  60550. indices[offset + 0] = faceIndices.GetValue(0);
  60551. indices[offset + 1] = faceIndices.GetValue(1);
  60552. indices[offset + 2] = faceIndices.GetValue(2);
  60553. }
  60554. vertexData.indices = indices;
  60555. }
  60556. finally {
  60557. module.destroy(faceIndices);
  60558. }
  60559. }
  60560. for (var kind in attributes) {
  60561. var uniqueId = attributes[kind];
  60562. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  60563. var dracoData = new module.DracoFloat32Array();
  60564. try {
  60565. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  60566. var babylonData = new Float32Array(numPoints * attribute.num_components());
  60567. for (var i = 0; i < babylonData.length; i++) {
  60568. babylonData[i] = dracoData.GetValue(i);
  60569. }
  60570. vertexData.set(babylonData, kind);
  60571. }
  60572. finally {
  60573. module.destroy(dracoData);
  60574. }
  60575. }
  60576. }
  60577. finally {
  60578. if (geometry) {
  60579. module.destroy(geometry);
  60580. }
  60581. module.destroy(decoder);
  60582. module.destroy(buffer);
  60583. }
  60584. return vertexData;
  60585. });
  60586. };
  60587. DracoCompression._GetDecoderModule = function () {
  60588. if (!DracoCompression._DecoderModulePromise) {
  60589. var promise = void 0;
  60590. var config_1 = {};
  60591. if (typeof DracoDecoderModule !== "undefined") {
  60592. promise = Promise.resolve();
  60593. }
  60594. else if (typeof WebAssembly === "object" && DracoCompression.Configuration.decoderWasm) {
  60595. promise = Promise.all([
  60596. DracoCompression._LoadScriptAsync(DracoCompression.Configuration.decoderWasm.wrapperUrl),
  60597. DracoCompression._LoadFileAsync(DracoCompression.Configuration.decoderWasm.binaryUrl).then(function (data) {
  60598. config_1.wasmBinary = data;
  60599. })
  60600. ]);
  60601. }
  60602. else if (DracoCompression.Configuration.decoder) {
  60603. promise = DracoCompression._LoadScriptAsync(DracoCompression.Configuration.decoder.url);
  60604. }
  60605. else {
  60606. throw new Error("Invalid decoder configuration");
  60607. }
  60608. DracoCompression._DecoderModulePromise = promise.then(function () {
  60609. return new Promise(function (resolve) {
  60610. config_1.onModuleLoaded = function (decoderModule) {
  60611. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  60612. resolve({ module: decoderModule });
  60613. };
  60614. DracoDecoderModule(config_1);
  60615. });
  60616. });
  60617. }
  60618. return DracoCompression._DecoderModulePromise;
  60619. };
  60620. DracoCompression._LoadScriptAsync = function (url) {
  60621. return new Promise(function (resolve, reject) {
  60622. BABYLON.Tools.LoadScript(url, function () {
  60623. resolve();
  60624. }, function (message) {
  60625. reject(new Error(message));
  60626. });
  60627. });
  60628. };
  60629. DracoCompression._LoadFileAsync = function (url) {
  60630. return new Promise(function (resolve, reject) {
  60631. BABYLON.Tools.LoadFile(url, function (data) {
  60632. resolve(data);
  60633. }, undefined, undefined, true, function (request, exception) {
  60634. reject(exception);
  60635. });
  60636. });
  60637. };
  60638. DracoCompression._GetDefaultConfig = function () {
  60639. var configuration = {
  60640. decoder: null,
  60641. decoderWasm: null
  60642. };
  60643. if (BABYLON.Tools.IsWindowObjectExist()) {
  60644. var decoderUrl = null;
  60645. var decoderWasmBinaryUrl = null;
  60646. var decoderWasmWrapperUrl = null;
  60647. for (var i = 0; i < document.scripts.length; i++) {
  60648. var type = document.scripts[i].type;
  60649. var src = document.scripts[i].src;
  60650. switch (type) {
  60651. case "text/x-draco-decoder": {
  60652. decoderUrl = src;
  60653. break;
  60654. }
  60655. case "text/x-draco-decoder-wasm-binary": {
  60656. decoderWasmBinaryUrl = src;
  60657. break;
  60658. }
  60659. case "text/x-draco-decoder-wasm-wrapper": {
  60660. decoderWasmWrapperUrl = src;
  60661. break;
  60662. }
  60663. }
  60664. }
  60665. if (decoderUrl) {
  60666. configuration.decoder = {
  60667. url: decoderUrl
  60668. };
  60669. }
  60670. if (decoderWasmWrapperUrl && decoderWasmBinaryUrl) {
  60671. configuration.decoderWasm = {
  60672. binaryUrl: decoderWasmBinaryUrl,
  60673. wrapperUrl: decoderWasmWrapperUrl
  60674. };
  60675. }
  60676. }
  60677. return configuration;
  60678. };
  60679. /**
  60680. * Gets the configuration.
  60681. */
  60682. DracoCompression.Configuration = DracoCompression._GetDefaultConfig();
  60683. return DracoCompression;
  60684. }());
  60685. BABYLON.DracoCompression = DracoCompression;
  60686. })(BABYLON || (BABYLON = {}));
  60687. //# sourceMappingURL=babylon.dracoCompression.js.map
  60688. "use strict";
  60689. var BABYLON;
  60690. (function (BABYLON) {
  60691. var AudioEngine = /** @class */ (function () {
  60692. function AudioEngine() {
  60693. this._audioContext = null;
  60694. this._audioContextInitialized = false;
  60695. this.canUseWebAudio = false;
  60696. this.WarnedWebAudioUnsupported = false;
  60697. this.unlocked = false;
  60698. this.isMP3supported = false;
  60699. this.isOGGsupported = false;
  60700. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  60701. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  60702. this.canUseWebAudio = true;
  60703. }
  60704. var audioElem = document.createElement('audio');
  60705. try {
  60706. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  60707. this.isMP3supported = true;
  60708. }
  60709. }
  60710. catch (e) {
  60711. // protect error during capability check.
  60712. }
  60713. try {
  60714. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  60715. this.isOGGsupported = true;
  60716. }
  60717. }
  60718. catch (e) {
  60719. // protect error during capability check.
  60720. }
  60721. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  60722. this._unlockiOSaudio();
  60723. }
  60724. else {
  60725. this.unlocked = true;
  60726. }
  60727. }
  60728. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  60729. get: function () {
  60730. if (!this._audioContextInitialized) {
  60731. this._initializeAudioContext();
  60732. }
  60733. return this._audioContext;
  60734. },
  60735. enumerable: true,
  60736. configurable: true
  60737. });
  60738. AudioEngine.prototype._unlockiOSaudio = function () {
  60739. var _this = this;
  60740. var unlockaudio = function () {
  60741. if (!_this.audioContext) {
  60742. return;
  60743. }
  60744. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  60745. var source = _this.audioContext.createBufferSource();
  60746. source.buffer = buffer;
  60747. source.connect(_this.audioContext.destination);
  60748. source.start(0);
  60749. setTimeout(function () {
  60750. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  60751. _this.unlocked = true;
  60752. window.removeEventListener('touchend', unlockaudio, false);
  60753. if (_this.onAudioUnlocked) {
  60754. _this.onAudioUnlocked();
  60755. }
  60756. }
  60757. }, 0);
  60758. };
  60759. window.addEventListener('touchend', unlockaudio, false);
  60760. };
  60761. AudioEngine.prototype._initializeAudioContext = function () {
  60762. try {
  60763. if (this.canUseWebAudio) {
  60764. this._audioContext = new AudioContext();
  60765. // create a global volume gain node
  60766. this.masterGain = this._audioContext.createGain();
  60767. this.masterGain.gain.value = 1;
  60768. this.masterGain.connect(this._audioContext.destination);
  60769. this._audioContextInitialized = true;
  60770. }
  60771. }
  60772. catch (e) {
  60773. this.canUseWebAudio = false;
  60774. BABYLON.Tools.Error("Web Audio: " + e.message);
  60775. }
  60776. };
  60777. AudioEngine.prototype.dispose = function () {
  60778. if (this.canUseWebAudio && this._audioContextInitialized) {
  60779. if (this._connectedAnalyser && this._audioContext) {
  60780. this._connectedAnalyser.stopDebugCanvas();
  60781. this._connectedAnalyser.dispose();
  60782. this.masterGain.disconnect();
  60783. this.masterGain.connect(this._audioContext.destination);
  60784. this._connectedAnalyser = null;
  60785. }
  60786. this.masterGain.gain.value = 1;
  60787. }
  60788. this.WarnedWebAudioUnsupported = false;
  60789. };
  60790. AudioEngine.prototype.getGlobalVolume = function () {
  60791. if (this.canUseWebAudio && this._audioContextInitialized) {
  60792. return this.masterGain.gain.value;
  60793. }
  60794. else {
  60795. return -1;
  60796. }
  60797. };
  60798. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  60799. if (this.canUseWebAudio && this._audioContextInitialized) {
  60800. this.masterGain.gain.value = newVolume;
  60801. }
  60802. };
  60803. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  60804. if (this._connectedAnalyser) {
  60805. this._connectedAnalyser.stopDebugCanvas();
  60806. }
  60807. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  60808. this._connectedAnalyser = analyser;
  60809. this.masterGain.disconnect();
  60810. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  60811. }
  60812. };
  60813. return AudioEngine;
  60814. }());
  60815. BABYLON.AudioEngine = AudioEngine;
  60816. })(BABYLON || (BABYLON = {}));
  60817. //# sourceMappingURL=babylon.audioEngine.js.map
  60818. "use strict";
  60819. var BABYLON;
  60820. (function (BABYLON) {
  60821. var Sound = /** @class */ (function () {
  60822. /**
  60823. * Create a sound and attach it to a scene
  60824. * @param name Name of your sound
  60825. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  60826. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  60827. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  60828. */
  60829. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  60830. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  60831. var _this = this;
  60832. this.autoplay = false;
  60833. this.loop = false;
  60834. this.useCustomAttenuation = false;
  60835. this.spatialSound = false;
  60836. this.refDistance = 1;
  60837. this.rolloffFactor = 1;
  60838. this.maxDistance = 100;
  60839. this.distanceModel = "linear";
  60840. this._panningModel = "equalpower";
  60841. this._playbackRate = 1;
  60842. this._streaming = false;
  60843. this._startTime = 0;
  60844. this._startOffset = 0;
  60845. this._position = BABYLON.Vector3.Zero();
  60846. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  60847. this._volume = 1;
  60848. this._isReadyToPlay = false;
  60849. this.isPlaying = false;
  60850. this.isPaused = false;
  60851. this._isDirectional = false;
  60852. // Used if you'd like to create a directional sound.
  60853. // If not set, the sound will be omnidirectional
  60854. this._coneInnerAngle = 360;
  60855. this._coneOuterAngle = 360;
  60856. this._coneOuterGain = 0;
  60857. this._isOutputConnected = false;
  60858. this._urlType = "Unknown";
  60859. this.name = name;
  60860. this._scene = scene;
  60861. this._readyToPlayCallback = readyToPlayCallback;
  60862. // Default custom attenuation function is a linear attenuation
  60863. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  60864. if (currentDistance < maxDistance) {
  60865. return currentVolume * (1 - currentDistance / maxDistance);
  60866. }
  60867. else {
  60868. return 0;
  60869. }
  60870. };
  60871. if (options) {
  60872. this.autoplay = options.autoplay || false;
  60873. this.loop = options.loop || false;
  60874. // if volume === 0, we need another way to check this option
  60875. if (options.volume !== undefined) {
  60876. this._volume = options.volume;
  60877. }
  60878. this.spatialSound = options.spatialSound || false;
  60879. this.maxDistance = options.maxDistance || 100;
  60880. this.useCustomAttenuation = options.useCustomAttenuation || false;
  60881. this.rolloffFactor = options.rolloffFactor || 1;
  60882. this.refDistance = options.refDistance || 1;
  60883. this.distanceModel = options.distanceModel || "linear";
  60884. this._playbackRate = options.playbackRate || 1;
  60885. this._streaming = options.streaming || false;
  60886. }
  60887. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60888. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  60889. this._soundGain.gain.value = this._volume;
  60890. this._inputAudioNode = this._soundGain;
  60891. this._ouputAudioNode = this._soundGain;
  60892. if (this.spatialSound) {
  60893. this._createSpatialParameters();
  60894. }
  60895. this._scene.mainSoundTrack.AddSound(this);
  60896. var validParameter = true;
  60897. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  60898. if (urlOrArrayBuffer) {
  60899. try {
  60900. if (typeof (urlOrArrayBuffer) === "string")
  60901. this._urlType = "String";
  60902. if (Array.isArray(urlOrArrayBuffer))
  60903. this._urlType = "Array";
  60904. if (urlOrArrayBuffer instanceof ArrayBuffer)
  60905. this._urlType = "ArrayBuffer";
  60906. var urls = [];
  60907. var codecSupportedFound = false;
  60908. switch (this._urlType) {
  60909. case "ArrayBuffer":
  60910. if (urlOrArrayBuffer.byteLength > 0) {
  60911. codecSupportedFound = true;
  60912. this._soundLoaded(urlOrArrayBuffer);
  60913. }
  60914. break;
  60915. case "String":
  60916. urls.push(urlOrArrayBuffer);
  60917. case "Array":
  60918. if (urls.length === 0)
  60919. urls = urlOrArrayBuffer;
  60920. // If we found a supported format, we load it immediately and stop the loop
  60921. for (var i = 0; i < urls.length; i++) {
  60922. var url = urls[i];
  60923. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  60924. codecSupportedFound = true;
  60925. }
  60926. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  60927. codecSupportedFound = true;
  60928. }
  60929. if (url.indexOf(".wav", url.length - 4) !== -1) {
  60930. codecSupportedFound = true;
  60931. }
  60932. if (url.indexOf("blob:") !== -1) {
  60933. codecSupportedFound = true;
  60934. }
  60935. if (codecSupportedFound) {
  60936. // Loading sound using XHR2
  60937. if (!this._streaming) {
  60938. this._scene._loadFile(url, function (data) {
  60939. _this._soundLoaded(data);
  60940. }, undefined, true, true, function (exception) {
  60941. if (exception) {
  60942. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  60943. }
  60944. BABYLON.Tools.Error("Sound creation aborted.");
  60945. _this._scene.mainSoundTrack.RemoveSound(_this);
  60946. });
  60947. }
  60948. else {
  60949. this._htmlAudioElement = new Audio(url);
  60950. this._htmlAudioElement.controls = false;
  60951. this._htmlAudioElement.loop = this.loop;
  60952. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  60953. this._htmlAudioElement.preload = "auto";
  60954. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  60955. _this._isReadyToPlay = true;
  60956. if (_this.autoplay) {
  60957. _this.play();
  60958. }
  60959. if (_this._readyToPlayCallback) {
  60960. _this._readyToPlayCallback();
  60961. }
  60962. });
  60963. document.body.appendChild(this._htmlAudioElement);
  60964. }
  60965. break;
  60966. }
  60967. }
  60968. break;
  60969. default:
  60970. validParameter = false;
  60971. break;
  60972. }
  60973. if (!validParameter) {
  60974. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  60975. }
  60976. else {
  60977. if (!codecSupportedFound) {
  60978. this._isReadyToPlay = true;
  60979. // Simulating a ready to play event to avoid breaking code path
  60980. if (this._readyToPlayCallback) {
  60981. window.setTimeout(function () {
  60982. if (_this._readyToPlayCallback) {
  60983. _this._readyToPlayCallback();
  60984. }
  60985. }, 1000);
  60986. }
  60987. }
  60988. }
  60989. }
  60990. catch (ex) {
  60991. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  60992. this._scene.mainSoundTrack.RemoveSound(this);
  60993. }
  60994. }
  60995. }
  60996. else {
  60997. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  60998. this._scene.mainSoundTrack.AddSound(this);
  60999. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61000. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61001. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61002. }
  61003. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61004. if (this._readyToPlayCallback) {
  61005. window.setTimeout(function () {
  61006. if (_this._readyToPlayCallback) {
  61007. _this._readyToPlayCallback();
  61008. }
  61009. }, 1000);
  61010. }
  61011. }
  61012. }
  61013. Sound.prototype.dispose = function () {
  61014. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61015. if (this.isPlaying) {
  61016. this.stop();
  61017. }
  61018. this._isReadyToPlay = false;
  61019. if (this.soundTrackId === -1) {
  61020. this._scene.mainSoundTrack.RemoveSound(this);
  61021. }
  61022. else {
  61023. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61024. }
  61025. if (this._soundGain) {
  61026. this._soundGain.disconnect();
  61027. this._soundGain = null;
  61028. }
  61029. if (this._soundPanner) {
  61030. this._soundPanner.disconnect();
  61031. this._soundPanner = null;
  61032. }
  61033. if (this._soundSource) {
  61034. this._soundSource.disconnect();
  61035. this._soundSource = null;
  61036. }
  61037. this._audioBuffer = null;
  61038. if (this._htmlAudioElement) {
  61039. this._htmlAudioElement.pause();
  61040. this._htmlAudioElement.src = "";
  61041. document.body.removeChild(this._htmlAudioElement);
  61042. }
  61043. if (this._connectedMesh && this._registerFunc) {
  61044. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61045. this._connectedMesh = null;
  61046. }
  61047. }
  61048. };
  61049. Sound.prototype.isReady = function () {
  61050. return this._isReadyToPlay;
  61051. };
  61052. Sound.prototype._soundLoaded = function (audioData) {
  61053. var _this = this;
  61054. if (!BABYLON.Engine.audioEngine.audioContext) {
  61055. return;
  61056. }
  61057. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61058. _this._audioBuffer = buffer;
  61059. _this._isReadyToPlay = true;
  61060. if (_this.autoplay) {
  61061. _this.play();
  61062. }
  61063. if (_this._readyToPlayCallback) {
  61064. _this._readyToPlayCallback();
  61065. }
  61066. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61067. };
  61068. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61069. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61070. this._audioBuffer = audioBuffer;
  61071. this._isReadyToPlay = true;
  61072. }
  61073. };
  61074. Sound.prototype.updateOptions = function (options) {
  61075. if (options) {
  61076. this.loop = options.loop || this.loop;
  61077. this.maxDistance = options.maxDistance || this.maxDistance;
  61078. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61079. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61080. this.refDistance = options.refDistance || this.refDistance;
  61081. this.distanceModel = options.distanceModel || this.distanceModel;
  61082. this._playbackRate = options.playbackRate || this._playbackRate;
  61083. this._updateSpatialParameters();
  61084. if (this.isPlaying) {
  61085. if (this._streaming) {
  61086. this._htmlAudioElement.playbackRate = this._playbackRate;
  61087. }
  61088. else {
  61089. if (this._soundSource) {
  61090. this._soundSource.playbackRate.value = this._playbackRate;
  61091. }
  61092. }
  61093. }
  61094. }
  61095. };
  61096. Sound.prototype._createSpatialParameters = function () {
  61097. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61098. if (this._scene.headphone) {
  61099. this._panningModel = "HRTF";
  61100. }
  61101. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61102. this._updateSpatialParameters();
  61103. this._soundPanner.connect(this._ouputAudioNode);
  61104. this._inputAudioNode = this._soundPanner;
  61105. }
  61106. };
  61107. Sound.prototype._updateSpatialParameters = function () {
  61108. if (this.spatialSound && this._soundPanner) {
  61109. if (this.useCustomAttenuation) {
  61110. // Tricks to disable in a way embedded Web Audio attenuation
  61111. this._soundPanner.distanceModel = "linear";
  61112. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61113. this._soundPanner.refDistance = 1;
  61114. this._soundPanner.rolloffFactor = 1;
  61115. this._soundPanner.panningModel = this._panningModel;
  61116. }
  61117. else {
  61118. this._soundPanner.distanceModel = this.distanceModel;
  61119. this._soundPanner.maxDistance = this.maxDistance;
  61120. this._soundPanner.refDistance = this.refDistance;
  61121. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61122. this._soundPanner.panningModel = this._panningModel;
  61123. }
  61124. }
  61125. };
  61126. Sound.prototype.switchPanningModelToHRTF = function () {
  61127. this._panningModel = "HRTF";
  61128. this._switchPanningModel();
  61129. };
  61130. Sound.prototype.switchPanningModelToEqualPower = function () {
  61131. this._panningModel = "equalpower";
  61132. this._switchPanningModel();
  61133. };
  61134. Sound.prototype._switchPanningModel = function () {
  61135. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61136. this._soundPanner.panningModel = this._panningModel;
  61137. }
  61138. };
  61139. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61140. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61141. if (this._isOutputConnected) {
  61142. this._ouputAudioNode.disconnect();
  61143. }
  61144. this._ouputAudioNode.connect(soundTrackAudioNode);
  61145. this._isOutputConnected = true;
  61146. }
  61147. };
  61148. /**
  61149. * Transform this sound into a directional source
  61150. * @param coneInnerAngle Size of the inner cone in degree
  61151. * @param coneOuterAngle Size of the outer cone in degree
  61152. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61153. */
  61154. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61155. if (coneOuterAngle < coneInnerAngle) {
  61156. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61157. return;
  61158. }
  61159. this._coneInnerAngle = coneInnerAngle;
  61160. this._coneOuterAngle = coneOuterAngle;
  61161. this._coneOuterGain = coneOuterGain;
  61162. this._isDirectional = true;
  61163. if (this.isPlaying && this.loop) {
  61164. this.stop();
  61165. this.play();
  61166. }
  61167. };
  61168. Sound.prototype.setPosition = function (newPosition) {
  61169. this._position = newPosition;
  61170. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61171. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61172. }
  61173. };
  61174. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61175. this._localDirection = newLocalDirection;
  61176. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61177. this._updateDirection();
  61178. }
  61179. };
  61180. Sound.prototype._updateDirection = function () {
  61181. if (!this._connectedMesh || !this._soundPanner) {
  61182. return;
  61183. }
  61184. var mat = this._connectedMesh.getWorldMatrix();
  61185. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61186. direction.normalize();
  61187. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61188. };
  61189. Sound.prototype.updateDistanceFromListener = function () {
  61190. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61191. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61192. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61193. }
  61194. };
  61195. Sound.prototype.setAttenuationFunction = function (callback) {
  61196. this._customAttenuationFunction = callback;
  61197. };
  61198. /**
  61199. * Play the sound
  61200. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61201. * @param offset (optional) Start the sound setting it at a specific time
  61202. */
  61203. Sound.prototype.play = function (time, offset) {
  61204. var _this = this;
  61205. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61206. try {
  61207. if (this._startOffset < 0) {
  61208. time = -this._startOffset;
  61209. this._startOffset = 0;
  61210. }
  61211. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61212. if (!this._soundSource || !this._streamingSource) {
  61213. if (this.spatialSound && this._soundPanner) {
  61214. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61215. if (this._isDirectional) {
  61216. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61217. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61218. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61219. if (this._connectedMesh) {
  61220. this._updateDirection();
  61221. }
  61222. else {
  61223. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61224. }
  61225. }
  61226. }
  61227. }
  61228. if (this._streaming) {
  61229. if (!this._streamingSource) {
  61230. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61231. this._htmlAudioElement.onended = function () { _this._onended(); };
  61232. this._htmlAudioElement.playbackRate = this._playbackRate;
  61233. }
  61234. this._streamingSource.disconnect();
  61235. this._streamingSource.connect(this._inputAudioNode);
  61236. this._htmlAudioElement.play();
  61237. }
  61238. else {
  61239. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61240. this._soundSource.buffer = this._audioBuffer;
  61241. this._soundSource.connect(this._inputAudioNode);
  61242. this._soundSource.loop = this.loop;
  61243. this._soundSource.playbackRate.value = this._playbackRate;
  61244. this._soundSource.onended = function () { _this._onended(); };
  61245. if (this._soundSource.buffer) {
  61246. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61247. }
  61248. }
  61249. this._startTime = startTime;
  61250. this.isPlaying = true;
  61251. this.isPaused = false;
  61252. }
  61253. catch (ex) {
  61254. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61255. }
  61256. }
  61257. };
  61258. Sound.prototype._onended = function () {
  61259. this.isPlaying = false;
  61260. if (this.onended) {
  61261. this.onended();
  61262. }
  61263. };
  61264. /**
  61265. * Stop the sound
  61266. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61267. */
  61268. Sound.prototype.stop = function (time) {
  61269. if (this.isPlaying) {
  61270. if (this._streaming) {
  61271. this._htmlAudioElement.pause();
  61272. // Test needed for Firefox or it will generate an Invalid State Error
  61273. if (this._htmlAudioElement.currentTime > 0) {
  61274. this._htmlAudioElement.currentTime = 0;
  61275. }
  61276. }
  61277. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61278. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61279. this._soundSource.stop(stopTime);
  61280. this._soundSource.onended = function () { };
  61281. if (!this.isPaused) {
  61282. this._startOffset = 0;
  61283. }
  61284. }
  61285. this.isPlaying = false;
  61286. }
  61287. };
  61288. Sound.prototype.pause = function () {
  61289. if (this.isPlaying) {
  61290. this.isPaused = true;
  61291. if (this._streaming) {
  61292. this._htmlAudioElement.pause();
  61293. }
  61294. else if (BABYLON.Engine.audioEngine.audioContext) {
  61295. this.stop(0);
  61296. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61297. }
  61298. }
  61299. };
  61300. Sound.prototype.setVolume = function (newVolume, time) {
  61301. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61302. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61303. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61304. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61305. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61306. }
  61307. else {
  61308. this._soundGain.gain.value = newVolume;
  61309. }
  61310. }
  61311. this._volume = newVolume;
  61312. };
  61313. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61314. this._playbackRate = newPlaybackRate;
  61315. if (this.isPlaying) {
  61316. if (this._streaming) {
  61317. this._htmlAudioElement.playbackRate = this._playbackRate;
  61318. }
  61319. else if (this._soundSource) {
  61320. this._soundSource.playbackRate.value = this._playbackRate;
  61321. }
  61322. }
  61323. };
  61324. Sound.prototype.getVolume = function () {
  61325. return this._volume;
  61326. };
  61327. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61328. var _this = this;
  61329. if (this._connectedMesh && this._registerFunc) {
  61330. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61331. this._registerFunc = null;
  61332. }
  61333. this._connectedMesh = meshToConnectTo;
  61334. if (!this.spatialSound) {
  61335. this.spatialSound = true;
  61336. this._createSpatialParameters();
  61337. if (this.isPlaying && this.loop) {
  61338. this.stop();
  61339. this.play();
  61340. }
  61341. }
  61342. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61343. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61344. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61345. };
  61346. Sound.prototype.detachFromMesh = function () {
  61347. if (this._connectedMesh && this._registerFunc) {
  61348. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61349. this._registerFunc = null;
  61350. this._connectedMesh = null;
  61351. }
  61352. };
  61353. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61354. if (!node.getBoundingInfo) {
  61355. return;
  61356. }
  61357. var mesh = node;
  61358. var boundingInfo = mesh.getBoundingInfo();
  61359. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61360. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61361. this._updateDirection();
  61362. }
  61363. };
  61364. Sound.prototype.clone = function () {
  61365. var _this = this;
  61366. if (!this._streaming) {
  61367. var setBufferAndRun = function () {
  61368. if (_this._isReadyToPlay) {
  61369. clonedSound._audioBuffer = _this.getAudioBuffer();
  61370. clonedSound._isReadyToPlay = true;
  61371. if (clonedSound.autoplay) {
  61372. clonedSound.play();
  61373. }
  61374. }
  61375. else {
  61376. window.setTimeout(setBufferAndRun, 300);
  61377. }
  61378. };
  61379. var currentOptions = {
  61380. autoplay: this.autoplay, loop: this.loop,
  61381. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61382. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61383. refDistance: this.refDistance, distanceModel: this.distanceModel
  61384. };
  61385. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61386. if (this.useCustomAttenuation) {
  61387. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61388. }
  61389. clonedSound.setPosition(this._position);
  61390. clonedSound.setPlaybackRate(this._playbackRate);
  61391. setBufferAndRun();
  61392. return clonedSound;
  61393. }
  61394. else {
  61395. return null;
  61396. }
  61397. };
  61398. Sound.prototype.getAudioBuffer = function () {
  61399. return this._audioBuffer;
  61400. };
  61401. Sound.prototype.serialize = function () {
  61402. var serializationObject = {
  61403. name: this.name,
  61404. url: this.name,
  61405. autoplay: this.autoplay,
  61406. loop: this.loop,
  61407. volume: this._volume,
  61408. spatialSound: this.spatialSound,
  61409. maxDistance: this.maxDistance,
  61410. rolloffFactor: this.rolloffFactor,
  61411. refDistance: this.refDistance,
  61412. distanceModel: this.distanceModel,
  61413. playbackRate: this._playbackRate,
  61414. panningModel: this._panningModel,
  61415. soundTrackId: this.soundTrackId
  61416. };
  61417. if (this.spatialSound) {
  61418. if (this._connectedMesh)
  61419. serializationObject.connectedMeshId = this._connectedMesh.id;
  61420. serializationObject.position = this._position.asArray();
  61421. serializationObject.refDistance = this.refDistance;
  61422. serializationObject.distanceModel = this.distanceModel;
  61423. serializationObject.isDirectional = this._isDirectional;
  61424. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  61425. serializationObject.coneInnerAngle = this._coneInnerAngle;
  61426. serializationObject.coneOuterAngle = this._coneOuterAngle;
  61427. serializationObject.coneOuterGain = this._coneOuterGain;
  61428. }
  61429. return serializationObject;
  61430. };
  61431. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  61432. var soundName = parsedSound.name;
  61433. var soundUrl;
  61434. if (parsedSound.url) {
  61435. soundUrl = rootUrl + parsedSound.url;
  61436. }
  61437. else {
  61438. soundUrl = rootUrl + soundName;
  61439. }
  61440. var options = {
  61441. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  61442. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  61443. rolloffFactor: parsedSound.rolloffFactor,
  61444. refDistance: parsedSound.refDistance,
  61445. distanceModel: parsedSound.distanceModel,
  61446. playbackRate: parsedSound.playbackRate
  61447. };
  61448. var newSound;
  61449. if (!sourceSound) {
  61450. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  61451. scene._addPendingData(newSound);
  61452. }
  61453. else {
  61454. var setBufferAndRun = function () {
  61455. if (sourceSound._isReadyToPlay) {
  61456. newSound._audioBuffer = sourceSound.getAudioBuffer();
  61457. newSound._isReadyToPlay = true;
  61458. if (newSound.autoplay) {
  61459. newSound.play();
  61460. }
  61461. }
  61462. else {
  61463. window.setTimeout(setBufferAndRun, 300);
  61464. }
  61465. };
  61466. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  61467. setBufferAndRun();
  61468. }
  61469. if (parsedSound.position) {
  61470. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  61471. newSound.setPosition(soundPosition);
  61472. }
  61473. if (parsedSound.isDirectional) {
  61474. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  61475. if (parsedSound.localDirectionToMesh) {
  61476. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  61477. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  61478. }
  61479. }
  61480. if (parsedSound.connectedMeshId) {
  61481. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  61482. if (connectedMesh) {
  61483. newSound.attachToMesh(connectedMesh);
  61484. }
  61485. }
  61486. return newSound;
  61487. };
  61488. return Sound;
  61489. }());
  61490. BABYLON.Sound = Sound;
  61491. })(BABYLON || (BABYLON = {}));
  61492. //# sourceMappingURL=babylon.sound.js.map
  61493. "use strict";
  61494. var BABYLON;
  61495. (function (BABYLON) {
  61496. var SoundTrack = /** @class */ (function () {
  61497. function SoundTrack(scene, options) {
  61498. this.id = -1;
  61499. this._isMainTrack = false;
  61500. this._isInitialized = false;
  61501. this._scene = scene;
  61502. this.soundCollection = new Array();
  61503. this._options = options;
  61504. if (!this._isMainTrack) {
  61505. this._scene.soundTracks.push(this);
  61506. this.id = this._scene.soundTracks.length - 1;
  61507. }
  61508. }
  61509. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  61510. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61511. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  61512. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  61513. if (this._options) {
  61514. if (this._options.volume) {
  61515. this._outputAudioNode.gain.value = this._options.volume;
  61516. }
  61517. if (this._options.mainTrack) {
  61518. this._isMainTrack = this._options.mainTrack;
  61519. }
  61520. }
  61521. this._isInitialized = true;
  61522. }
  61523. };
  61524. SoundTrack.prototype.dispose = function () {
  61525. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  61526. if (this._connectedAnalyser) {
  61527. this._connectedAnalyser.stopDebugCanvas();
  61528. }
  61529. while (this.soundCollection.length) {
  61530. this.soundCollection[0].dispose();
  61531. }
  61532. if (this._outputAudioNode) {
  61533. this._outputAudioNode.disconnect();
  61534. }
  61535. this._outputAudioNode = null;
  61536. }
  61537. };
  61538. SoundTrack.prototype.AddSound = function (sound) {
  61539. if (!this._isInitialized) {
  61540. this._initializeSoundTrackAudioGraph();
  61541. }
  61542. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61543. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  61544. }
  61545. if (sound.soundTrackId) {
  61546. if (sound.soundTrackId === -1) {
  61547. this._scene.mainSoundTrack.RemoveSound(sound);
  61548. }
  61549. else {
  61550. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  61551. }
  61552. }
  61553. this.soundCollection.push(sound);
  61554. sound.soundTrackId = this.id;
  61555. };
  61556. SoundTrack.prototype.RemoveSound = function (sound) {
  61557. var index = this.soundCollection.indexOf(sound);
  61558. if (index !== -1) {
  61559. this.soundCollection.splice(index, 1);
  61560. }
  61561. };
  61562. SoundTrack.prototype.setVolume = function (newVolume) {
  61563. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61564. this._outputAudioNode.gain.value = newVolume;
  61565. }
  61566. };
  61567. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  61568. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61569. for (var i = 0; i < this.soundCollection.length; i++) {
  61570. this.soundCollection[i].switchPanningModelToHRTF();
  61571. }
  61572. }
  61573. };
  61574. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  61575. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61576. for (var i = 0; i < this.soundCollection.length; i++) {
  61577. this.soundCollection[i].switchPanningModelToEqualPower();
  61578. }
  61579. }
  61580. };
  61581. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  61582. if (this._connectedAnalyser) {
  61583. this._connectedAnalyser.stopDebugCanvas();
  61584. }
  61585. this._connectedAnalyser = analyser;
  61586. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61587. this._outputAudioNode.disconnect();
  61588. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  61589. }
  61590. };
  61591. return SoundTrack;
  61592. }());
  61593. BABYLON.SoundTrack = SoundTrack;
  61594. })(BABYLON || (BABYLON = {}));
  61595. //# sourceMappingURL=babylon.soundtrack.js.map
  61596. "use strict";
  61597. var BABYLON;
  61598. (function (BABYLON) {
  61599. var Analyser = /** @class */ (function () {
  61600. function Analyser(scene) {
  61601. this.SMOOTHING = 0.75;
  61602. this.FFT_SIZE = 512;
  61603. this.BARGRAPHAMPLITUDE = 256;
  61604. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  61605. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  61606. this._scene = scene;
  61607. this._audioEngine = BABYLON.Engine.audioEngine;
  61608. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  61609. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  61610. this._webAudioAnalyser.minDecibels = -140;
  61611. this._webAudioAnalyser.maxDecibels = 0;
  61612. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61613. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61614. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  61615. }
  61616. }
  61617. Analyser.prototype.getFrequencyBinCount = function () {
  61618. if (this._audioEngine.canUseWebAudio) {
  61619. return this._webAudioAnalyser.frequencyBinCount;
  61620. }
  61621. else {
  61622. return 0;
  61623. }
  61624. };
  61625. Analyser.prototype.getByteFrequencyData = function () {
  61626. if (this._audioEngine.canUseWebAudio) {
  61627. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61628. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61629. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  61630. }
  61631. return this._byteFreqs;
  61632. };
  61633. Analyser.prototype.getByteTimeDomainData = function () {
  61634. if (this._audioEngine.canUseWebAudio) {
  61635. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61636. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61637. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  61638. }
  61639. return this._byteTime;
  61640. };
  61641. Analyser.prototype.getFloatFrequencyData = function () {
  61642. if (this._audioEngine.canUseWebAudio) {
  61643. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61644. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61645. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  61646. }
  61647. return this._floatFreqs;
  61648. };
  61649. Analyser.prototype.drawDebugCanvas = function () {
  61650. var _this = this;
  61651. if (this._audioEngine.canUseWebAudio) {
  61652. if (!this._debugCanvas) {
  61653. this._debugCanvas = document.createElement("canvas");
  61654. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  61655. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  61656. this._debugCanvas.style.position = "absolute";
  61657. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  61658. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  61659. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  61660. document.body.appendChild(this._debugCanvas);
  61661. this._registerFunc = function () {
  61662. _this.drawDebugCanvas();
  61663. };
  61664. this._scene.registerBeforeRender(this._registerFunc);
  61665. }
  61666. if (this._registerFunc && this._debugCanvasContext) {
  61667. var workingArray = this.getByteFrequencyData();
  61668. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  61669. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  61670. // Draw the frequency domain chart.
  61671. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  61672. var value = workingArray[i];
  61673. var percent = value / this.BARGRAPHAMPLITUDE;
  61674. var height = this.DEBUGCANVASSIZE.height * percent;
  61675. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  61676. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  61677. var hue = i / this.getFrequencyBinCount() * 360;
  61678. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  61679. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  61680. }
  61681. }
  61682. }
  61683. };
  61684. Analyser.prototype.stopDebugCanvas = function () {
  61685. if (this._debugCanvas) {
  61686. if (this._registerFunc) {
  61687. this._scene.unregisterBeforeRender(this._registerFunc);
  61688. this._registerFunc = null;
  61689. }
  61690. document.body.removeChild(this._debugCanvas);
  61691. this._debugCanvas = null;
  61692. this._debugCanvasContext = null;
  61693. }
  61694. };
  61695. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  61696. if (this._audioEngine.canUseWebAudio) {
  61697. inputAudioNode.connect(this._webAudioAnalyser);
  61698. this._webAudioAnalyser.connect(outputAudioNode);
  61699. }
  61700. };
  61701. Analyser.prototype.dispose = function () {
  61702. if (this._audioEngine.canUseWebAudio) {
  61703. this._webAudioAnalyser.disconnect();
  61704. }
  61705. };
  61706. return Analyser;
  61707. }());
  61708. BABYLON.Analyser = Analyser;
  61709. })(BABYLON || (BABYLON = {}));
  61710. //# sourceMappingURL=babylon.analyser.js.map
  61711. "use strict";
  61712. var BABYLON;
  61713. (function (BABYLON) {
  61714. var CubeTexture = /** @class */ (function (_super) {
  61715. __extends(CubeTexture, _super);
  61716. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  61717. if (extensions === void 0) { extensions = null; }
  61718. if (noMipmap === void 0) { noMipmap = false; }
  61719. if (files === void 0) { files = null; }
  61720. if (onLoad === void 0) { onLoad = null; }
  61721. if (onError === void 0) { onError = null; }
  61722. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  61723. if (prefiltered === void 0) { prefiltered = false; }
  61724. if (forcedExtension === void 0) { forcedExtension = null; }
  61725. var _this = _super.call(this, scene) || this;
  61726. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61727. /**
  61728. * Gets or sets the center of the bounding box associated with the cube texture
  61729. * It must define where the camera used to render the texture was set
  61730. */
  61731. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61732. _this._rotationY = 0;
  61733. _this.name = rootUrl;
  61734. _this.url = rootUrl;
  61735. _this._noMipmap = noMipmap;
  61736. _this.hasAlpha = false;
  61737. _this._format = format;
  61738. _this._prefiltered = prefiltered;
  61739. _this.isCube = true;
  61740. _this._textureMatrix = BABYLON.Matrix.Identity();
  61741. if (prefiltered) {
  61742. _this.gammaSpace = false;
  61743. }
  61744. if (!rootUrl && !files) {
  61745. return _this;
  61746. }
  61747. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  61748. var lastDot = rootUrl.lastIndexOf(".");
  61749. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  61750. var isDDS = (extension === ".dds");
  61751. if (!files) {
  61752. if (!isDDS && !extensions) {
  61753. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  61754. }
  61755. files = [];
  61756. if (extensions) {
  61757. for (var index = 0; index < extensions.length; index++) {
  61758. files.push(rootUrl + extensions[index]);
  61759. }
  61760. }
  61761. }
  61762. _this._files = files;
  61763. if (!_this._texture) {
  61764. if (!scene.useDelayedTextureLoading) {
  61765. if (prefiltered) {
  61766. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  61767. }
  61768. else {
  61769. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  61770. }
  61771. }
  61772. else {
  61773. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61774. }
  61775. }
  61776. else if (onLoad) {
  61777. if (_this._texture.isReady) {
  61778. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  61779. }
  61780. else {
  61781. _this._texture.onLoadedObservable.add(onLoad);
  61782. }
  61783. }
  61784. return _this;
  61785. }
  61786. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  61787. get: function () {
  61788. return this._boundingBoxSize;
  61789. },
  61790. /**
  61791. * Gets or sets the size of the bounding box associated with the cube texture
  61792. * When defined, the cubemap will switch to local mode
  61793. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61794. * @example https://www.babylonjs-playground.com/#RNASML
  61795. */
  61796. set: function (value) {
  61797. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61798. return;
  61799. }
  61800. this._boundingBoxSize = value;
  61801. var scene = this.getScene();
  61802. if (scene) {
  61803. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61804. }
  61805. },
  61806. enumerable: true,
  61807. configurable: true
  61808. });
  61809. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  61810. /**
  61811. * Gets texture matrix rotation angle around Y axis radians.
  61812. */
  61813. get: function () {
  61814. return this._rotationY;
  61815. },
  61816. /**
  61817. * Sets texture matrix rotation angle around Y axis in radians.
  61818. */
  61819. set: function (value) {
  61820. this._rotationY = value;
  61821. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  61822. },
  61823. enumerable: true,
  61824. configurable: true
  61825. });
  61826. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  61827. var rootUrlKey = "";
  61828. files.forEach(function (url) { return rootUrlKey += url; });
  61829. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  61830. };
  61831. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  61832. if (forcedExtension === void 0) { forcedExtension = null; }
  61833. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  61834. };
  61835. // Methods
  61836. CubeTexture.prototype.delayLoad = function () {
  61837. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61838. return;
  61839. }
  61840. var scene = this.getScene();
  61841. if (!scene) {
  61842. return;
  61843. }
  61844. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61845. this._texture = this._getFromCache(this.url, this._noMipmap);
  61846. if (!this._texture) {
  61847. if (this._prefiltered) {
  61848. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  61849. }
  61850. else {
  61851. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  61852. }
  61853. }
  61854. };
  61855. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  61856. return this._textureMatrix;
  61857. };
  61858. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61859. this._textureMatrix = value;
  61860. };
  61861. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61862. var texture = BABYLON.SerializationHelper.Parse(function () {
  61863. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  61864. }, parsedTexture, scene);
  61865. // Local Cubemaps
  61866. if (parsedTexture.boundingBoxPosition) {
  61867. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  61868. }
  61869. if (parsedTexture.boundingBoxSize) {
  61870. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  61871. }
  61872. // Animations
  61873. if (parsedTexture.animations) {
  61874. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  61875. var parsedAnimation = parsedTexture.animations[animationIndex];
  61876. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61877. }
  61878. }
  61879. return texture;
  61880. };
  61881. CubeTexture.prototype.clone = function () {
  61882. var _this = this;
  61883. return BABYLON.SerializationHelper.Clone(function () {
  61884. var scene = _this.getScene();
  61885. if (!scene) {
  61886. return _this;
  61887. }
  61888. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  61889. }, this);
  61890. };
  61891. __decorate([
  61892. BABYLON.serialize("rotationY")
  61893. ], CubeTexture.prototype, "_rotationY", void 0);
  61894. return CubeTexture;
  61895. }(BABYLON.BaseTexture));
  61896. BABYLON.CubeTexture = CubeTexture;
  61897. })(BABYLON || (BABYLON = {}));
  61898. //# sourceMappingURL=babylon.cubeTexture.js.map
  61899. "use strict";
  61900. var BABYLON;
  61901. (function (BABYLON) {
  61902. var RenderTargetTexture = /** @class */ (function (_super) {
  61903. __extends(RenderTargetTexture, _super);
  61904. /**
  61905. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  61906. * or used a shadow, depth texture...
  61907. * @param name The friendly name of the texture
  61908. * @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)
  61909. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  61910. * @param generateMipMaps True if mip maps need to be generated after render.
  61911. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  61912. * @param type The type of the buffer in the RTT (int, half float, float...)
  61913. * @param isCube True if a cube texture needs to be created
  61914. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  61915. * @param generateDepthBuffer True to generate a depth buffer
  61916. * @param generateStencilBuffer True to generate a stencil buffer
  61917. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  61918. */
  61919. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  61920. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  61921. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61922. if (isCube === void 0) { isCube = false; }
  61923. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61924. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  61925. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  61926. if (isMulti === void 0) { isMulti = false; }
  61927. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61928. _this.isCube = isCube;
  61929. /**
  61930. * Use this list to define the list of mesh you want to render.
  61931. */
  61932. _this.renderList = new Array();
  61933. _this.renderParticles = true;
  61934. _this.renderSprites = false;
  61935. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  61936. _this.ignoreCameraViewport = false;
  61937. // Events
  61938. /**
  61939. * An event triggered when the texture is unbind.
  61940. */
  61941. _this.onBeforeBindObservable = new BABYLON.Observable();
  61942. /**
  61943. * An event triggered when the texture is unbind.
  61944. */
  61945. _this.onAfterUnbindObservable = new BABYLON.Observable();
  61946. /**
  61947. * An event triggered before rendering the texture
  61948. */
  61949. _this.onBeforeRenderObservable = new BABYLON.Observable();
  61950. /**
  61951. * An event triggered after rendering the texture
  61952. */
  61953. _this.onAfterRenderObservable = new BABYLON.Observable();
  61954. /**
  61955. * An event triggered after the texture clear
  61956. */
  61957. _this.onClearObservable = new BABYLON.Observable();
  61958. _this._currentRefreshId = -1;
  61959. _this._refreshRate = 1;
  61960. _this._samples = 1;
  61961. /**
  61962. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  61963. * It must define where the camera used to render the texture is set
  61964. */
  61965. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61966. scene = _this.getScene();
  61967. if (!scene) {
  61968. return _this;
  61969. }
  61970. _this._engine = scene.getEngine();
  61971. _this.name = name;
  61972. _this.isRenderTarget = true;
  61973. _this._initialSizeParameter = size;
  61974. _this._processSizeParameter(size);
  61975. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  61976. });
  61977. _this._generateMipMaps = generateMipMaps ? true : false;
  61978. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  61979. // Rendering groups
  61980. _this._renderingManager = new BABYLON.RenderingManager(scene);
  61981. if (isMulti) {
  61982. return _this;
  61983. }
  61984. _this._renderTargetOptions = {
  61985. generateMipMaps: generateMipMaps,
  61986. type: type,
  61987. samplingMode: samplingMode,
  61988. generateDepthBuffer: generateDepthBuffer,
  61989. generateStencilBuffer: generateStencilBuffer
  61990. };
  61991. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  61992. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61993. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61994. }
  61995. if (isCube) {
  61996. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  61997. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  61998. _this._textureMatrix = BABYLON.Matrix.Identity();
  61999. }
  62000. else {
  62001. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62002. }
  62003. return _this;
  62004. }
  62005. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62006. get: function () {
  62007. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62008. },
  62009. enumerable: true,
  62010. configurable: true
  62011. });
  62012. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62013. get: function () {
  62014. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62015. },
  62016. enumerable: true,
  62017. configurable: true
  62018. });
  62019. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62020. get: function () {
  62021. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62022. },
  62023. enumerable: true,
  62024. configurable: true
  62025. });
  62026. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62027. set: function (callback) {
  62028. if (this._onAfterUnbindObserver) {
  62029. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62030. }
  62031. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62032. },
  62033. enumerable: true,
  62034. configurable: true
  62035. });
  62036. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62037. set: function (callback) {
  62038. if (this._onBeforeRenderObserver) {
  62039. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62040. }
  62041. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62042. },
  62043. enumerable: true,
  62044. configurable: true
  62045. });
  62046. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62047. set: function (callback) {
  62048. if (this._onAfterRenderObserver) {
  62049. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62050. }
  62051. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62052. },
  62053. enumerable: true,
  62054. configurable: true
  62055. });
  62056. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62057. set: function (callback) {
  62058. if (this._onClearObserver) {
  62059. this.onClearObservable.remove(this._onClearObserver);
  62060. }
  62061. this._onClearObserver = this.onClearObservable.add(callback);
  62062. },
  62063. enumerable: true,
  62064. configurable: true
  62065. });
  62066. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62067. get: function () {
  62068. return this._renderTargetOptions;
  62069. },
  62070. enumerable: true,
  62071. configurable: true
  62072. });
  62073. RenderTargetTexture.prototype._onRatioRescale = function () {
  62074. if (this._sizeRatio) {
  62075. this.resize(this._initialSizeParameter);
  62076. }
  62077. };
  62078. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62079. get: function () {
  62080. return this._boundingBoxSize;
  62081. },
  62082. /**
  62083. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62084. * When defined, the cubemap will switch to local mode
  62085. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62086. * @example https://www.babylonjs-playground.com/#RNASML
  62087. */
  62088. set: function (value) {
  62089. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62090. return;
  62091. }
  62092. this._boundingBoxSize = value;
  62093. var scene = this.getScene();
  62094. if (scene) {
  62095. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62096. }
  62097. },
  62098. enumerable: true,
  62099. configurable: true
  62100. });
  62101. /**
  62102. * Creates a depth stencil texture.
  62103. * This is only available in WebGL 2 or with the depth texture extension available.
  62104. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62105. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62106. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62107. */
  62108. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62109. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62110. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62111. if (generateStencil === void 0) { generateStencil = false; }
  62112. if (!this.getScene()) {
  62113. return;
  62114. }
  62115. var engine = this.getScene().getEngine();
  62116. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62117. bilinearFiltering: bilinearFiltering,
  62118. comparisonFunction: comparisonFunction,
  62119. generateStencil: generateStencil,
  62120. isCube: this.isCube
  62121. });
  62122. engine.setFrameBufferDepthStencilTexture(this);
  62123. };
  62124. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62125. if (size.ratio) {
  62126. this._sizeRatio = size.ratio;
  62127. this._size = {
  62128. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62129. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62130. };
  62131. }
  62132. else {
  62133. this._size = size;
  62134. }
  62135. };
  62136. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62137. get: function () {
  62138. return this._samples;
  62139. },
  62140. set: function (value) {
  62141. if (this._samples === value) {
  62142. return;
  62143. }
  62144. var scene = this.getScene();
  62145. if (!scene) {
  62146. return;
  62147. }
  62148. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62149. },
  62150. enumerable: true,
  62151. configurable: true
  62152. });
  62153. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62154. this._currentRefreshId = -1;
  62155. };
  62156. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62157. get: function () {
  62158. return this._refreshRate;
  62159. },
  62160. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62161. set: function (value) {
  62162. this._refreshRate = value;
  62163. this.resetRefreshCounter();
  62164. },
  62165. enumerable: true,
  62166. configurable: true
  62167. });
  62168. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62169. if (!this._postProcessManager) {
  62170. var scene = this.getScene();
  62171. if (!scene) {
  62172. return;
  62173. }
  62174. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62175. this._postProcesses = new Array();
  62176. }
  62177. this._postProcesses.push(postProcess);
  62178. this._postProcesses[0].autoClear = false;
  62179. };
  62180. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62181. if (!this._postProcesses) {
  62182. return;
  62183. }
  62184. if (dispose) {
  62185. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62186. var postProcess = _a[_i];
  62187. postProcess.dispose();
  62188. }
  62189. }
  62190. this._postProcesses = [];
  62191. };
  62192. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62193. if (!this._postProcesses) {
  62194. return;
  62195. }
  62196. var index = this._postProcesses.indexOf(postProcess);
  62197. if (index === -1) {
  62198. return;
  62199. }
  62200. this._postProcesses.splice(index, 1);
  62201. if (this._postProcesses.length > 0) {
  62202. this._postProcesses[0].autoClear = false;
  62203. }
  62204. };
  62205. RenderTargetTexture.prototype._shouldRender = function () {
  62206. if (this._currentRefreshId === -1) {
  62207. this._currentRefreshId = 1;
  62208. return true;
  62209. }
  62210. if (this.refreshRate === this._currentRefreshId) {
  62211. this._currentRefreshId = 1;
  62212. return true;
  62213. }
  62214. this._currentRefreshId++;
  62215. return false;
  62216. };
  62217. RenderTargetTexture.prototype.getRenderSize = function () {
  62218. if (this._size.width) {
  62219. return this._size.width;
  62220. }
  62221. return this._size;
  62222. };
  62223. RenderTargetTexture.prototype.getRenderWidth = function () {
  62224. if (this._size.width) {
  62225. return this._size.width;
  62226. }
  62227. return this._size;
  62228. };
  62229. RenderTargetTexture.prototype.getRenderHeight = function () {
  62230. if (this._size.width) {
  62231. return this._size.height;
  62232. }
  62233. return this._size;
  62234. };
  62235. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62236. get: function () {
  62237. return true;
  62238. },
  62239. enumerable: true,
  62240. configurable: true
  62241. });
  62242. RenderTargetTexture.prototype.scale = function (ratio) {
  62243. var newSize = this.getRenderSize() * ratio;
  62244. this.resize(newSize);
  62245. };
  62246. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62247. if (this.isCube) {
  62248. return this._textureMatrix;
  62249. }
  62250. return _super.prototype.getReflectionTextureMatrix.call(this);
  62251. };
  62252. RenderTargetTexture.prototype.resize = function (size) {
  62253. this.releaseInternalTexture();
  62254. var scene = this.getScene();
  62255. if (!scene) {
  62256. return;
  62257. }
  62258. this._processSizeParameter(size);
  62259. if (this.isCube) {
  62260. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62261. }
  62262. else {
  62263. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62264. }
  62265. };
  62266. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62267. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62268. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62269. var scene = this.getScene();
  62270. if (!scene) {
  62271. return;
  62272. }
  62273. var engine = scene.getEngine();
  62274. if (this.useCameraPostProcesses !== undefined) {
  62275. useCameraPostProcess = this.useCameraPostProcesses;
  62276. }
  62277. if (this._waitingRenderList) {
  62278. this.renderList = [];
  62279. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62280. var id = this._waitingRenderList[index];
  62281. var mesh_1 = scene.getMeshByID(id);
  62282. if (mesh_1) {
  62283. this.renderList.push(mesh_1);
  62284. }
  62285. }
  62286. delete this._waitingRenderList;
  62287. }
  62288. // Is predicate defined?
  62289. if (this.renderListPredicate) {
  62290. if (this.renderList) {
  62291. this.renderList.splice(0); // Clear previous renderList
  62292. }
  62293. else {
  62294. this.renderList = [];
  62295. }
  62296. var scene = this.getScene();
  62297. if (!scene) {
  62298. return;
  62299. }
  62300. var sceneMeshes = scene.meshes;
  62301. for (var index = 0; index < sceneMeshes.length; index++) {
  62302. var mesh = sceneMeshes[index];
  62303. if (this.renderListPredicate(mesh)) {
  62304. this.renderList.push(mesh);
  62305. }
  62306. }
  62307. }
  62308. this.onBeforeBindObservable.notifyObservers(this);
  62309. // Set custom projection.
  62310. // Needs to be before binding to prevent changing the aspect ratio.
  62311. var camera;
  62312. if (this.activeCamera) {
  62313. camera = this.activeCamera;
  62314. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62315. if (this.activeCamera !== scene.activeCamera) {
  62316. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62317. }
  62318. }
  62319. else {
  62320. camera = scene.activeCamera;
  62321. if (camera) {
  62322. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62323. }
  62324. }
  62325. // Prepare renderingManager
  62326. this._renderingManager.reset();
  62327. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  62328. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  62329. var sceneRenderId = scene.getRenderId();
  62330. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  62331. var mesh = currentRenderList[meshIndex];
  62332. if (mesh) {
  62333. if (!mesh.isReady(this.refreshRate === 0)) {
  62334. this.resetRefreshCounter();
  62335. continue;
  62336. }
  62337. mesh._preActivateForIntermediateRendering(sceneRenderId);
  62338. var isMasked = void 0;
  62339. if (!this.renderList && camera) {
  62340. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  62341. }
  62342. else {
  62343. isMasked = false;
  62344. }
  62345. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  62346. mesh._activate(sceneRenderId);
  62347. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  62348. var subMesh = mesh.subMeshes[subIndex];
  62349. scene._activeIndices.addCount(subMesh.indexCount, false);
  62350. this._renderingManager.dispatch(subMesh, mesh);
  62351. }
  62352. }
  62353. }
  62354. }
  62355. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  62356. var particleSystem = scene.particleSystems[particleIndex];
  62357. var emitter = particleSystem.emitter;
  62358. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  62359. continue;
  62360. }
  62361. if (currentRenderList.indexOf(emitter) >= 0) {
  62362. this._renderingManager.dispatchParticles(particleSystem);
  62363. }
  62364. }
  62365. if (this.isCube) {
  62366. for (var face = 0; face < 6; face++) {
  62367. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62368. scene.incrementRenderId();
  62369. scene.resetCachedMaterial();
  62370. }
  62371. }
  62372. else {
  62373. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62374. }
  62375. this.onAfterUnbindObservable.notifyObservers(this);
  62376. if (scene.activeCamera) {
  62377. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  62378. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  62379. }
  62380. engine.setViewport(scene.activeCamera.viewport);
  62381. }
  62382. scene.resetCachedMaterial();
  62383. };
  62384. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  62385. var minimum = 128;
  62386. var x = renderDimension * scale;
  62387. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  62388. // Ensure we don't exceed the render dimension (while staying POT)
  62389. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  62390. };
  62391. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62392. var _this = this;
  62393. if (!this._texture) {
  62394. return;
  62395. }
  62396. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  62397. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62398. });
  62399. };
  62400. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  62401. var scene = this.getScene();
  62402. if (!scene) {
  62403. return;
  62404. }
  62405. var engine = scene.getEngine();
  62406. if (!this._texture) {
  62407. return;
  62408. }
  62409. // Bind
  62410. if (this._postProcessManager) {
  62411. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  62412. }
  62413. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  62414. if (this._texture) {
  62415. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  62416. }
  62417. }
  62418. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  62419. // Clear
  62420. if (this.onClearObservable.hasObservers()) {
  62421. this.onClearObservable.notifyObservers(engine);
  62422. }
  62423. else {
  62424. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  62425. }
  62426. if (!this._doNotChangeAspectRatio) {
  62427. scene.updateTransformMatrix(true);
  62428. }
  62429. // Render
  62430. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  62431. if (this._postProcessManager) {
  62432. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  62433. }
  62434. else if (useCameraPostProcess) {
  62435. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  62436. }
  62437. if (!this._doNotChangeAspectRatio) {
  62438. scene.updateTransformMatrix(true);
  62439. }
  62440. // Dump ?
  62441. if (dumpForDebug) {
  62442. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  62443. }
  62444. // Unbind
  62445. if (!this.isCube || faceIndex === 5) {
  62446. if (this.isCube) {
  62447. if (faceIndex === 5) {
  62448. engine.generateMipMapsForCubemap(this._texture);
  62449. }
  62450. }
  62451. this.unbindFrameBuffer(engine, faceIndex);
  62452. }
  62453. else {
  62454. this.onAfterRenderObservable.notifyObservers(faceIndex);
  62455. }
  62456. };
  62457. /**
  62458. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  62459. * This allowed control for front to back rendering or reversly depending of the special needs.
  62460. *
  62461. * @param renderingGroupId The rendering group id corresponding to its index
  62462. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  62463. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  62464. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  62465. */
  62466. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  62467. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  62468. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  62469. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  62470. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  62471. };
  62472. /**
  62473. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  62474. *
  62475. * @param renderingGroupId The rendering group id corresponding to its index
  62476. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  62477. */
  62478. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  62479. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  62480. };
  62481. RenderTargetTexture.prototype.clone = function () {
  62482. var textureSize = this.getSize();
  62483. 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);
  62484. // Base texture
  62485. newTexture.hasAlpha = this.hasAlpha;
  62486. newTexture.level = this.level;
  62487. // RenderTarget Texture
  62488. newTexture.coordinatesMode = this.coordinatesMode;
  62489. if (this.renderList) {
  62490. newTexture.renderList = this.renderList.slice(0);
  62491. }
  62492. return newTexture;
  62493. };
  62494. RenderTargetTexture.prototype.serialize = function () {
  62495. if (!this.name) {
  62496. return null;
  62497. }
  62498. var serializationObject = _super.prototype.serialize.call(this);
  62499. serializationObject.renderTargetSize = this.getRenderSize();
  62500. serializationObject.renderList = [];
  62501. if (this.renderList) {
  62502. for (var index = 0; index < this.renderList.length; index++) {
  62503. serializationObject.renderList.push(this.renderList[index].id);
  62504. }
  62505. }
  62506. return serializationObject;
  62507. };
  62508. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  62509. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  62510. var objBuffer = this.getInternalTexture();
  62511. var scene = this.getScene();
  62512. if (objBuffer && scene) {
  62513. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  62514. }
  62515. };
  62516. RenderTargetTexture.prototype.dispose = function () {
  62517. if (this._postProcessManager) {
  62518. this._postProcessManager.dispose();
  62519. this._postProcessManager = null;
  62520. }
  62521. this.clearPostProcesses(true);
  62522. if (this._resizeObserver) {
  62523. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  62524. this._resizeObserver = null;
  62525. }
  62526. this.renderList = null;
  62527. // Remove from custom render targets
  62528. var scene = this.getScene();
  62529. if (!scene) {
  62530. return;
  62531. }
  62532. var index = scene.customRenderTargets.indexOf(this);
  62533. if (index >= 0) {
  62534. scene.customRenderTargets.splice(index, 1);
  62535. }
  62536. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  62537. var camera = _a[_i];
  62538. index = camera.customRenderTargets.indexOf(this);
  62539. if (index >= 0) {
  62540. camera.customRenderTargets.splice(index, 1);
  62541. }
  62542. }
  62543. _super.prototype.dispose.call(this);
  62544. };
  62545. RenderTargetTexture.prototype._rebuild = function () {
  62546. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62547. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62548. }
  62549. if (this._postProcessManager) {
  62550. this._postProcessManager._rebuild();
  62551. }
  62552. };
  62553. /**
  62554. * Clear the info related to rendering groups preventing retention point in material dispose.
  62555. */
  62556. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  62557. if (this._renderingManager) {
  62558. this._renderingManager.freeRenderingGroups();
  62559. }
  62560. };
  62561. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  62562. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  62563. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  62564. return RenderTargetTexture;
  62565. }(BABYLON.Texture));
  62566. BABYLON.RenderTargetTexture = RenderTargetTexture;
  62567. })(BABYLON || (BABYLON = {}));
  62568. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  62569. "use strict";
  62570. var BABYLON;
  62571. (function (BABYLON) {
  62572. ;
  62573. var MultiRenderTarget = /** @class */ (function (_super) {
  62574. __extends(MultiRenderTarget, _super);
  62575. function MultiRenderTarget(name, size, count, scene, options) {
  62576. var _this = this;
  62577. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  62578. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  62579. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  62580. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  62581. _this._engine = scene.getEngine();
  62582. if (!_this.isSupported) {
  62583. _this.dispose();
  62584. return;
  62585. }
  62586. var types = [];
  62587. var samplingModes = [];
  62588. for (var i = 0; i < count; i++) {
  62589. if (options && options.types && options.types[i] !== undefined) {
  62590. types.push(options.types[i]);
  62591. }
  62592. else {
  62593. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62594. }
  62595. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  62596. samplingModes.push(options.samplingModes[i]);
  62597. }
  62598. else {
  62599. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62600. }
  62601. }
  62602. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  62603. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  62604. _this._size = size;
  62605. _this._multiRenderTargetOptions = {
  62606. samplingModes: samplingModes,
  62607. generateMipMaps: generateMipMaps,
  62608. generateDepthBuffer: generateDepthBuffer,
  62609. generateStencilBuffer: generateStencilBuffer,
  62610. generateDepthTexture: generateDepthTexture,
  62611. types: types,
  62612. textureCount: count
  62613. };
  62614. _this._createInternalTextures();
  62615. _this._createTextures();
  62616. return _this;
  62617. }
  62618. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  62619. get: function () {
  62620. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  62621. },
  62622. enumerable: true,
  62623. configurable: true
  62624. });
  62625. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  62626. get: function () {
  62627. return this._textures;
  62628. },
  62629. enumerable: true,
  62630. configurable: true
  62631. });
  62632. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  62633. get: function () {
  62634. return this._textures[this._textures.length - 1];
  62635. },
  62636. enumerable: true,
  62637. configurable: true
  62638. });
  62639. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  62640. set: function (wrap) {
  62641. if (this._textures) {
  62642. for (var i = 0; i < this._textures.length; i++) {
  62643. this._textures[i].wrapU = wrap;
  62644. }
  62645. }
  62646. },
  62647. enumerable: true,
  62648. configurable: true
  62649. });
  62650. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  62651. set: function (wrap) {
  62652. if (this._textures) {
  62653. for (var i = 0; i < this._textures.length; i++) {
  62654. this._textures[i].wrapV = wrap;
  62655. }
  62656. }
  62657. },
  62658. enumerable: true,
  62659. configurable: true
  62660. });
  62661. MultiRenderTarget.prototype._rebuild = function () {
  62662. this.releaseInternalTextures();
  62663. this._createInternalTextures();
  62664. for (var i = 0; i < this._internalTextures.length; i++) {
  62665. var texture = this._textures[i];
  62666. texture._texture = this._internalTextures[i];
  62667. }
  62668. // Keeps references to frame buffer and stencil/depth buffer
  62669. this._texture = this._internalTextures[0];
  62670. };
  62671. MultiRenderTarget.prototype._createInternalTextures = function () {
  62672. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  62673. };
  62674. MultiRenderTarget.prototype._createTextures = function () {
  62675. this._textures = [];
  62676. for (var i = 0; i < this._internalTextures.length; i++) {
  62677. var texture = new BABYLON.Texture(null, this.getScene());
  62678. texture._texture = this._internalTextures[i];
  62679. this._textures.push(texture);
  62680. }
  62681. // Keeps references to frame buffer and stencil/depth buffer
  62682. this._texture = this._internalTextures[0];
  62683. };
  62684. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  62685. get: function () {
  62686. return this._samples;
  62687. },
  62688. set: function (value) {
  62689. if (this._samples === value) {
  62690. return;
  62691. }
  62692. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  62693. },
  62694. enumerable: true,
  62695. configurable: true
  62696. });
  62697. MultiRenderTarget.prototype.resize = function (size) {
  62698. this.releaseInternalTextures();
  62699. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  62700. this._createInternalTextures();
  62701. };
  62702. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62703. var _this = this;
  62704. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  62705. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62706. });
  62707. };
  62708. MultiRenderTarget.prototype.dispose = function () {
  62709. this.releaseInternalTextures();
  62710. _super.prototype.dispose.call(this);
  62711. };
  62712. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  62713. if (!this._internalTextures) {
  62714. return;
  62715. }
  62716. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  62717. if (this._internalTextures[i] !== undefined) {
  62718. this._internalTextures[i].dispose();
  62719. this._internalTextures.splice(i, 1);
  62720. }
  62721. }
  62722. };
  62723. return MultiRenderTarget;
  62724. }(BABYLON.RenderTargetTexture));
  62725. BABYLON.MultiRenderTarget = MultiRenderTarget;
  62726. })(BABYLON || (BABYLON = {}));
  62727. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  62728. "use strict";
  62729. var BABYLON;
  62730. (function (BABYLON) {
  62731. var MirrorTexture = /** @class */ (function (_super) {
  62732. __extends(MirrorTexture, _super);
  62733. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  62734. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62735. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62736. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62737. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  62738. _this.scene = scene;
  62739. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  62740. _this._transformMatrix = BABYLON.Matrix.Zero();
  62741. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  62742. _this._adaptiveBlurKernel = 0;
  62743. _this._blurKernelX = 0;
  62744. _this._blurKernelY = 0;
  62745. _this._blurRatio = 1.0;
  62746. _this.ignoreCameraViewport = true;
  62747. _this._updateGammaSpace();
  62748. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(_this._updateGammaSpace);
  62749. _this.onBeforeRenderObservable.add(function () {
  62750. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  62751. _this._savedViewMatrix = scene.getViewMatrix();
  62752. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  62753. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  62754. scene.clipPlane = _this.mirrorPlane;
  62755. scene.getEngine().cullBackFaces = false;
  62756. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  62757. });
  62758. _this.onAfterRenderObservable.add(function () {
  62759. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  62760. scene.getEngine().cullBackFaces = true;
  62761. scene._mirroredCameraPosition = null;
  62762. delete scene.clipPlane;
  62763. });
  62764. return _this;
  62765. }
  62766. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  62767. get: function () {
  62768. return this._blurRatio;
  62769. },
  62770. set: function (value) {
  62771. if (this._blurRatio === value) {
  62772. return;
  62773. }
  62774. this._blurRatio = value;
  62775. this._preparePostProcesses();
  62776. },
  62777. enumerable: true,
  62778. configurable: true
  62779. });
  62780. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  62781. set: function (value) {
  62782. this._adaptiveBlurKernel = value;
  62783. this._autoComputeBlurKernel();
  62784. },
  62785. enumerable: true,
  62786. configurable: true
  62787. });
  62788. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  62789. set: function (value) {
  62790. this.blurKernelX = value;
  62791. this.blurKernelY = value;
  62792. },
  62793. enumerable: true,
  62794. configurable: true
  62795. });
  62796. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  62797. get: function () {
  62798. return this._blurKernelX;
  62799. },
  62800. set: function (value) {
  62801. if (this._blurKernelX === value) {
  62802. return;
  62803. }
  62804. this._blurKernelX = value;
  62805. this._preparePostProcesses();
  62806. },
  62807. enumerable: true,
  62808. configurable: true
  62809. });
  62810. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  62811. get: function () {
  62812. return this._blurKernelY;
  62813. },
  62814. set: function (value) {
  62815. if (this._blurKernelY === value) {
  62816. return;
  62817. }
  62818. this._blurKernelY = value;
  62819. this._preparePostProcesses();
  62820. },
  62821. enumerable: true,
  62822. configurable: true
  62823. });
  62824. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  62825. var engine = this.getScene().getEngine();
  62826. var dw = this.getRenderWidth() / engine.getRenderWidth();
  62827. var dh = this.getRenderHeight() / engine.getRenderHeight();
  62828. this.blurKernelX = this._adaptiveBlurKernel * dw;
  62829. this.blurKernelY = this._adaptiveBlurKernel * dh;
  62830. };
  62831. MirrorTexture.prototype._onRatioRescale = function () {
  62832. if (this._sizeRatio) {
  62833. this.resize(this._initialSizeParameter);
  62834. if (!this._adaptiveBlurKernel) {
  62835. this._preparePostProcesses();
  62836. }
  62837. }
  62838. if (this._adaptiveBlurKernel) {
  62839. this._autoComputeBlurKernel();
  62840. }
  62841. };
  62842. MirrorTexture.prototype._updateGammaSpace = function () {
  62843. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  62844. };
  62845. MirrorTexture.prototype._preparePostProcesses = function () {
  62846. this.clearPostProcesses(true);
  62847. if (this._blurKernelX && this._blurKernelY) {
  62848. var engine = this.getScene().getEngine();
  62849. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62850. 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);
  62851. this._blurX.autoClear = false;
  62852. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  62853. this._blurX.inputTexture = this._texture;
  62854. }
  62855. else {
  62856. this._blurX.alwaysForcePOT = true;
  62857. }
  62858. 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);
  62859. this._blurY.autoClear = false;
  62860. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  62861. this.addPostProcess(this._blurX);
  62862. this.addPostProcess(this._blurY);
  62863. }
  62864. else {
  62865. if (this._blurY) {
  62866. this.removePostProcess(this._blurY);
  62867. this._blurY.dispose();
  62868. this._blurY = null;
  62869. }
  62870. if (this._blurX) {
  62871. this.removePostProcess(this._blurX);
  62872. this._blurX.dispose();
  62873. this._blurX = null;
  62874. }
  62875. }
  62876. };
  62877. MirrorTexture.prototype.clone = function () {
  62878. var scene = this.getScene();
  62879. if (!scene) {
  62880. return this;
  62881. }
  62882. var textureSize = this.getSize();
  62883. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  62884. // Base texture
  62885. newTexture.hasAlpha = this.hasAlpha;
  62886. newTexture.level = this.level;
  62887. // Mirror Texture
  62888. newTexture.mirrorPlane = this.mirrorPlane.clone();
  62889. if (this.renderList) {
  62890. newTexture.renderList = this.renderList.slice(0);
  62891. }
  62892. return newTexture;
  62893. };
  62894. MirrorTexture.prototype.serialize = function () {
  62895. if (!this.name) {
  62896. return null;
  62897. }
  62898. var serializationObject = _super.prototype.serialize.call(this);
  62899. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  62900. return serializationObject;
  62901. };
  62902. MirrorTexture.prototype.dispose = function () {
  62903. _super.prototype.dispose.call(this);
  62904. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  62905. };
  62906. return MirrorTexture;
  62907. }(BABYLON.RenderTargetTexture));
  62908. BABYLON.MirrorTexture = MirrorTexture;
  62909. })(BABYLON || (BABYLON = {}));
  62910. //# sourceMappingURL=babylon.mirrorTexture.js.map
  62911. "use strict";
  62912. var BABYLON;
  62913. (function (BABYLON) {
  62914. /**
  62915. * Creates a refraction texture used by refraction channel of the standard material.
  62916. * @param name the texture name
  62917. * @param size size of the underlying texture
  62918. * @param scene root scene
  62919. */
  62920. var RefractionTexture = /** @class */ (function (_super) {
  62921. __extends(RefractionTexture, _super);
  62922. function RefractionTexture(name, size, scene, generateMipMaps) {
  62923. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  62924. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  62925. _this.depth = 2.0;
  62926. _this.onBeforeRenderObservable.add(function () {
  62927. scene.clipPlane = _this.refractionPlane;
  62928. });
  62929. _this.onAfterRenderObservable.add(function () {
  62930. delete scene.clipPlane;
  62931. });
  62932. return _this;
  62933. }
  62934. RefractionTexture.prototype.clone = function () {
  62935. var scene = this.getScene();
  62936. if (!scene) {
  62937. return this;
  62938. }
  62939. var textureSize = this.getSize();
  62940. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  62941. // Base texture
  62942. newTexture.hasAlpha = this.hasAlpha;
  62943. newTexture.level = this.level;
  62944. // Refraction Texture
  62945. newTexture.refractionPlane = this.refractionPlane.clone();
  62946. if (this.renderList) {
  62947. newTexture.renderList = this.renderList.slice(0);
  62948. }
  62949. newTexture.depth = this.depth;
  62950. return newTexture;
  62951. };
  62952. RefractionTexture.prototype.serialize = function () {
  62953. if (!this.name) {
  62954. return null;
  62955. }
  62956. var serializationObject = _super.prototype.serialize.call(this);
  62957. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  62958. serializationObject.depth = this.depth;
  62959. return serializationObject;
  62960. };
  62961. return RefractionTexture;
  62962. }(BABYLON.RenderTargetTexture));
  62963. BABYLON.RefractionTexture = RefractionTexture;
  62964. })(BABYLON || (BABYLON = {}));
  62965. //# sourceMappingURL=babylon.refractionTexture.js.map
  62966. "use strict";
  62967. var BABYLON;
  62968. (function (BABYLON) {
  62969. /**
  62970. * A class extending {BABYLON.Texture} allowing drawing on a texture
  62971. * @see http://doc.babylonjs.com/how_to/dynamictexture
  62972. */
  62973. var DynamicTexture = /** @class */ (function (_super) {
  62974. __extends(DynamicTexture, _super);
  62975. /**
  62976. * Creates a {BABYLON.DynamicTexture}
  62977. * @param name defines the name of the texture
  62978. * @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
  62979. * @param scene defines the scene where you want the texture
  62980. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  62981. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  62982. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  62983. */
  62984. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  62985. if (scene === void 0) { scene = null; }
  62986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62987. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62988. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  62989. _this.name = name;
  62990. _this._engine = _this.getScene().getEngine();
  62991. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62992. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62993. _this._generateMipMaps = generateMipMaps;
  62994. if (options.getContext) {
  62995. _this._canvas = options;
  62996. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62997. }
  62998. else {
  62999. _this._canvas = document.createElement("canvas");
  63000. if (options.width) {
  63001. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63002. }
  63003. else {
  63004. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63005. }
  63006. }
  63007. var textureSize = _this.getSize();
  63008. _this._canvas.width = textureSize.width;
  63009. _this._canvas.height = textureSize.height;
  63010. _this._context = _this._canvas.getContext("2d");
  63011. return _this;
  63012. }
  63013. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63014. /**
  63015. * Gets the current state of canRescale
  63016. */
  63017. get: function () {
  63018. return true;
  63019. },
  63020. enumerable: true,
  63021. configurable: true
  63022. });
  63023. DynamicTexture.prototype._recreate = function (textureSize) {
  63024. this._canvas.width = textureSize.width;
  63025. this._canvas.height = textureSize.height;
  63026. this.releaseInternalTexture();
  63027. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63028. };
  63029. /**
  63030. * Scales the texture
  63031. * @param ratio the scale factor to apply to both width and height
  63032. */
  63033. DynamicTexture.prototype.scale = function (ratio) {
  63034. var textureSize = this.getSize();
  63035. textureSize.width *= ratio;
  63036. textureSize.height *= ratio;
  63037. this._recreate(textureSize);
  63038. };
  63039. /**
  63040. * Resizes the texture
  63041. * @param width the new width
  63042. * @param height the new height
  63043. */
  63044. DynamicTexture.prototype.scaleTo = function (width, height) {
  63045. var textureSize = this.getSize();
  63046. textureSize.width = width;
  63047. textureSize.height = height;
  63048. this._recreate(textureSize);
  63049. };
  63050. /**
  63051. * Gets the context of the canvas used by the texture
  63052. * @returns the canvas context of the dynamic texture
  63053. */
  63054. DynamicTexture.prototype.getContext = function () {
  63055. return this._context;
  63056. };
  63057. /**
  63058. * Clears the texture
  63059. */
  63060. DynamicTexture.prototype.clear = function () {
  63061. var size = this.getSize();
  63062. this._context.fillRect(0, 0, size.width, size.height);
  63063. };
  63064. /**
  63065. * Updates the texture
  63066. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63067. */
  63068. DynamicTexture.prototype.update = function (invertY) {
  63069. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  63070. };
  63071. /**
  63072. * Draws text onto the texture
  63073. * @param text defines the text to be drawn
  63074. * @param x defines the placement of the text from the left
  63075. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63076. * @param font defines the font to be used with font-style, font-size, font-name
  63077. * @param color defines the color used for the text
  63078. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63079. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63080. * @param update defines whether texture is immediately update (default is true)
  63081. */
  63082. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63083. if (update === void 0) { update = true; }
  63084. var size = this.getSize();
  63085. if (clearColor) {
  63086. this._context.fillStyle = clearColor;
  63087. this._context.fillRect(0, 0, size.width, size.height);
  63088. }
  63089. this._context.font = font;
  63090. if (x === null || x === undefined) {
  63091. var textSize = this._context.measureText(text);
  63092. x = (size.width - textSize.width) / 2;
  63093. }
  63094. if (y === null || y === undefined) {
  63095. var fontSize = parseInt((font.replace(/\D/g, '')));
  63096. ;
  63097. y = (size.height / 2) + (fontSize / 3.65);
  63098. }
  63099. this._context.fillStyle = color;
  63100. this._context.fillText(text, x, y);
  63101. if (update) {
  63102. this.update(invertY);
  63103. }
  63104. };
  63105. /**
  63106. * Clones the texture
  63107. * @returns the clone of the texture.
  63108. */
  63109. DynamicTexture.prototype.clone = function () {
  63110. var scene = this.getScene();
  63111. if (!scene) {
  63112. return this;
  63113. }
  63114. var textureSize = this.getSize();
  63115. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63116. // Base texture
  63117. newTexture.hasAlpha = this.hasAlpha;
  63118. newTexture.level = this.level;
  63119. // Dynamic Texture
  63120. newTexture.wrapU = this.wrapU;
  63121. newTexture.wrapV = this.wrapV;
  63122. return newTexture;
  63123. };
  63124. /** @ignore */
  63125. DynamicTexture.prototype._rebuild = function () {
  63126. this.update();
  63127. };
  63128. return DynamicTexture;
  63129. }(BABYLON.Texture));
  63130. BABYLON.DynamicTexture = DynamicTexture;
  63131. })(BABYLON || (BABYLON = {}));
  63132. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63133. "use strict";
  63134. var BABYLON;
  63135. (function (BABYLON) {
  63136. var VideoTexture = /** @class */ (function (_super) {
  63137. __extends(VideoTexture, _super);
  63138. /**
  63139. * Creates a video texture.
  63140. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63141. * @param {string | null} name optional name, will detect from video source, if not defined
  63142. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63143. * @param {BABYLON.Scene} scene is obviously the current scene.
  63144. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63145. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63146. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63147. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63148. */
  63149. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63150. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63151. if (invertY === void 0) { invertY = false; }
  63152. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63153. if (settings === void 0) { settings = {
  63154. autoPlay: true,
  63155. loop: true,
  63156. autoUpdateTexture: true,
  63157. }; }
  63158. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63159. _this._createInternalTexture = function () {
  63160. if (_this._texture != null) {
  63161. return;
  63162. }
  63163. if (!_this._engine.needPOTTextures ||
  63164. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63165. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63166. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63167. }
  63168. else {
  63169. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63170. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63171. _this._generateMipMaps = false;
  63172. }
  63173. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63174. _this._texture.isReady = true;
  63175. _this._updateInternalTexture();
  63176. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63177. _this.onLoadObservable.notifyObservers(_this);
  63178. }
  63179. };
  63180. _this.reset = function () {
  63181. if (_this._texture == null) {
  63182. return;
  63183. }
  63184. _this._texture.dispose();
  63185. _this._texture = null;
  63186. };
  63187. _this._updateInternalTexture = function (e) {
  63188. if (_this._texture == null || !_this._texture.isReady) {
  63189. return;
  63190. }
  63191. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63192. return;
  63193. }
  63194. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63195. };
  63196. _this._engine = _this.getScene().getEngine();
  63197. _this._generateMipMaps = generateMipMaps;
  63198. _this._samplingMode = samplingMode;
  63199. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63200. _this.name = name || _this._getName(src);
  63201. _this.video = _this._getVideo(src);
  63202. if (settings.autoPlay !== undefined) {
  63203. _this.video.autoplay = settings.autoPlay;
  63204. }
  63205. if (settings.loop !== undefined) {
  63206. _this.video.loop = settings.loop;
  63207. }
  63208. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63209. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63210. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63211. _this.video.addEventListener("emptied", _this.reset);
  63212. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63213. _this._createInternalTexture();
  63214. }
  63215. return _this;
  63216. }
  63217. VideoTexture.prototype._getName = function (src) {
  63218. if (src instanceof HTMLVideoElement) {
  63219. return src.currentSrc;
  63220. }
  63221. if (typeof src === "object") {
  63222. return src.toString();
  63223. }
  63224. return src;
  63225. };
  63226. ;
  63227. VideoTexture.prototype._getVideo = function (src) {
  63228. if (src instanceof HTMLVideoElement) {
  63229. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63230. return src;
  63231. }
  63232. var video = document.createElement("video");
  63233. if (typeof src === "string") {
  63234. BABYLON.Tools.SetCorsBehavior(src, video);
  63235. video.src = src;
  63236. }
  63237. else {
  63238. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63239. src.forEach(function (url) {
  63240. var source = document.createElement("source");
  63241. source.src = url;
  63242. video.appendChild(source);
  63243. });
  63244. }
  63245. return video;
  63246. };
  63247. ;
  63248. /**
  63249. * Internal method to initiate `update`.
  63250. */
  63251. VideoTexture.prototype._rebuild = function () {
  63252. this.update();
  63253. };
  63254. /**
  63255. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63256. */
  63257. VideoTexture.prototype.update = function () {
  63258. if (!this.autoUpdateTexture) {
  63259. // Expecting user to call `updateTexture` manually
  63260. return;
  63261. }
  63262. this.updateTexture(true);
  63263. };
  63264. /**
  63265. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63266. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63267. */
  63268. VideoTexture.prototype.updateTexture = function (isVisible) {
  63269. if (!isVisible) {
  63270. return;
  63271. }
  63272. if (this.video.paused) {
  63273. return;
  63274. }
  63275. this._updateInternalTexture();
  63276. };
  63277. /**
  63278. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63279. * @param url New url.
  63280. */
  63281. VideoTexture.prototype.updateURL = function (url) {
  63282. this.video.src = url;
  63283. };
  63284. VideoTexture.prototype.dispose = function () {
  63285. _super.prototype.dispose.call(this);
  63286. this.video.removeEventListener("canplay", this._createInternalTexture);
  63287. this.video.removeEventListener("paused", this._updateInternalTexture);
  63288. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63289. this.video.removeEventListener("emptied", this.reset);
  63290. this.video.pause();
  63291. };
  63292. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63293. var video = document.createElement("video");
  63294. var constraintsDeviceId;
  63295. if (constraints && constraints.deviceId) {
  63296. constraintsDeviceId = {
  63297. exact: constraints.deviceId,
  63298. };
  63299. }
  63300. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63301. if (navigator.mediaDevices) {
  63302. navigator.mediaDevices.getUserMedia({ video: constraints })
  63303. .then(function (stream) {
  63304. if (video.mozSrcObject !== undefined) {
  63305. // hack for Firefox < 19
  63306. video.mozSrcObject = stream;
  63307. }
  63308. else {
  63309. video.srcObject = stream;
  63310. }
  63311. var onPlaying = function () {
  63312. if (onReady) {
  63313. onReady(new VideoTexture("video", video, scene, true, true));
  63314. }
  63315. video.removeEventListener("playing", onPlaying);
  63316. };
  63317. video.addEventListener("playing", onPlaying);
  63318. video.play();
  63319. })
  63320. .catch(function (err) {
  63321. BABYLON.Tools.Error(err.name);
  63322. });
  63323. }
  63324. else {
  63325. navigator.getUserMedia =
  63326. navigator.getUserMedia ||
  63327. navigator.webkitGetUserMedia ||
  63328. navigator.mozGetUserMedia ||
  63329. navigator.msGetUserMedia;
  63330. if (navigator.getUserMedia) {
  63331. navigator.getUserMedia({
  63332. video: {
  63333. deviceId: constraintsDeviceId,
  63334. width: {
  63335. min: (constraints && constraints.minWidth) || 256,
  63336. max: (constraints && constraints.maxWidth) || 640,
  63337. },
  63338. height: {
  63339. min: (constraints && constraints.minHeight) || 256,
  63340. max: (constraints && constraints.maxHeight) || 480,
  63341. },
  63342. },
  63343. }, function (stream) {
  63344. if (video.mozSrcObject !== undefined) {
  63345. // hack for Firefox < 19
  63346. video.mozSrcObject = stream;
  63347. }
  63348. else {
  63349. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  63350. }
  63351. video.play();
  63352. if (onReady) {
  63353. onReady(new VideoTexture("video", video, scene, true, true));
  63354. }
  63355. }, function (e) {
  63356. BABYLON.Tools.Error(e.name);
  63357. });
  63358. }
  63359. }
  63360. };
  63361. return VideoTexture;
  63362. }(BABYLON.Texture));
  63363. BABYLON.VideoTexture = VideoTexture;
  63364. })(BABYLON || (BABYLON = {}));
  63365. //# sourceMappingURL=babylon.videoTexture.js.map
  63366. "use strict";
  63367. var BABYLON;
  63368. (function (BABYLON) {
  63369. var RawTexture = /** @class */ (function (_super) {
  63370. __extends(RawTexture, _super);
  63371. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  63372. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63373. if (invertY === void 0) { invertY = false; }
  63374. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63375. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63376. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63377. _this.format = format;
  63378. _this._engine = scene.getEngine();
  63379. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  63380. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63381. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63382. return _this;
  63383. }
  63384. RawTexture.prototype.update = function (data) {
  63385. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  63386. };
  63387. // Statics
  63388. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63389. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63390. if (invertY === void 0) { invertY = false; }
  63391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63392. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  63393. };
  63394. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63395. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63396. if (invertY === void 0) { invertY = false; }
  63397. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63398. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63399. };
  63400. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63401. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63402. if (invertY === void 0) { invertY = false; }
  63403. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63404. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63405. };
  63406. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63407. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63408. if (invertY === void 0) { invertY = false; }
  63409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63410. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63411. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  63412. };
  63413. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63414. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63415. if (invertY === void 0) { invertY = false; }
  63416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63417. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63418. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  63419. };
  63420. return RawTexture;
  63421. }(BABYLON.Texture));
  63422. BABYLON.RawTexture = RawTexture;
  63423. })(BABYLON || (BABYLON = {}));
  63424. //# sourceMappingURL=babylon.rawTexture.js.map
  63425. "use strict";
  63426. var BABYLON;
  63427. (function (BABYLON) {
  63428. /**
  63429. * Class used to store 3D textures containing user data
  63430. */
  63431. var RawTexture3D = /** @class */ (function (_super) {
  63432. __extends(RawTexture3D, _super);
  63433. /**
  63434. * Create a new RawTexture3D
  63435. * @param data defines the data of the texture
  63436. * @param width defines the width of the texture
  63437. * @param height defines the height of the texture
  63438. * @param depth defines the depth of the texture
  63439. * @param format defines the texture format to use
  63440. * @param scene defines the hosting scene
  63441. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  63442. * @param invertY defines if texture must be stored with Y axis inverted
  63443. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  63444. */
  63445. function RawTexture3D(data, width, height, depth,
  63446. /** Gets or sets the texture format to use*/
  63447. format, scene, generateMipMaps, invertY, samplingMode) {
  63448. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63449. if (invertY === void 0) { invertY = false; }
  63450. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63451. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63452. _this.format = format;
  63453. _this._engine = scene.getEngine();
  63454. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  63455. _this.is3D = true;
  63456. return _this;
  63457. }
  63458. /**
  63459. * Update the texture with new data
  63460. * @param data defines the data to store in the texture
  63461. */
  63462. RawTexture3D.prototype.update = function (data) {
  63463. if (!this._texture) {
  63464. return;
  63465. }
  63466. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  63467. };
  63468. return RawTexture3D;
  63469. }(BABYLON.Texture));
  63470. BABYLON.RawTexture3D = RawTexture3D;
  63471. })(BABYLON || (BABYLON = {}));
  63472. //# sourceMappingURL=babylon.rawTexture3D.js.map
  63473. "use strict";
  63474. var BABYLON;
  63475. (function (BABYLON) {
  63476. /**
  63477. * PostProcess can be used to apply a shader to a texture after it has been rendered
  63478. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  63479. */
  63480. var PostProcess = /** @class */ (function () {
  63481. /**
  63482. * Creates a new instance PostProcess
  63483. * @param name The name of the PostProcess.
  63484. * @param fragmentUrl The url of the fragment shader to be used.
  63485. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  63486. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  63487. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  63488. * @param camera The camera to apply the render pass to.
  63489. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  63490. * @param engine The engine which the post process will be applied. (default: current engine)
  63491. * @param reusable If the post process can be reused on the same frame. (default: false)
  63492. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  63493. * @param textureType Type of textures used when performing the post process. (default: 0)
  63494. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  63495. * @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
  63496. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  63497. */
  63498. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  63499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  63500. if (defines === void 0) { defines = null; }
  63501. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63502. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  63503. if (blockCompilation === void 0) { blockCompilation = false; }
  63504. this.name = name;
  63505. /**
  63506. * Width of the texture to apply the post process on
  63507. */
  63508. this.width = -1;
  63509. /**
  63510. * Height of the texture to apply the post process on
  63511. */
  63512. this.height = -1;
  63513. /**
  63514. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  63515. */
  63516. this._outputTexture = null;
  63517. /**
  63518. * If the buffer needs to be cleared before applying the post process. (default: true)
  63519. * Should be set to false if shader will overwrite all previous pixels.
  63520. */
  63521. this.autoClear = true;
  63522. /**
  63523. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  63524. */
  63525. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  63526. /**
  63527. * Animations to be used for the post processing
  63528. */
  63529. this.animations = new Array();
  63530. /**
  63531. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  63532. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  63533. */
  63534. this.enablePixelPerfectMode = false;
  63535. /**
  63536. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  63537. */
  63538. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  63539. /**
  63540. * Force textures to be a power of two (default: false)
  63541. */
  63542. this.alwaysForcePOT = false;
  63543. /**
  63544. * Number of sample textures (default: 1)
  63545. */
  63546. this.samples = 1;
  63547. /**
  63548. * Modify the scale of the post process to be the same as the viewport (default: false)
  63549. */
  63550. this.adaptScaleToCurrentViewport = false;
  63551. this._reusable = false;
  63552. /**
  63553. * Smart array of input and output textures for the post process.
  63554. */
  63555. this._textures = new BABYLON.SmartArray(2);
  63556. /**
  63557. * The index in _textures that corresponds to the output texture.
  63558. */
  63559. this._currentRenderTextureInd = 0;
  63560. this._scaleRatio = new BABYLON.Vector2(1, 1);
  63561. this._texelSize = BABYLON.Vector2.Zero();
  63562. // Events
  63563. /**
  63564. * An event triggered when the postprocess is activated.
  63565. */
  63566. this.onActivateObservable = new BABYLON.Observable();
  63567. /**
  63568. * An event triggered when the postprocess changes its size.
  63569. */
  63570. this.onSizeChangedObservable = new BABYLON.Observable();
  63571. /**
  63572. * An event triggered when the postprocess applies its effect.
  63573. */
  63574. this.onApplyObservable = new BABYLON.Observable();
  63575. /**
  63576. * An event triggered before rendering the postprocess
  63577. */
  63578. this.onBeforeRenderObservable = new BABYLON.Observable();
  63579. /**
  63580. * An event triggered after rendering the postprocess
  63581. */
  63582. this.onAfterRenderObservable = new BABYLON.Observable();
  63583. if (camera != null) {
  63584. this._camera = camera;
  63585. this._scene = camera.getScene();
  63586. camera.attachPostProcess(this);
  63587. this._engine = this._scene.getEngine();
  63588. this._scene.postProcesses.push(this);
  63589. }
  63590. else if (engine) {
  63591. this._engine = engine;
  63592. this._engine.postProcesses.push(this);
  63593. }
  63594. this._options = options;
  63595. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  63596. this._reusable = reusable || false;
  63597. this._textureType = textureType;
  63598. this._samplers = samplers || [];
  63599. this._samplers.push("textureSampler");
  63600. this._fragmentUrl = fragmentUrl;
  63601. this._vertexUrl = vertexUrl;
  63602. this._parameters = parameters || [];
  63603. this._parameters.push("scale");
  63604. this._indexParameters = indexParameters;
  63605. if (!blockCompilation) {
  63606. this.updateEffect(defines);
  63607. }
  63608. }
  63609. Object.defineProperty(PostProcess.prototype, "onActivate", {
  63610. /**
  63611. * A function that is added to the onActivateObservable
  63612. */
  63613. set: function (callback) {
  63614. if (this._onActivateObserver) {
  63615. this.onActivateObservable.remove(this._onActivateObserver);
  63616. }
  63617. if (callback) {
  63618. this._onActivateObserver = this.onActivateObservable.add(callback);
  63619. }
  63620. },
  63621. enumerable: true,
  63622. configurable: true
  63623. });
  63624. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  63625. /**
  63626. * A function that is added to the onSizeChangedObservable
  63627. */
  63628. set: function (callback) {
  63629. if (this._onSizeChangedObserver) {
  63630. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  63631. }
  63632. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  63633. },
  63634. enumerable: true,
  63635. configurable: true
  63636. });
  63637. Object.defineProperty(PostProcess.prototype, "onApply", {
  63638. /**
  63639. * A function that is added to the onApplyObservable
  63640. */
  63641. set: function (callback) {
  63642. if (this._onApplyObserver) {
  63643. this.onApplyObservable.remove(this._onApplyObserver);
  63644. }
  63645. this._onApplyObserver = this.onApplyObservable.add(callback);
  63646. },
  63647. enumerable: true,
  63648. configurable: true
  63649. });
  63650. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  63651. /**
  63652. * A function that is added to the onBeforeRenderObservable
  63653. */
  63654. set: function (callback) {
  63655. if (this._onBeforeRenderObserver) {
  63656. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63657. }
  63658. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63659. },
  63660. enumerable: true,
  63661. configurable: true
  63662. });
  63663. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  63664. /**
  63665. * A function that is added to the onAfterRenderObservable
  63666. */
  63667. set: function (callback) {
  63668. if (this._onAfterRenderObserver) {
  63669. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63670. }
  63671. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63672. },
  63673. enumerable: true,
  63674. configurable: true
  63675. });
  63676. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  63677. /**
  63678. * 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
  63679. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  63680. */
  63681. get: function () {
  63682. return this._textures.data[this._currentRenderTextureInd];
  63683. },
  63684. set: function (value) {
  63685. this._forcedOutputTexture = value;
  63686. },
  63687. enumerable: true,
  63688. configurable: true
  63689. });
  63690. /**
  63691. * Gets the camera which post process is applied to.
  63692. * @returns The camera the post process is applied to.
  63693. */
  63694. PostProcess.prototype.getCamera = function () {
  63695. return this._camera;
  63696. };
  63697. Object.defineProperty(PostProcess.prototype, "texelSize", {
  63698. /**
  63699. * Gets the texel size of the postprocess.
  63700. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  63701. */
  63702. get: function () {
  63703. if (this._shareOutputWithPostProcess) {
  63704. return this._shareOutputWithPostProcess.texelSize;
  63705. }
  63706. if (this._forcedOutputTexture) {
  63707. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  63708. }
  63709. return this._texelSize;
  63710. },
  63711. enumerable: true,
  63712. configurable: true
  63713. });
  63714. /**
  63715. * Gets the engine which this post process belongs to.
  63716. * @returns The engine the post process was enabled with.
  63717. */
  63718. PostProcess.prototype.getEngine = function () {
  63719. return this._engine;
  63720. };
  63721. /**
  63722. * The effect that is created when initializing the post process.
  63723. * @returns The created effect corrisponding the the postprocess.
  63724. */
  63725. PostProcess.prototype.getEffect = function () {
  63726. return this._effect;
  63727. };
  63728. /**
  63729. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  63730. * @param postProcess The post process to share the output with.
  63731. * @returns This post process.
  63732. */
  63733. PostProcess.prototype.shareOutputWith = function (postProcess) {
  63734. this._disposeTextures();
  63735. this._shareOutputWithPostProcess = postProcess;
  63736. return this;
  63737. };
  63738. /**
  63739. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  63740. * This should be called if the post process that shares output with this post process is disabled/disposed.
  63741. */
  63742. PostProcess.prototype.useOwnOutput = function () {
  63743. if (this._textures.length == 0) {
  63744. this._textures = new BABYLON.SmartArray(2);
  63745. }
  63746. this._shareOutputWithPostProcess = null;
  63747. };
  63748. /**
  63749. * Updates the effect with the current post process compile time values and recompiles the shader.
  63750. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  63751. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  63752. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  63753. * @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
  63754. * @param onCompiled Called when the shader has been compiled.
  63755. * @param onError Called if there is an error when compiling a shader.
  63756. */
  63757. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  63758. if (defines === void 0) { defines = null; }
  63759. if (uniforms === void 0) { uniforms = null; }
  63760. if (samplers === void 0) { samplers = null; }
  63761. 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);
  63762. };
  63763. /**
  63764. * The post process is reusable if it can be used multiple times within one frame.
  63765. * @returns If the post process is reusable
  63766. */
  63767. PostProcess.prototype.isReusable = function () {
  63768. return this._reusable;
  63769. };
  63770. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  63771. PostProcess.prototype.markTextureDirty = function () {
  63772. this.width = -1;
  63773. };
  63774. /**
  63775. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  63776. * 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.
  63777. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  63778. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  63779. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  63780. * @returns The target texture that was bound to be written to.
  63781. */
  63782. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  63783. var _this = this;
  63784. if (sourceTexture === void 0) { sourceTexture = null; }
  63785. camera = camera || this._camera;
  63786. var scene = camera.getScene();
  63787. var engine = scene.getEngine();
  63788. var maxSize = engine.getCaps().maxTextureSize;
  63789. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  63790. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  63791. // 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
  63792. var webVRCamera = camera.parent;
  63793. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  63794. requiredWidth /= 2;
  63795. }
  63796. var desiredWidth = (this._options.width || requiredWidth);
  63797. var desiredHeight = this._options.height || requiredHeight;
  63798. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  63799. if (this.adaptScaleToCurrentViewport) {
  63800. var currentViewport = engine.currentViewport;
  63801. if (currentViewport) {
  63802. desiredWidth *= currentViewport.width;
  63803. desiredHeight *= currentViewport.height;
  63804. }
  63805. }
  63806. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  63807. if (!this._options.width) {
  63808. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  63809. }
  63810. if (!this._options.height) {
  63811. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  63812. }
  63813. }
  63814. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  63815. if (this._textures.length > 0) {
  63816. for (var i = 0; i < this._textures.length; i++) {
  63817. this._engine._releaseTexture(this._textures.data[i]);
  63818. }
  63819. this._textures.reset();
  63820. }
  63821. this.width = desiredWidth;
  63822. this.height = desiredHeight;
  63823. var textureSize = { width: this.width, height: this.height };
  63824. var textureOptions = {
  63825. generateMipMaps: false,
  63826. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  63827. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  63828. samplingMode: this.renderTargetSamplingMode,
  63829. type: this._textureType
  63830. };
  63831. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63832. if (this._reusable) {
  63833. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63834. }
  63835. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  63836. this.onSizeChangedObservable.notifyObservers(this);
  63837. }
  63838. this._textures.forEach(function (texture) {
  63839. if (texture.samples !== _this.samples) {
  63840. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  63841. }
  63842. });
  63843. }
  63844. var target;
  63845. if (this._shareOutputWithPostProcess) {
  63846. target = this._shareOutputWithPostProcess.inputTexture;
  63847. }
  63848. else if (this._forcedOutputTexture) {
  63849. target = this._forcedOutputTexture;
  63850. this.width = this._forcedOutputTexture.width;
  63851. this.height = this._forcedOutputTexture.height;
  63852. }
  63853. else {
  63854. target = this.inputTexture;
  63855. }
  63856. // Bind the input of this post process to be used as the output of the previous post process.
  63857. if (this.enablePixelPerfectMode) {
  63858. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  63859. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  63860. }
  63861. else {
  63862. this._scaleRatio.copyFromFloats(1, 1);
  63863. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  63864. }
  63865. this.onActivateObservable.notifyObservers(camera);
  63866. // Clear
  63867. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  63868. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  63869. }
  63870. if (this._reusable) {
  63871. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  63872. }
  63873. return target;
  63874. };
  63875. Object.defineProperty(PostProcess.prototype, "isSupported", {
  63876. /**
  63877. * If the post process is supported.
  63878. */
  63879. get: function () {
  63880. return this._effect.isSupported;
  63881. },
  63882. enumerable: true,
  63883. configurable: true
  63884. });
  63885. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  63886. /**
  63887. * The aspect ratio of the output texture.
  63888. */
  63889. get: function () {
  63890. if (this._shareOutputWithPostProcess) {
  63891. return this._shareOutputWithPostProcess.aspectRatio;
  63892. }
  63893. if (this._forcedOutputTexture) {
  63894. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  63895. }
  63896. return this.width / this.height;
  63897. },
  63898. enumerable: true,
  63899. configurable: true
  63900. });
  63901. /**
  63902. * Get a value indicating if the post-process is ready to be used
  63903. * @returns true if the post-process is ready (shader is compiled)
  63904. */
  63905. PostProcess.prototype.isReady = function () {
  63906. return this._effect && this._effect.isReady();
  63907. };
  63908. /**
  63909. * Binds all textures and uniforms to the shader, this will be run on every pass.
  63910. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  63911. */
  63912. PostProcess.prototype.apply = function () {
  63913. // Check
  63914. if (!this._effect || !this._effect.isReady())
  63915. return null;
  63916. // States
  63917. this._engine.enableEffect(this._effect);
  63918. this._engine.setState(false);
  63919. this._engine.setDepthBuffer(false);
  63920. this._engine.setDepthWrite(false);
  63921. // Alpha
  63922. this._engine.setAlphaMode(this.alphaMode);
  63923. if (this.alphaConstants) {
  63924. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  63925. }
  63926. // Bind the output texture of the preivous post process as the input to this post process.
  63927. var source;
  63928. if (this._shareOutputWithPostProcess) {
  63929. source = this._shareOutputWithPostProcess.inputTexture;
  63930. }
  63931. else if (this._forcedOutputTexture) {
  63932. source = this._forcedOutputTexture;
  63933. }
  63934. else {
  63935. source = this.inputTexture;
  63936. }
  63937. this._effect._bindTexture("textureSampler", source);
  63938. // Parameters
  63939. this._effect.setVector2("scale", this._scaleRatio);
  63940. this.onApplyObservable.notifyObservers(this._effect);
  63941. return this._effect;
  63942. };
  63943. PostProcess.prototype._disposeTextures = function () {
  63944. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  63945. return;
  63946. }
  63947. if (this._textures.length > 0) {
  63948. for (var i = 0; i < this._textures.length; i++) {
  63949. this._engine._releaseTexture(this._textures.data[i]);
  63950. }
  63951. }
  63952. this._textures.dispose();
  63953. };
  63954. /**
  63955. * Disposes the post process.
  63956. * @param camera The camera to dispose the post process on.
  63957. */
  63958. PostProcess.prototype.dispose = function (camera) {
  63959. camera = camera || this._camera;
  63960. this._disposeTextures();
  63961. if (this._scene) {
  63962. var index_1 = this._scene.postProcesses.indexOf(this);
  63963. if (index_1 !== -1) {
  63964. this._scene.postProcesses.splice(index_1, 1);
  63965. }
  63966. }
  63967. else {
  63968. var index_2 = this._engine.postProcesses.indexOf(this);
  63969. if (index_2 !== -1) {
  63970. this._engine.postProcesses.splice(index_2, 1);
  63971. }
  63972. }
  63973. if (!camera) {
  63974. return;
  63975. }
  63976. camera.detachPostProcess(this);
  63977. var index = camera._postProcesses.indexOf(this);
  63978. if (index === 0 && camera._postProcesses.length > 0) {
  63979. var firstPostProcess = this._camera._getFirstPostProcess();
  63980. if (firstPostProcess) {
  63981. firstPostProcess.markTextureDirty();
  63982. }
  63983. }
  63984. this.onActivateObservable.clear();
  63985. this.onAfterRenderObservable.clear();
  63986. this.onApplyObservable.clear();
  63987. this.onBeforeRenderObservable.clear();
  63988. this.onSizeChangedObservable.clear();
  63989. };
  63990. return PostProcess;
  63991. }());
  63992. BABYLON.PostProcess = PostProcess;
  63993. })(BABYLON || (BABYLON = {}));
  63994. //# sourceMappingURL=babylon.postProcess.js.map
  63995. "use strict";
  63996. var BABYLON;
  63997. (function (BABYLON) {
  63998. var PassPostProcess = /** @class */ (function (_super) {
  63999. __extends(PassPostProcess, _super);
  64000. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64001. if (camera === void 0) { camera = null; }
  64002. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64003. if (blockCompilation === void 0) { blockCompilation = false; }
  64004. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64005. }
  64006. return PassPostProcess;
  64007. }(BABYLON.PostProcess));
  64008. BABYLON.PassPostProcess = PassPostProcess;
  64009. })(BABYLON || (BABYLON = {}));
  64010. //# sourceMappingURL=babylon.passPostProcess.js.map
  64011. "use strict";
  64012. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64013. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64014. s = arguments[i];
  64015. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64016. t[p] = s[p];
  64017. }
  64018. return t;
  64019. };
  64020. var BABYLON;
  64021. (function (BABYLON) {
  64022. /**
  64023. * Default implementation IShadowGenerator.
  64024. * This is the main object responsible of generating shadows in the framework.
  64025. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64026. */
  64027. var ShadowGenerator = /** @class */ (function () {
  64028. /**
  64029. * Creates a ShadowGenerator object.
  64030. * A ShadowGenerator is the required tool to use the shadows.
  64031. * Each light casting shadows needs to use its own ShadowGenerator.
  64032. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64033. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64034. * @param light The light object generating the shadows.
  64035. * @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.
  64036. */
  64037. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64038. this._bias = 0.00005;
  64039. this._normalBias = 0;
  64040. this._blurBoxOffset = 1;
  64041. this._blurScale = 2;
  64042. this._blurKernel = 1;
  64043. this._useKernelBlur = false;
  64044. this._filter = ShadowGenerator.FILTER_NONE;
  64045. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64046. this._contactHardeningLightSizeUVRatio = 0.1;
  64047. this._darkness = 0;
  64048. this._transparencyShadow = false;
  64049. /**
  64050. * Controls the extent to which the shadows fade out at the edge of the frustum
  64051. * Used only by directionals and spots
  64052. */
  64053. this.frustumEdgeFalloff = 0;
  64054. /**
  64055. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64056. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64057. * It might on the other hand introduce peter panning.
  64058. */
  64059. this.forceBackFacesOnly = false;
  64060. this._lightDirection = BABYLON.Vector3.Zero();
  64061. this._viewMatrix = BABYLON.Matrix.Zero();
  64062. this._projectionMatrix = BABYLON.Matrix.Zero();
  64063. this._transformMatrix = BABYLON.Matrix.Zero();
  64064. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64065. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64066. this._currentFaceIndex = 0;
  64067. this._currentFaceIndexCache = 0;
  64068. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64069. this._mapSize = mapSize;
  64070. this._light = light;
  64071. this._scene = light.getScene();
  64072. light._shadowGenerator = this;
  64073. // Texture type fallback from float to int if not supported.
  64074. var caps = this._scene.getEngine().getCaps();
  64075. if (!useFullFloatFirst) {
  64076. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64077. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64078. }
  64079. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64080. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64081. }
  64082. else {
  64083. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64084. }
  64085. }
  64086. else {
  64087. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64088. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64089. }
  64090. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64091. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64092. }
  64093. else {
  64094. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64095. }
  64096. }
  64097. this._initializeGenerator();
  64098. this._applyFilterValues();
  64099. }
  64100. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64101. /**
  64102. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64103. */
  64104. get: function () {
  64105. return this._bias;
  64106. },
  64107. /**
  64108. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64109. */
  64110. set: function (bias) {
  64111. this._bias = bias;
  64112. },
  64113. enumerable: true,
  64114. configurable: true
  64115. });
  64116. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64117. /**
  64118. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64119. */
  64120. get: function () {
  64121. return this._normalBias;
  64122. },
  64123. /**
  64124. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64125. */
  64126. set: function (normalBias) {
  64127. this._normalBias = normalBias;
  64128. },
  64129. enumerable: true,
  64130. configurable: true
  64131. });
  64132. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64133. /**
  64134. * Gets the blur box offset: offset applied during the blur pass.
  64135. * Only usefull if useKernelBlur = false
  64136. */
  64137. get: function () {
  64138. return this._blurBoxOffset;
  64139. },
  64140. /**
  64141. * Sets the blur box offset: offset applied during the blur pass.
  64142. * Only usefull if useKernelBlur = false
  64143. */
  64144. set: function (value) {
  64145. if (this._blurBoxOffset === value) {
  64146. return;
  64147. }
  64148. this._blurBoxOffset = value;
  64149. this._disposeBlurPostProcesses();
  64150. },
  64151. enumerable: true,
  64152. configurable: true
  64153. });
  64154. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64155. /**
  64156. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64157. * 2 means half of the size.
  64158. */
  64159. get: function () {
  64160. return this._blurScale;
  64161. },
  64162. /**
  64163. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64164. * 2 means half of the size.
  64165. */
  64166. set: function (value) {
  64167. if (this._blurScale === value) {
  64168. return;
  64169. }
  64170. this._blurScale = value;
  64171. this._disposeBlurPostProcesses();
  64172. },
  64173. enumerable: true,
  64174. configurable: true
  64175. });
  64176. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64177. /**
  64178. * Gets the blur kernel: kernel size of the blur pass.
  64179. * Only usefull if useKernelBlur = true
  64180. */
  64181. get: function () {
  64182. return this._blurKernel;
  64183. },
  64184. /**
  64185. * Sets the blur kernel: kernel size of the blur pass.
  64186. * Only usefull if useKernelBlur = true
  64187. */
  64188. set: function (value) {
  64189. if (this._blurKernel === value) {
  64190. return;
  64191. }
  64192. this._blurKernel = value;
  64193. this._disposeBlurPostProcesses();
  64194. },
  64195. enumerable: true,
  64196. configurable: true
  64197. });
  64198. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64199. /**
  64200. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64201. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64202. */
  64203. get: function () {
  64204. return this._useKernelBlur;
  64205. },
  64206. /**
  64207. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64208. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64209. */
  64210. set: function (value) {
  64211. if (this._useKernelBlur === value) {
  64212. return;
  64213. }
  64214. this._useKernelBlur = value;
  64215. this._disposeBlurPostProcesses();
  64216. },
  64217. enumerable: true,
  64218. configurable: true
  64219. });
  64220. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  64221. /**
  64222. * Gets the depth scale used in ESM mode.
  64223. */
  64224. get: function () {
  64225. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  64226. },
  64227. /**
  64228. * Sets the depth scale used in ESM mode.
  64229. * This can override the scale stored on the light.
  64230. */
  64231. set: function (value) {
  64232. this._depthScale = value;
  64233. },
  64234. enumerable: true,
  64235. configurable: true
  64236. });
  64237. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  64238. /**
  64239. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  64240. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64241. */
  64242. get: function () {
  64243. return this._filter;
  64244. },
  64245. /**
  64246. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64247. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64248. */
  64249. set: function (value) {
  64250. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64251. if (this._light.needCube()) {
  64252. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64253. this.useExponentialShadowMap = true;
  64254. return;
  64255. }
  64256. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64257. this.useCloseExponentialShadowMap = true;
  64258. return;
  64259. }
  64260. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64261. this.usePoissonSampling = true;
  64262. return;
  64263. }
  64264. }
  64265. // Weblg1 fallback for PCF.
  64266. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64267. if (this._scene.getEngine().webGLVersion === 1) {
  64268. this.usePoissonSampling = true;
  64269. return;
  64270. }
  64271. }
  64272. if (this._filter === value) {
  64273. return;
  64274. }
  64275. this._filter = value;
  64276. this._disposeBlurPostProcesses();
  64277. this._applyFilterValues();
  64278. this._light._markMeshesAsLightDirty();
  64279. },
  64280. enumerable: true,
  64281. configurable: true
  64282. });
  64283. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  64284. /**
  64285. * Gets if the current filter is set to Poisson Sampling.
  64286. */
  64287. get: function () {
  64288. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  64289. },
  64290. /**
  64291. * Sets the current filter to Poisson Sampling.
  64292. */
  64293. set: function (value) {
  64294. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  64295. return;
  64296. }
  64297. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  64298. },
  64299. enumerable: true,
  64300. configurable: true
  64301. });
  64302. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  64303. /**
  64304. * Gets if the current filter is set to VSM.
  64305. * DEPRECATED. Should use useExponentialShadowMap instead.
  64306. */
  64307. get: function () {
  64308. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64309. return this.useExponentialShadowMap;
  64310. },
  64311. /**
  64312. * Sets the current filter is to VSM.
  64313. * DEPRECATED. Should use useExponentialShadowMap instead.
  64314. */
  64315. set: function (value) {
  64316. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64317. this.useExponentialShadowMap = value;
  64318. },
  64319. enumerable: true,
  64320. configurable: true
  64321. });
  64322. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  64323. /**
  64324. * Gets if the current filter is set to blurred VSM.
  64325. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64326. */
  64327. get: function () {
  64328. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64329. return this.useBlurExponentialShadowMap;
  64330. },
  64331. /**
  64332. * Sets the current filter is to blurred VSM.
  64333. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64334. */
  64335. set: function (value) {
  64336. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64337. this.useBlurExponentialShadowMap = value;
  64338. },
  64339. enumerable: true,
  64340. configurable: true
  64341. });
  64342. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  64343. /**
  64344. * Gets if the current filter is set to ESM.
  64345. */
  64346. get: function () {
  64347. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  64348. },
  64349. /**
  64350. * Sets the current filter is to ESM.
  64351. */
  64352. set: function (value) {
  64353. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  64354. return;
  64355. }
  64356. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64357. },
  64358. enumerable: true,
  64359. configurable: true
  64360. });
  64361. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  64362. /**
  64363. * Gets if the current filter is set to filtered ESM.
  64364. */
  64365. get: function () {
  64366. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  64367. },
  64368. /**
  64369. * Gets if the current filter is set to filtered ESM.
  64370. */
  64371. set: function (value) {
  64372. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64373. return;
  64374. }
  64375. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64376. },
  64377. enumerable: true,
  64378. configurable: true
  64379. });
  64380. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  64381. /**
  64382. * Gets if the current filter is set to "close ESM" (using the inverse of the
  64383. * exponential to prevent steep falloff artifacts).
  64384. */
  64385. get: function () {
  64386. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  64387. },
  64388. /**
  64389. * Sets the current filter to "close ESM" (using the inverse of the
  64390. * exponential to prevent steep falloff artifacts).
  64391. */
  64392. set: function (value) {
  64393. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  64394. return;
  64395. }
  64396. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64397. },
  64398. enumerable: true,
  64399. configurable: true
  64400. });
  64401. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  64402. /**
  64403. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  64404. * exponential to prevent steep falloff artifacts).
  64405. */
  64406. get: function () {
  64407. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  64408. },
  64409. /**
  64410. * Sets the current filter to filtered "close ESM" (using the inverse of the
  64411. * exponential to prevent steep falloff artifacts).
  64412. */
  64413. set: function (value) {
  64414. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64415. return;
  64416. }
  64417. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64418. },
  64419. enumerable: true,
  64420. configurable: true
  64421. });
  64422. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  64423. /**
  64424. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  64425. */
  64426. get: function () {
  64427. return this.filter === ShadowGenerator.FILTER_PCF;
  64428. },
  64429. /**
  64430. * Sets the current filter to "PCF" (percentage closer filtering).
  64431. */
  64432. set: function (value) {
  64433. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  64434. return;
  64435. }
  64436. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  64437. },
  64438. enumerable: true,
  64439. configurable: true
  64440. });
  64441. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  64442. /**
  64443. * Gets the PCF or PCSS Quality.
  64444. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64445. */
  64446. get: function () {
  64447. return this._filteringQuality;
  64448. },
  64449. /**
  64450. * Sets the PCF or PCSS Quality.
  64451. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64452. */
  64453. set: function (filteringQuality) {
  64454. this._filteringQuality = filteringQuality;
  64455. },
  64456. enumerable: true,
  64457. configurable: true
  64458. });
  64459. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  64460. /**
  64461. * Gets if the current filter is set to "PCSS" (contact hardening).
  64462. */
  64463. get: function () {
  64464. return this.filter === ShadowGenerator.FILTER_PCSS;
  64465. },
  64466. /**
  64467. * Sets the current filter to "PCSS" (contact hardening).
  64468. */
  64469. set: function (value) {
  64470. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  64471. return;
  64472. }
  64473. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  64474. },
  64475. enumerable: true,
  64476. configurable: true
  64477. });
  64478. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  64479. /**
  64480. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64481. * Using a ratio helps keeping shape stability independently of the map size.
  64482. *
  64483. * It does not account for the light projection as it was having too much
  64484. * instability during the light setup or during light position changes.
  64485. *
  64486. * Only valid if useContactHardeningShadow is true.
  64487. */
  64488. get: function () {
  64489. return this._contactHardeningLightSizeUVRatio;
  64490. },
  64491. /**
  64492. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64493. * Using a ratio helps keeping shape stability independently of the map size.
  64494. *
  64495. * It does not account for the light projection as it was having too much
  64496. * instability during the light setup or during light position changes.
  64497. *
  64498. * Only valid if useContactHardeningShadow is true.
  64499. */
  64500. set: function (contactHardeningLightSizeUVRatio) {
  64501. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  64502. },
  64503. enumerable: true,
  64504. configurable: true
  64505. });
  64506. /**
  64507. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  64508. * 0 means strongest and 1 would means no shadow.
  64509. * @returns the darkness.
  64510. */
  64511. ShadowGenerator.prototype.getDarkness = function () {
  64512. return this._darkness;
  64513. };
  64514. /**
  64515. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  64516. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  64517. * @returns the shadow generator allowing fluent coding.
  64518. */
  64519. ShadowGenerator.prototype.setDarkness = function (darkness) {
  64520. if (darkness >= 1.0)
  64521. this._darkness = 1.0;
  64522. else if (darkness <= 0.0)
  64523. this._darkness = 0.0;
  64524. else
  64525. this._darkness = darkness;
  64526. return this;
  64527. };
  64528. /**
  64529. * Sets the ability to have transparent shadow (boolean).
  64530. * @param transparent True if transparent else False
  64531. * @returns the shadow generator allowing fluent coding
  64532. */
  64533. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  64534. this._transparencyShadow = transparent;
  64535. return this;
  64536. };
  64537. /**
  64538. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  64539. * @returns The render target texture if present otherwise, null
  64540. */
  64541. ShadowGenerator.prototype.getShadowMap = function () {
  64542. return this._shadowMap;
  64543. };
  64544. /**
  64545. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  64546. * @returns The render target texture if the shadow map is present otherwise, null
  64547. */
  64548. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  64549. if (this._shadowMap2) {
  64550. return this._shadowMap2;
  64551. }
  64552. return this._shadowMap;
  64553. };
  64554. /**
  64555. * Helper function to add a mesh and its descendants to the list of shadow casters.
  64556. * @param mesh Mesh to add
  64557. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  64558. * @returns the Shadow Generator itself
  64559. */
  64560. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  64561. if (includeDescendants === void 0) { includeDescendants = true; }
  64562. if (!this._shadowMap) {
  64563. return this;
  64564. }
  64565. if (!this._shadowMap.renderList) {
  64566. this._shadowMap.renderList = [];
  64567. }
  64568. this._shadowMap.renderList.push(mesh);
  64569. if (includeDescendants) {
  64570. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  64571. }
  64572. return this;
  64573. var _a;
  64574. };
  64575. /**
  64576. * Helper function to remove a mesh and its descendants from the list of shadow casters
  64577. * @param mesh Mesh to remove
  64578. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  64579. * @returns the Shadow Generator itself
  64580. */
  64581. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  64582. if (includeDescendants === void 0) { includeDescendants = true; }
  64583. if (!this._shadowMap || !this._shadowMap.renderList) {
  64584. return this;
  64585. }
  64586. var index = this._shadowMap.renderList.indexOf(mesh);
  64587. if (index !== -1) {
  64588. this._shadowMap.renderList.splice(index, 1);
  64589. }
  64590. if (includeDescendants) {
  64591. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  64592. var child = _a[_i];
  64593. this.removeShadowCaster(child);
  64594. }
  64595. }
  64596. return this;
  64597. };
  64598. /**
  64599. * Returns the associated light object.
  64600. * @returns the light generating the shadow
  64601. */
  64602. ShadowGenerator.prototype.getLight = function () {
  64603. return this._light;
  64604. };
  64605. ShadowGenerator.prototype._initializeGenerator = function () {
  64606. this._light._markMeshesAsLightDirty();
  64607. this._initializeShadowMap();
  64608. };
  64609. ShadowGenerator.prototype._initializeShadowMap = function () {
  64610. var _this = this;
  64611. // Render target
  64612. var engine = this._scene.getEngine();
  64613. if (engine.webGLVersion > 1) {
  64614. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  64615. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  64616. }
  64617. else {
  64618. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  64619. }
  64620. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64621. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64622. this._shadowMap.anisotropicFilteringLevel = 1;
  64623. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64624. this._shadowMap.renderParticles = false;
  64625. this._shadowMap.ignoreCameraViewport = true;
  64626. // Record Face Index before render.
  64627. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  64628. _this._currentFaceIndex = faceIndex;
  64629. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64630. engine.setColorWrite(false);
  64631. }
  64632. });
  64633. // Custom render function.
  64634. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  64635. // Blur if required afer render.
  64636. this._shadowMap.onAfterUnbindObservable.add(function () {
  64637. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64638. engine.setColorWrite(true);
  64639. }
  64640. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  64641. return;
  64642. }
  64643. var shadowMap = _this.getShadowMapForRendering();
  64644. if (shadowMap) {
  64645. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  64646. }
  64647. });
  64648. // Clear according to the chosen filter.
  64649. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  64650. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64651. this._shadowMap.onClearObservable.add(function (engine) {
  64652. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64653. engine.clear(clearOne, false, true, false);
  64654. }
  64655. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  64656. engine.clear(clearZero, true, true, false);
  64657. }
  64658. else {
  64659. engine.clear(clearOne, true, true, false);
  64660. }
  64661. });
  64662. };
  64663. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  64664. var _this = this;
  64665. var engine = this._scene.getEngine();
  64666. var targetSize = this._mapSize / this.blurScale;
  64667. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  64668. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  64669. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64670. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64671. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64672. }
  64673. if (this.useKernelBlur) {
  64674. 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);
  64675. this._kernelBlurXPostprocess.width = targetSize;
  64676. this._kernelBlurXPostprocess.height = targetSize;
  64677. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  64678. effect.setTexture("textureSampler", _this._shadowMap);
  64679. });
  64680. 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);
  64681. this._kernelBlurXPostprocess.autoClear = false;
  64682. this._kernelBlurYPostprocess.autoClear = false;
  64683. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64684. this._kernelBlurXPostprocess.packedFloat = true;
  64685. this._kernelBlurYPostprocess.packedFloat = true;
  64686. }
  64687. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  64688. }
  64689. else {
  64690. 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);
  64691. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  64692. effect.setFloat2("screenSize", targetSize, targetSize);
  64693. effect.setTexture("textureSampler", _this._shadowMap);
  64694. });
  64695. this._boxBlurPostprocess.autoClear = false;
  64696. this._blurPostProcesses = [this._boxBlurPostprocess];
  64697. }
  64698. };
  64699. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64700. var index;
  64701. var engine = this._scene.getEngine();
  64702. if (depthOnlySubMeshes.length) {
  64703. engine.setColorWrite(false);
  64704. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64705. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  64706. }
  64707. engine.setColorWrite(true);
  64708. }
  64709. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64710. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  64711. }
  64712. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64713. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  64714. }
  64715. if (this._transparencyShadow) {
  64716. for (index = 0; index < transparentSubMeshes.length; index++) {
  64717. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  64718. }
  64719. }
  64720. };
  64721. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  64722. var _this = this;
  64723. var mesh = subMesh.getRenderingMesh();
  64724. var scene = this._scene;
  64725. var engine = scene.getEngine();
  64726. var material = subMesh.getMaterial();
  64727. if (!material) {
  64728. return;
  64729. }
  64730. // Culling
  64731. engine.setState(material.backFaceCulling);
  64732. // Managing instances
  64733. var batch = mesh._getInstancesRenderList(subMesh._id);
  64734. if (batch.mustReturn) {
  64735. return;
  64736. }
  64737. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  64738. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  64739. engine.enableEffect(this._effect);
  64740. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  64741. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  64742. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  64743. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64744. this._effect.setVector3("lightData", this._cachedDirection);
  64745. }
  64746. else {
  64747. this._effect.setVector3("lightData", this._cachedPosition);
  64748. }
  64749. if (scene.activeCamera) {
  64750. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  64751. }
  64752. // Alpha test
  64753. if (material && material.needAlphaTesting()) {
  64754. var alphaTexture = material.getAlphaTestTexture();
  64755. if (alphaTexture) {
  64756. this._effect.setTexture("diffuseSampler", alphaTexture);
  64757. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  64758. }
  64759. }
  64760. // Bones
  64761. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64762. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  64763. }
  64764. // Morph targets
  64765. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  64766. if (this.forceBackFacesOnly) {
  64767. engine.setState(true, 0, false, true);
  64768. }
  64769. // Draw
  64770. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64771. if (this.forceBackFacesOnly) {
  64772. engine.setState(true, 0, false, false);
  64773. }
  64774. }
  64775. else {
  64776. // Need to reset refresh rate of the shadowMap
  64777. if (this._shadowMap) {
  64778. this._shadowMap.resetRefreshCounter();
  64779. }
  64780. }
  64781. };
  64782. ShadowGenerator.prototype._applyFilterValues = function () {
  64783. if (!this._shadowMap) {
  64784. return;
  64785. }
  64786. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  64787. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64788. }
  64789. else {
  64790. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64791. }
  64792. };
  64793. /**
  64794. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64795. * @param onCompiled Callback triggered at the and of the effects compilation
  64796. * @param options Sets of optional options forcing the compilation with different modes
  64797. */
  64798. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  64799. var _this = this;
  64800. var localOptions = __assign({ useInstances: false }, options);
  64801. var shadowMap = this.getShadowMap();
  64802. if (!shadowMap) {
  64803. if (onCompiled) {
  64804. onCompiled(this);
  64805. }
  64806. return;
  64807. }
  64808. var renderList = shadowMap.renderList;
  64809. if (!renderList) {
  64810. if (onCompiled) {
  64811. onCompiled(this);
  64812. }
  64813. return;
  64814. }
  64815. var subMeshes = new Array();
  64816. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  64817. var mesh = renderList_1[_i];
  64818. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  64819. }
  64820. if (subMeshes.length === 0) {
  64821. if (onCompiled) {
  64822. onCompiled(this);
  64823. }
  64824. return;
  64825. }
  64826. var currentIndex = 0;
  64827. var checkReady = function () {
  64828. if (!_this._scene || !_this._scene.getEngine()) {
  64829. return;
  64830. }
  64831. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  64832. currentIndex++;
  64833. if (currentIndex >= subMeshes.length) {
  64834. if (onCompiled) {
  64835. onCompiled(_this);
  64836. }
  64837. return;
  64838. }
  64839. }
  64840. setTimeout(checkReady, 16);
  64841. };
  64842. checkReady();
  64843. };
  64844. /**
  64845. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64846. * @param options Sets of optional options forcing the compilation with different modes
  64847. * @returns A promise that resolves when the compilation completes
  64848. */
  64849. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  64850. var _this = this;
  64851. return new Promise(function (resolve) {
  64852. _this.forceCompilation(function () {
  64853. resolve();
  64854. }, options);
  64855. });
  64856. };
  64857. /**
  64858. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  64859. * @param subMesh The submesh we want to render in the shadow map
  64860. * @param useInstances Defines wether will draw in the map using instances
  64861. * @returns true if ready otherwise, false
  64862. */
  64863. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  64864. var defines = [];
  64865. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64866. defines.push("#define FLOAT");
  64867. }
  64868. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64869. defines.push("#define ESM");
  64870. }
  64871. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  64872. defines.push("#define DEPTHTEXTURE");
  64873. }
  64874. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64875. var mesh = subMesh.getMesh();
  64876. var material = subMesh.getMaterial();
  64877. // Normal bias.
  64878. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64879. attribs.push(BABYLON.VertexBuffer.NormalKind);
  64880. defines.push("#define NORMAL");
  64881. if (mesh.nonUniformScaling) {
  64882. defines.push("#define NONUNIFORMSCALING");
  64883. }
  64884. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64885. defines.push("#define DIRECTIONINLIGHTDATA");
  64886. }
  64887. }
  64888. // Alpha test
  64889. if (material && material.needAlphaTesting()) {
  64890. var alphaTexture = material.getAlphaTestTexture();
  64891. if (alphaTexture) {
  64892. defines.push("#define ALPHATEST");
  64893. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64894. attribs.push(BABYLON.VertexBuffer.UVKind);
  64895. defines.push("#define UV1");
  64896. }
  64897. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64898. if (alphaTexture.coordinatesIndex === 1) {
  64899. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64900. defines.push("#define UV2");
  64901. }
  64902. }
  64903. }
  64904. }
  64905. // Bones
  64906. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64909. if (mesh.numBoneInfluencers > 4) {
  64910. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64911. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64912. }
  64913. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64914. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  64915. }
  64916. else {
  64917. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64918. }
  64919. // Morph targets
  64920. var manager = mesh.morphTargetManager;
  64921. var morphInfluencers = 0;
  64922. if (manager) {
  64923. if (manager.numInfluencers > 0) {
  64924. defines.push("#define MORPHTARGETS");
  64925. morphInfluencers = manager.numInfluencers;
  64926. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  64927. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  64928. }
  64929. }
  64930. // Instances
  64931. if (useInstances) {
  64932. defines.push("#define INSTANCES");
  64933. attribs.push("world0");
  64934. attribs.push("world1");
  64935. attribs.push("world2");
  64936. attribs.push("world3");
  64937. }
  64938. // Get correct effect
  64939. var join = defines.join("\n");
  64940. if (this._cachedDefines !== join) {
  64941. this._cachedDefines = join;
  64942. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  64943. }
  64944. if (!this._effect.isReady()) {
  64945. return false;
  64946. }
  64947. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64948. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  64949. this._initializeBlurRTTAndPostProcesses();
  64950. }
  64951. }
  64952. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  64953. return false;
  64954. }
  64955. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  64956. return false;
  64957. }
  64958. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  64959. return false;
  64960. }
  64961. return true;
  64962. };
  64963. /**
  64964. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  64965. * @param defines Defines of the material we want to update
  64966. * @param lightIndex Index of the light in the enabled light list of the material
  64967. */
  64968. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  64969. var scene = this._scene;
  64970. var light = this._light;
  64971. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64972. return;
  64973. }
  64974. defines["SHADOW" + lightIndex] = true;
  64975. if (this.useContactHardeningShadow) {
  64976. defines["SHADOWPCSS" + lightIndex] = true;
  64977. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64978. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64979. }
  64980. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64981. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64982. }
  64983. // else default to high.
  64984. }
  64985. if (this.usePercentageCloserFiltering) {
  64986. defines["SHADOWPCF" + lightIndex] = true;
  64987. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64988. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64989. }
  64990. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64991. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64992. }
  64993. // else default to high.
  64994. }
  64995. else if (this.usePoissonSampling) {
  64996. defines["SHADOWPOISSON" + lightIndex] = true;
  64997. }
  64998. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64999. defines["SHADOWESM" + lightIndex] = true;
  65000. }
  65001. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65002. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65003. }
  65004. if (light.needCube()) {
  65005. defines["SHADOWCUBE" + lightIndex] = true;
  65006. }
  65007. };
  65008. /**
  65009. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65010. * defined in the generator but impacting the effect).
  65011. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65012. * @param effect The effect we are binfing the information for
  65013. */
  65014. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65015. var light = this._light;
  65016. var scene = this._scene;
  65017. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65018. return;
  65019. }
  65020. var camera = scene.activeCamera;
  65021. if (!camera) {
  65022. return;
  65023. }
  65024. var shadowMap = this.getShadowMap();
  65025. if (!shadowMap) {
  65026. return;
  65027. }
  65028. if (!light.needCube()) {
  65029. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65030. }
  65031. // Only PCF uses depth stencil texture.
  65032. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65033. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65034. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65035. }
  65036. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65037. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65038. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65039. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65040. }
  65041. else {
  65042. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65043. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65044. }
  65045. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65046. };
  65047. /**
  65048. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65049. * (eq to shadow prjection matrix * light transform matrix)
  65050. * @returns The transform matrix used to create the shadow map
  65051. */
  65052. ShadowGenerator.prototype.getTransformMatrix = function () {
  65053. var scene = this._scene;
  65054. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65055. return this._transformMatrix;
  65056. }
  65057. this._currentRenderID = scene.getRenderId();
  65058. this._currentFaceIndexCache = this._currentFaceIndex;
  65059. var lightPosition = this._light.position;
  65060. if (this._light.computeTransformedInformation()) {
  65061. lightPosition = this._light.transformedPosition;
  65062. }
  65063. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65064. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65065. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65066. }
  65067. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65068. this._cachedPosition.copyFrom(lightPosition);
  65069. this._cachedDirection.copyFrom(this._lightDirection);
  65070. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65071. var shadowMap = this.getShadowMap();
  65072. if (shadowMap) {
  65073. var renderList = shadowMap.renderList;
  65074. if (renderList) {
  65075. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65076. }
  65077. }
  65078. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65079. }
  65080. return this._transformMatrix;
  65081. };
  65082. /**
  65083. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65084. * Cube and 2D textures for instance.
  65085. */
  65086. ShadowGenerator.prototype.recreateShadowMap = function () {
  65087. var shadowMap = this._shadowMap;
  65088. if (!shadowMap) {
  65089. return;
  65090. }
  65091. // Track render list.
  65092. var renderList = shadowMap.renderList;
  65093. // Clean up existing data.
  65094. this._disposeRTTandPostProcesses();
  65095. // Reinitializes.
  65096. this._initializeGenerator();
  65097. // Reaffect the filter to ensure a correct fallback if necessary.
  65098. this.filter = this.filter;
  65099. // Reaffect the filter.
  65100. this._applyFilterValues();
  65101. // Reaffect Render List.
  65102. this._shadowMap.renderList = renderList;
  65103. };
  65104. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65105. if (this._shadowMap2) {
  65106. this._shadowMap2.dispose();
  65107. this._shadowMap2 = null;
  65108. }
  65109. if (this._boxBlurPostprocess) {
  65110. this._boxBlurPostprocess.dispose();
  65111. this._boxBlurPostprocess = null;
  65112. }
  65113. if (this._kernelBlurXPostprocess) {
  65114. this._kernelBlurXPostprocess.dispose();
  65115. this._kernelBlurXPostprocess = null;
  65116. }
  65117. if (this._kernelBlurYPostprocess) {
  65118. this._kernelBlurYPostprocess.dispose();
  65119. this._kernelBlurYPostprocess = null;
  65120. }
  65121. this._blurPostProcesses = [];
  65122. };
  65123. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65124. if (this._shadowMap) {
  65125. this._shadowMap.dispose();
  65126. this._shadowMap = null;
  65127. }
  65128. this._disposeBlurPostProcesses();
  65129. };
  65130. /**
  65131. * Disposes the ShadowGenerator.
  65132. * Returns nothing.
  65133. */
  65134. ShadowGenerator.prototype.dispose = function () {
  65135. this._disposeRTTandPostProcesses();
  65136. if (this._light) {
  65137. this._light._shadowGenerator = null;
  65138. this._light._markMeshesAsLightDirty();
  65139. }
  65140. };
  65141. /**
  65142. * Serializes the shadow generator setup to a json object.
  65143. * @returns The serialized JSON object
  65144. */
  65145. ShadowGenerator.prototype.serialize = function () {
  65146. var serializationObject = {};
  65147. var shadowMap = this.getShadowMap();
  65148. if (!shadowMap) {
  65149. return serializationObject;
  65150. }
  65151. serializationObject.lightId = this._light.id;
  65152. serializationObject.mapSize = shadowMap.getRenderSize();
  65153. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65154. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65155. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65156. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65157. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65158. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65159. serializationObject.depthScale = this.depthScale;
  65160. serializationObject.darkness = this.getDarkness();
  65161. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65162. serializationObject.blurKernel = this.blurKernel;
  65163. serializationObject.blurScale = this.blurScale;
  65164. serializationObject.useKernelBlur = this.useKernelBlur;
  65165. serializationObject.transparencyShadow = this._transparencyShadow;
  65166. serializationObject.bias = this.bias;
  65167. serializationObject.normalBias = this.normalBias;
  65168. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65169. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65170. serializationObject.filteringQuality = this.filteringQuality;
  65171. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65172. serializationObject.renderList = [];
  65173. if (shadowMap.renderList) {
  65174. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65175. var mesh = shadowMap.renderList[meshIndex];
  65176. serializationObject.renderList.push(mesh.id);
  65177. }
  65178. }
  65179. return serializationObject;
  65180. };
  65181. /**
  65182. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65183. * @param parsedShadowGenerator The JSON object to parse
  65184. * @param scene The scene to create the shadow map for
  65185. * @returns The parsed shadow generator
  65186. */
  65187. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65188. //casting to point light, as light is missing the position attr and typescript complains.
  65189. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65190. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65191. var shadowMap = shadowGenerator.getShadowMap();
  65192. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65193. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65194. meshes.forEach(function (mesh) {
  65195. if (!shadowMap) {
  65196. return;
  65197. }
  65198. if (!shadowMap.renderList) {
  65199. shadowMap.renderList = [];
  65200. }
  65201. shadowMap.renderList.push(mesh);
  65202. });
  65203. }
  65204. if (parsedShadowGenerator.usePoissonSampling) {
  65205. shadowGenerator.usePoissonSampling = true;
  65206. }
  65207. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65208. shadowGenerator.useExponentialShadowMap = true;
  65209. }
  65210. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65211. shadowGenerator.useBlurExponentialShadowMap = true;
  65212. }
  65213. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65214. shadowGenerator.useCloseExponentialShadowMap = true;
  65215. }
  65216. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  65217. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  65218. }
  65219. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  65220. shadowGenerator.usePercentageCloserFiltering = true;
  65221. }
  65222. else if (parsedShadowGenerator.useContactHardeningShadow) {
  65223. shadowGenerator.useContactHardeningShadow = true;
  65224. }
  65225. if (parsedShadowGenerator.filteringQuality) {
  65226. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  65227. }
  65228. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  65229. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  65230. }
  65231. else if (parsedShadowGenerator.useVarianceShadowMap) {
  65232. shadowGenerator.useExponentialShadowMap = true;
  65233. }
  65234. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  65235. shadowGenerator.useBlurExponentialShadowMap = true;
  65236. }
  65237. if (parsedShadowGenerator.depthScale) {
  65238. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  65239. }
  65240. if (parsedShadowGenerator.blurScale) {
  65241. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65242. }
  65243. if (parsedShadowGenerator.blurBoxOffset) {
  65244. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65245. }
  65246. if (parsedShadowGenerator.useKernelBlur) {
  65247. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65248. }
  65249. if (parsedShadowGenerator.blurKernel) {
  65250. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65251. }
  65252. if (parsedShadowGenerator.bias !== undefined) {
  65253. shadowGenerator.bias = parsedShadowGenerator.bias;
  65254. }
  65255. if (parsedShadowGenerator.normalBias !== undefined) {
  65256. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65257. }
  65258. if (parsedShadowGenerator.darkness) {
  65259. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  65260. }
  65261. if (parsedShadowGenerator.transparencyShadow) {
  65262. shadowGenerator.setTransparencyShadow(true);
  65263. }
  65264. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  65265. return shadowGenerator;
  65266. };
  65267. /**
  65268. * Shadow generator mode None: no filtering applied.
  65269. */
  65270. ShadowGenerator.FILTER_NONE = 0;
  65271. /**
  65272. * Shadow generator mode ESM: Exponential Shadow Mapping.
  65273. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65274. */
  65275. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  65276. /**
  65277. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  65278. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  65279. */
  65280. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  65281. /**
  65282. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  65283. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65284. */
  65285. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  65286. /**
  65287. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  65288. * edge artifacts on steep falloff.
  65289. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65290. */
  65291. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  65292. /**
  65293. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  65294. * edge artifacts on steep falloff.
  65295. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65296. */
  65297. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  65298. /**
  65299. * Shadow generator mode PCF: Percentage Closer Filtering
  65300. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65301. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  65302. */
  65303. ShadowGenerator.FILTER_PCF = 6;
  65304. /**
  65305. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  65306. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65307. * Contact Hardening
  65308. */
  65309. ShadowGenerator.FILTER_PCSS = 7;
  65310. /**
  65311. * Reserved for PCF and PCSS
  65312. * Highest Quality.
  65313. *
  65314. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  65315. *
  65316. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  65317. */
  65318. ShadowGenerator.QUALITY_HIGH = 0;
  65319. /**
  65320. * Reserved for PCF and PCSS
  65321. * Good tradeoff for quality/perf cross devices
  65322. *
  65323. * Execute PCF on a 3*3 kernel.
  65324. *
  65325. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  65326. */
  65327. ShadowGenerator.QUALITY_MEDIUM = 1;
  65328. /**
  65329. * Reserved for PCF and PCSS
  65330. * The lowest quality but the fastest.
  65331. *
  65332. * Execute PCF on a 1*1 kernel.
  65333. *
  65334. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  65335. */
  65336. ShadowGenerator.QUALITY_LOW = 2;
  65337. return ShadowGenerator;
  65338. }());
  65339. BABYLON.ShadowGenerator = ShadowGenerator;
  65340. })(BABYLON || (BABYLON = {}));
  65341. //# sourceMappingURL=babylon.shadowGenerator.js.map
  65342. "use strict";
  65343. var BABYLON;
  65344. (function (BABYLON) {
  65345. var DefaultLoadingScreen = /** @class */ (function () {
  65346. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  65347. if (_loadingText === void 0) { _loadingText = ""; }
  65348. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  65349. var _this = this;
  65350. this._renderingCanvas = _renderingCanvas;
  65351. this._loadingText = _loadingText;
  65352. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  65353. // Resize
  65354. this._resizeLoadingUI = function () {
  65355. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  65356. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  65357. if (!_this._loadingDiv) {
  65358. return;
  65359. }
  65360. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  65361. _this._loadingDiv.style.left = canvasRect.left + "px";
  65362. _this._loadingDiv.style.top = canvasRect.top + "px";
  65363. _this._loadingDiv.style.width = canvasRect.width + "px";
  65364. _this._loadingDiv.style.height = canvasRect.height + "px";
  65365. };
  65366. }
  65367. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  65368. if (this._loadingDiv) {
  65369. // Do not add a loading screen if there is already one
  65370. return;
  65371. }
  65372. this._loadingDiv = document.createElement("div");
  65373. this._loadingDiv.id = "babylonjsLoadingDiv";
  65374. this._loadingDiv.style.opacity = "0";
  65375. this._loadingDiv.style.transition = "opacity 1.5s ease";
  65376. this._loadingDiv.style.pointerEvents = "none";
  65377. // Loading text
  65378. this._loadingTextDiv = document.createElement("div");
  65379. this._loadingTextDiv.style.position = "absolute";
  65380. this._loadingTextDiv.style.left = "0";
  65381. this._loadingTextDiv.style.top = "50%";
  65382. this._loadingTextDiv.style.marginTop = "80px";
  65383. this._loadingTextDiv.style.width = "100%";
  65384. this._loadingTextDiv.style.height = "20px";
  65385. this._loadingTextDiv.style.fontFamily = "Arial";
  65386. this._loadingTextDiv.style.fontSize = "14px";
  65387. this._loadingTextDiv.style.color = "white";
  65388. this._loadingTextDiv.style.textAlign = "center";
  65389. this._loadingTextDiv.innerHTML = "Loading";
  65390. this._loadingDiv.appendChild(this._loadingTextDiv);
  65391. //set the predefined text
  65392. this._loadingTextDiv.innerHTML = this._loadingText;
  65393. // Generating keyframes
  65394. var style = document.createElement('style');
  65395. style.type = 'text/css';
  65396. 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 }";
  65397. style.innerHTML = keyFrames;
  65398. document.getElementsByTagName('head')[0].appendChild(style);
  65399. // Loading img
  65400. var imgBack = new Image();
  65401. 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";
  65402. imgBack.style.position = "absolute";
  65403. imgBack.style.left = "50%";
  65404. imgBack.style.top = "50%";
  65405. imgBack.style.marginLeft = "-60px";
  65406. imgBack.style.marginTop = "-60px";
  65407. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  65408. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  65409. imgBack.style.transformOrigin = "50% 50%";
  65410. imgBack.style.webkitTransformOrigin = "50% 50%";
  65411. this._loadingDiv.appendChild(imgBack);
  65412. this._resizeLoadingUI();
  65413. window.addEventListener("resize", this._resizeLoadingUI);
  65414. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65415. document.body.appendChild(this._loadingDiv);
  65416. this._loadingDiv.style.opacity = "1";
  65417. };
  65418. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  65419. var _this = this;
  65420. if (!this._loadingDiv) {
  65421. return;
  65422. }
  65423. var onTransitionEnd = function () {
  65424. if (!_this._loadingDiv) {
  65425. return;
  65426. }
  65427. document.body.removeChild(_this._loadingDiv);
  65428. window.removeEventListener("resize", _this._resizeLoadingUI);
  65429. _this._loadingDiv = null;
  65430. };
  65431. this._loadingDiv.style.opacity = "0";
  65432. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  65433. };
  65434. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  65435. set: function (text) {
  65436. this._loadingText = text;
  65437. if (this._loadingTextDiv) {
  65438. this._loadingTextDiv.innerHTML = this._loadingText;
  65439. }
  65440. },
  65441. enumerable: true,
  65442. configurable: true
  65443. });
  65444. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  65445. get: function () {
  65446. return this._loadingDivBackgroundColor;
  65447. },
  65448. set: function (color) {
  65449. this._loadingDivBackgroundColor = color;
  65450. if (!this._loadingDiv) {
  65451. return;
  65452. }
  65453. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65454. },
  65455. enumerable: true,
  65456. configurable: true
  65457. });
  65458. return DefaultLoadingScreen;
  65459. }());
  65460. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  65461. })(BABYLON || (BABYLON = {}));
  65462. //# sourceMappingURL=babylon.loadingScreen.js.map
  65463. "use strict";
  65464. var BABYLON;
  65465. (function (BABYLON) {
  65466. var SceneLoaderProgressEvent = /** @class */ (function () {
  65467. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  65468. this.lengthComputable = lengthComputable;
  65469. this.loaded = loaded;
  65470. this.total = total;
  65471. }
  65472. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  65473. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  65474. };
  65475. return SceneLoaderProgressEvent;
  65476. }());
  65477. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  65478. var SceneLoader = /** @class */ (function () {
  65479. function SceneLoader() {
  65480. }
  65481. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  65482. get: function () {
  65483. return 0;
  65484. },
  65485. enumerable: true,
  65486. configurable: true
  65487. });
  65488. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  65489. get: function () {
  65490. return 1;
  65491. },
  65492. enumerable: true,
  65493. configurable: true
  65494. });
  65495. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  65496. get: function () {
  65497. return 2;
  65498. },
  65499. enumerable: true,
  65500. configurable: true
  65501. });
  65502. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  65503. get: function () {
  65504. return 3;
  65505. },
  65506. enumerable: true,
  65507. configurable: true
  65508. });
  65509. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  65510. get: function () {
  65511. return SceneLoader._ForceFullSceneLoadingForIncremental;
  65512. },
  65513. set: function (value) {
  65514. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  65515. },
  65516. enumerable: true,
  65517. configurable: true
  65518. });
  65519. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  65520. get: function () {
  65521. return SceneLoader._ShowLoadingScreen;
  65522. },
  65523. set: function (value) {
  65524. SceneLoader._ShowLoadingScreen = value;
  65525. },
  65526. enumerable: true,
  65527. configurable: true
  65528. });
  65529. Object.defineProperty(SceneLoader, "loggingLevel", {
  65530. get: function () {
  65531. return SceneLoader._loggingLevel;
  65532. },
  65533. set: function (value) {
  65534. SceneLoader._loggingLevel = value;
  65535. },
  65536. enumerable: true,
  65537. configurable: true
  65538. });
  65539. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  65540. get: function () {
  65541. return SceneLoader._CleanBoneMatrixWeights;
  65542. },
  65543. set: function (value) {
  65544. SceneLoader._CleanBoneMatrixWeights = value;
  65545. },
  65546. enumerable: true,
  65547. configurable: true
  65548. });
  65549. SceneLoader._getDefaultPlugin = function () {
  65550. return SceneLoader._registeredPlugins[".babylon"];
  65551. };
  65552. SceneLoader._getPluginForExtension = function (extension) {
  65553. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  65554. if (registeredPlugin) {
  65555. return registeredPlugin;
  65556. }
  65557. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  65558. return SceneLoader._getDefaultPlugin();
  65559. };
  65560. SceneLoader._getPluginForDirectLoad = function (data) {
  65561. for (var extension in SceneLoader._registeredPlugins) {
  65562. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  65563. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  65564. return SceneLoader._registeredPlugins[extension];
  65565. }
  65566. }
  65567. return SceneLoader._getDefaultPlugin();
  65568. };
  65569. SceneLoader._getPluginForFilename = function (sceneFilename) {
  65570. if (sceneFilename.name) {
  65571. sceneFilename = sceneFilename.name;
  65572. }
  65573. var queryStringPosition = sceneFilename.indexOf("?");
  65574. if (queryStringPosition !== -1) {
  65575. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  65576. }
  65577. var dotPosition = sceneFilename.lastIndexOf(".");
  65578. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  65579. return SceneLoader._getPluginForExtension(extension);
  65580. };
  65581. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  65582. SceneLoader._getDirectLoad = function (sceneFilename) {
  65583. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  65584. return sceneFilename.substr(5);
  65585. }
  65586. return null;
  65587. };
  65588. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  65589. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  65590. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  65591. var plugin;
  65592. if (registeredPlugin.plugin.createPlugin) {
  65593. plugin = registeredPlugin.plugin.createPlugin();
  65594. }
  65595. else {
  65596. plugin = registeredPlugin.plugin;
  65597. }
  65598. var useArrayBuffer = registeredPlugin.isBinary;
  65599. var database;
  65600. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  65601. var dataCallback = function (data, responseURL) {
  65602. if (scene.isDisposed) {
  65603. onError("Scene has been disposed");
  65604. return;
  65605. }
  65606. scene.database = database;
  65607. onSuccess(plugin, data, responseURL);
  65608. };
  65609. var request = null;
  65610. var pluginDisposed = false;
  65611. var onDisposeObservable = plugin.onDisposeObservable;
  65612. if (onDisposeObservable) {
  65613. onDisposeObservable.add(function () {
  65614. pluginDisposed = true;
  65615. if (request) {
  65616. request.abort();
  65617. request = null;
  65618. }
  65619. onDispose();
  65620. });
  65621. }
  65622. var manifestChecked = function () {
  65623. if (pluginDisposed) {
  65624. return;
  65625. }
  65626. var url = rootUrl + sceneFilename;
  65627. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  65628. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  65629. } : undefined, database, useArrayBuffer, function (request, exception) {
  65630. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  65631. });
  65632. };
  65633. if (directLoad) {
  65634. dataCallback(directLoad);
  65635. return plugin;
  65636. }
  65637. if (rootUrl.indexOf("file:") === -1) {
  65638. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  65639. if (canUseOfflineSupport) {
  65640. // Also check for exceptions
  65641. var exceptionFound = false;
  65642. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  65643. var regex = _a[_i];
  65644. if (regex.test(rootUrl + sceneFilename)) {
  65645. exceptionFound = true;
  65646. break;
  65647. }
  65648. }
  65649. canUseOfflineSupport = !exceptionFound;
  65650. }
  65651. if (canUseOfflineSupport) {
  65652. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  65653. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  65654. }
  65655. else {
  65656. manifestChecked();
  65657. }
  65658. }
  65659. else {
  65660. var fileOrString = sceneFilename;
  65661. if (fileOrString.name) {
  65662. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  65663. }
  65664. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  65665. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  65666. }
  65667. else {
  65668. onError("Unable to find file named " + sceneFilename);
  65669. }
  65670. }
  65671. return plugin;
  65672. };
  65673. // Public functions
  65674. SceneLoader.GetPluginForExtension = function (extension) {
  65675. return SceneLoader._getPluginForExtension(extension).plugin;
  65676. };
  65677. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  65678. return !!SceneLoader._registeredPlugins[extension];
  65679. };
  65680. SceneLoader.RegisterPlugin = function (plugin) {
  65681. if (typeof plugin.extensions === "string") {
  65682. var extension = plugin.extensions;
  65683. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65684. plugin: plugin,
  65685. isBinary: false
  65686. };
  65687. }
  65688. else {
  65689. var extensions = plugin.extensions;
  65690. Object.keys(extensions).forEach(function (extension) {
  65691. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65692. plugin: plugin,
  65693. isBinary: extensions[extension].isBinary
  65694. };
  65695. });
  65696. }
  65697. };
  65698. /**
  65699. * Import meshes into a scene
  65700. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65701. * @param rootUrl a string that defines the root url for scene and resources
  65702. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65703. * @param scene the instance of BABYLON.Scene to append to
  65704. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  65705. * @param onProgress a callback with a progress event for each file being loaded
  65706. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65707. * @param pluginExtension the extension used to determine the plugin
  65708. * @returns The loaded plugin
  65709. */
  65710. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65711. if (onSuccess === void 0) { onSuccess = null; }
  65712. if (onProgress === void 0) { onProgress = null; }
  65713. if (onError === void 0) { onError = null; }
  65714. if (pluginExtension === void 0) { pluginExtension = null; }
  65715. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65716. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65717. return null;
  65718. }
  65719. var loadingToken = {};
  65720. scene._addPendingData(loadingToken);
  65721. var disposeHandler = function () {
  65722. scene._removePendingData(loadingToken);
  65723. };
  65724. var errorHandler = function (message, exception) {
  65725. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  65726. if (onError) {
  65727. onError(scene, errorMessage, exception);
  65728. }
  65729. else {
  65730. BABYLON.Tools.Error(errorMessage);
  65731. // should the exception be thrown?
  65732. }
  65733. disposeHandler();
  65734. };
  65735. var progressHandler = onProgress ? function (event) {
  65736. try {
  65737. onProgress(event);
  65738. }
  65739. catch (e) {
  65740. errorHandler("Error in onProgress callback", e);
  65741. }
  65742. } : undefined;
  65743. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  65744. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  65745. if (onSuccess) {
  65746. try {
  65747. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  65748. }
  65749. catch (e) {
  65750. errorHandler("Error in onSuccess callback", e);
  65751. }
  65752. }
  65753. scene._removePendingData(loadingToken);
  65754. };
  65755. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65756. if (plugin.rewriteRootURL) {
  65757. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  65758. }
  65759. if (sceneFilename === "") {
  65760. if (sceneFilename === "") {
  65761. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65762. }
  65763. }
  65764. if (plugin.importMesh) {
  65765. var syncedPlugin = plugin;
  65766. var meshes = new Array();
  65767. var particleSystems = new Array();
  65768. var skeletons = new Array();
  65769. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  65770. return;
  65771. }
  65772. scene.loadingPluginName = plugin.name;
  65773. successHandler(meshes, particleSystems, skeletons, []);
  65774. }
  65775. else {
  65776. var asyncedPlugin = plugin;
  65777. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  65778. scene.loadingPluginName = plugin.name;
  65779. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  65780. }).catch(function (error) {
  65781. errorHandler(error.message, error);
  65782. });
  65783. }
  65784. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65785. };
  65786. /**
  65787. * Import meshes into a scene
  65788. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65789. * @param rootUrl a string that defines the root url for scene and resources
  65790. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65791. * @param scene the instance of BABYLON.Scene to append to
  65792. * @param onProgress a callback with a progress event for each file being loaded
  65793. * @param pluginExtension the extension used to determine the plugin
  65794. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  65795. */
  65796. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65797. if (onProgress === void 0) { onProgress = null; }
  65798. if (pluginExtension === void 0) { pluginExtension = null; }
  65799. return new Promise(function (resolve, reject) {
  65800. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  65801. resolve({
  65802. meshes: meshes,
  65803. particleSystems: particleSystems,
  65804. skeletons: skeletons,
  65805. animationGroups: animationGroups
  65806. });
  65807. }, onProgress, function (scene, message, exception) {
  65808. reject(exception || new Error(message));
  65809. });
  65810. });
  65811. };
  65812. /**
  65813. * Load a scene
  65814. * @param rootUrl a string that defines the root url for scene and resources
  65815. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65816. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65817. * @param onSuccess a callback with the scene when import succeeds
  65818. * @param onProgress a callback with a progress event for each file being loaded
  65819. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65820. * @param pluginExtension the extension used to determine the plugin
  65821. * @returns The loaded plugin
  65822. */
  65823. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  65824. if (onSuccess === void 0) { onSuccess = null; }
  65825. if (onProgress === void 0) { onProgress = null; }
  65826. if (onError === void 0) { onError = null; }
  65827. if (pluginExtension === void 0) { pluginExtension = null; }
  65828. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  65829. };
  65830. /**
  65831. * Load a scene
  65832. * @param rootUrl a string that defines the root url for scene and resources
  65833. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65834. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65835. * @param onProgress a callback with a progress event for each file being loaded
  65836. * @param pluginExtension the extension used to determine the plugin
  65837. * @returns The loaded scene
  65838. */
  65839. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  65840. if (onProgress === void 0) { onProgress = null; }
  65841. if (pluginExtension === void 0) { pluginExtension = null; }
  65842. return new Promise(function (resolve, reject) {
  65843. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  65844. resolve(scene);
  65845. }, onProgress, function (scene, message, exception) {
  65846. reject(exception || new Error(message));
  65847. }, pluginExtension);
  65848. });
  65849. };
  65850. /**
  65851. * Append a scene
  65852. * @param rootUrl a string that defines the root url for scene and resources
  65853. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65854. * @param scene is the instance of BABYLON.Scene to append to
  65855. * @param onSuccess a callback with the scene when import succeeds
  65856. * @param onProgress a callback with a progress event for each file being loaded
  65857. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65858. * @param pluginExtension the extension used to determine the plugin
  65859. * @returns The loaded plugin
  65860. */
  65861. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65862. if (onSuccess === void 0) { onSuccess = null; }
  65863. if (onProgress === void 0) { onProgress = null; }
  65864. if (onError === void 0) { onError = null; }
  65865. if (pluginExtension === void 0) { pluginExtension = null; }
  65866. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65867. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65868. return null;
  65869. }
  65870. if (SceneLoader.ShowLoadingScreen) {
  65871. scene.getEngine().displayLoadingUI();
  65872. }
  65873. var loadingToken = {};
  65874. scene._addPendingData(loadingToken);
  65875. var disposeHandler = function () {
  65876. scene._removePendingData(loadingToken);
  65877. scene.getEngine().hideLoadingUI();
  65878. };
  65879. var errorHandler = function (message, exception) {
  65880. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65881. if (onError) {
  65882. onError(scene, errorMessage, exception);
  65883. }
  65884. else {
  65885. BABYLON.Tools.Error(errorMessage);
  65886. // should the exception be thrown?
  65887. }
  65888. disposeHandler();
  65889. };
  65890. var progressHandler = onProgress ? function (event) {
  65891. try {
  65892. onProgress(event);
  65893. }
  65894. catch (e) {
  65895. errorHandler("Error in onProgress callback", e);
  65896. }
  65897. } : undefined;
  65898. var successHandler = function () {
  65899. if (onSuccess) {
  65900. try {
  65901. onSuccess(scene);
  65902. }
  65903. catch (e) {
  65904. errorHandler("Error in onSuccess callback", e);
  65905. }
  65906. }
  65907. scene._removePendingData(loadingToken);
  65908. };
  65909. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65910. if (sceneFilename === "") {
  65911. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65912. }
  65913. if (plugin.load) {
  65914. var syncedPlugin = plugin;
  65915. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  65916. return;
  65917. }
  65918. scene.loadingPluginName = plugin.name;
  65919. successHandler();
  65920. }
  65921. else {
  65922. var asyncedPlugin = plugin;
  65923. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  65924. scene.loadingPluginName = plugin.name;
  65925. successHandler();
  65926. }).catch(function (error) {
  65927. errorHandler(error.message, error);
  65928. });
  65929. }
  65930. if (SceneLoader.ShowLoadingScreen) {
  65931. scene.executeWhenReady(function () {
  65932. scene.getEngine().hideLoadingUI();
  65933. });
  65934. }
  65935. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65936. };
  65937. /**
  65938. * Append a scene
  65939. * @param rootUrl a string that defines the root url for scene and resources
  65940. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65941. * @param scene is the instance of BABYLON.Scene to append to
  65942. * @param onProgress a callback with a progress event for each file being loaded
  65943. * @param pluginExtension the extension used to determine the plugin
  65944. * @returns The given scene
  65945. */
  65946. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65947. if (onProgress === void 0) { onProgress = null; }
  65948. if (pluginExtension === void 0) { pluginExtension = null; }
  65949. return new Promise(function (resolve, reject) {
  65950. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  65951. resolve(scene);
  65952. }, onProgress, function (scene, message, exception) {
  65953. reject(exception || new Error(message));
  65954. }, pluginExtension);
  65955. });
  65956. };
  65957. /**
  65958. * Load a scene into an asset container
  65959. * @param rootUrl a string that defines the root url for scene and resources
  65960. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65961. * @param scene is the instance of BABYLON.Scene to append to
  65962. * @param onSuccess a callback with the scene when import succeeds
  65963. * @param onProgress a callback with a progress event for each file being loaded
  65964. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65965. * @param pluginExtension the extension used to determine the plugin
  65966. * @returns The loaded plugin
  65967. */
  65968. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65969. if (onSuccess === void 0) { onSuccess = null; }
  65970. if (onProgress === void 0) { onProgress = null; }
  65971. if (onError === void 0) { onError = null; }
  65972. if (pluginExtension === void 0) { pluginExtension = null; }
  65973. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65974. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65975. return null;
  65976. }
  65977. var loadingToken = {};
  65978. scene._addPendingData(loadingToken);
  65979. var disposeHandler = function () {
  65980. scene._removePendingData(loadingToken);
  65981. };
  65982. var errorHandler = function (message, exception) {
  65983. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65984. if (onError) {
  65985. onError(scene, errorMessage, exception);
  65986. }
  65987. else {
  65988. BABYLON.Tools.Error(errorMessage);
  65989. // should the exception be thrown?
  65990. }
  65991. disposeHandler();
  65992. };
  65993. var progressHandler = onProgress ? function (event) {
  65994. try {
  65995. onProgress(event);
  65996. }
  65997. catch (e) {
  65998. errorHandler("Error in onProgress callback", e);
  65999. }
  66000. } : undefined;
  66001. var successHandler = function (assets) {
  66002. if (onSuccess) {
  66003. try {
  66004. onSuccess(assets);
  66005. }
  66006. catch (e) {
  66007. errorHandler("Error in onSuccess callback", e);
  66008. }
  66009. }
  66010. scene._removePendingData(loadingToken);
  66011. };
  66012. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66013. if (plugin.loadAssetContainer) {
  66014. var syncedPlugin = plugin;
  66015. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66016. if (!assetContainer) {
  66017. return;
  66018. }
  66019. scene.loadingPluginName = plugin.name;
  66020. successHandler(assetContainer);
  66021. }
  66022. else if (plugin.loadAssetContainerAsync) {
  66023. var asyncedPlugin = plugin;
  66024. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66025. scene.loadingPluginName = plugin.name;
  66026. successHandler(assetContainer);
  66027. }).catch(function (error) {
  66028. errorHandler(error.message, error);
  66029. });
  66030. }
  66031. else {
  66032. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66033. }
  66034. if (SceneLoader.ShowLoadingScreen) {
  66035. scene.executeWhenReady(function () {
  66036. scene.getEngine().hideLoadingUI();
  66037. });
  66038. }
  66039. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66040. };
  66041. /**
  66042. * Load a scene into an asset container
  66043. * @param rootUrl a string that defines the root url for scene and resources
  66044. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66045. * @param scene is the instance of BABYLON.Scene to append to
  66046. * @param onProgress a callback with a progress event for each file being loaded
  66047. * @param pluginExtension the extension used to determine the plugin
  66048. * @returns The loaded asset container
  66049. */
  66050. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66051. if (onProgress === void 0) { onProgress = null; }
  66052. if (pluginExtension === void 0) { pluginExtension = null; }
  66053. return new Promise(function (resolve, reject) {
  66054. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66055. resolve(assetContainer);
  66056. }, onProgress, function (scene, message, exception) {
  66057. reject(exception || new Error(message));
  66058. }, pluginExtension);
  66059. });
  66060. };
  66061. // Flags
  66062. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66063. SceneLoader._ShowLoadingScreen = true;
  66064. SceneLoader._CleanBoneMatrixWeights = false;
  66065. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66066. // Members
  66067. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66068. SceneLoader._registeredPlugins = {};
  66069. return SceneLoader;
  66070. }());
  66071. BABYLON.SceneLoader = SceneLoader;
  66072. ;
  66073. })(BABYLON || (BABYLON = {}));
  66074. //# sourceMappingURL=babylon.sceneLoader.js.map
  66075. "use strict";
  66076. var BABYLON;
  66077. (function (BABYLON) {
  66078. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66079. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66080. var parsedMaterial = parsedData.materials[index];
  66081. if (parsedMaterial.id === id) {
  66082. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66083. }
  66084. }
  66085. return null;
  66086. };
  66087. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66088. for (var i in names) {
  66089. if (mesh.name === names[i]) {
  66090. hierarchyIds.push(mesh.id);
  66091. return true;
  66092. }
  66093. }
  66094. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66095. hierarchyIds.push(mesh.id);
  66096. return true;
  66097. }
  66098. return false;
  66099. };
  66100. var logOperation = function (operation, producer) {
  66101. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66102. };
  66103. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66104. if (addToScene === void 0) { addToScene = false; }
  66105. var container = new BABYLON.AssetContainer(scene);
  66106. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66107. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66108. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66109. // and avoid problems with multiple concurrent .babylon loads.
  66110. var log = "importScene has failed JSON parse";
  66111. try {
  66112. var parsedData = JSON.parse(data);
  66113. log = "";
  66114. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66115. var index;
  66116. var cache;
  66117. // Lights
  66118. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66119. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66120. var parsedLight = parsedData.lights[index];
  66121. var light = BABYLON.Light.Parse(parsedLight, scene);
  66122. if (light) {
  66123. container.lights.push(light);
  66124. log += (index === 0 ? "\n\tLights:" : "");
  66125. log += "\n\t\t" + light.toString(fullDetails);
  66126. }
  66127. }
  66128. }
  66129. // Animations
  66130. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66131. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66132. var parsedAnimation = parsedData.animations[index];
  66133. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66134. scene.animations.push(animation);
  66135. container.animations.push(animation);
  66136. log += (index === 0 ? "\n\tAnimations:" : "");
  66137. log += "\n\t\t" + animation.toString(fullDetails);
  66138. }
  66139. }
  66140. // Materials
  66141. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66142. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66143. var parsedMaterial = parsedData.materials[index];
  66144. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66145. container.materials.push(mat);
  66146. log += (index === 0 ? "\n\tMaterials:" : "");
  66147. log += "\n\t\t" + mat.toString(fullDetails);
  66148. }
  66149. }
  66150. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66151. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66152. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66153. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66154. container.multiMaterials.push(mmat);
  66155. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66156. log += "\n\t\t" + mmat.toString(fullDetails);
  66157. }
  66158. }
  66159. // Morph targets
  66160. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66161. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66162. var managerData = _a[_i];
  66163. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66164. }
  66165. }
  66166. // Skeletons
  66167. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66168. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66169. var parsedSkeleton = parsedData.skeletons[index];
  66170. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66171. container.skeletons.push(skeleton);
  66172. log += (index === 0 ? "\n\tSkeletons:" : "");
  66173. log += "\n\t\t" + skeleton.toString(fullDetails);
  66174. }
  66175. }
  66176. // Geometries
  66177. var geometries = parsedData.geometries;
  66178. if (geometries !== undefined && geometries !== null) {
  66179. var addedGeometry = new Array();
  66180. // Boxes
  66181. var boxes = geometries.boxes;
  66182. if (boxes !== undefined && boxes !== null) {
  66183. for (index = 0, cache = boxes.length; index < cache; index++) {
  66184. var parsedBox = boxes[index];
  66185. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  66186. }
  66187. }
  66188. // Spheres
  66189. var spheres = geometries.spheres;
  66190. if (spheres !== undefined && spheres !== null) {
  66191. for (index = 0, cache = spheres.length; index < cache; index++) {
  66192. var parsedSphere = spheres[index];
  66193. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  66194. }
  66195. }
  66196. // Cylinders
  66197. var cylinders = geometries.cylinders;
  66198. if (cylinders !== undefined && cylinders !== null) {
  66199. for (index = 0, cache = cylinders.length; index < cache; index++) {
  66200. var parsedCylinder = cylinders[index];
  66201. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  66202. }
  66203. }
  66204. // Toruses
  66205. var toruses = geometries.toruses;
  66206. if (toruses !== undefined && toruses !== null) {
  66207. for (index = 0, cache = toruses.length; index < cache; index++) {
  66208. var parsedTorus = toruses[index];
  66209. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  66210. }
  66211. }
  66212. // Grounds
  66213. var grounds = geometries.grounds;
  66214. if (grounds !== undefined && grounds !== null) {
  66215. for (index = 0, cache = grounds.length; index < cache; index++) {
  66216. var parsedGround = grounds[index];
  66217. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  66218. }
  66219. }
  66220. // Planes
  66221. var planes = geometries.planes;
  66222. if (planes !== undefined && planes !== null) {
  66223. for (index = 0, cache = planes.length; index < cache; index++) {
  66224. var parsedPlane = planes[index];
  66225. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  66226. }
  66227. }
  66228. // TorusKnots
  66229. var torusKnots = geometries.torusKnots;
  66230. if (torusKnots !== undefined && torusKnots !== null) {
  66231. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  66232. var parsedTorusKnot = torusKnots[index];
  66233. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  66234. }
  66235. }
  66236. // VertexData
  66237. var vertexData = geometries.vertexData;
  66238. if (vertexData !== undefined && vertexData !== null) {
  66239. for (index = 0, cache = vertexData.length; index < cache; index++) {
  66240. var parsedVertexData = vertexData[index];
  66241. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66242. }
  66243. }
  66244. addedGeometry.forEach(function (g) {
  66245. if (g) {
  66246. container.geometries.push(g);
  66247. }
  66248. });
  66249. }
  66250. // Transform nodes
  66251. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66252. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66253. var parsedTransformNode = parsedData.transformNodes[index];
  66254. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66255. container.transformNodes.push(node);
  66256. }
  66257. }
  66258. // Meshes
  66259. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66260. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66261. var parsedMesh = parsedData.meshes[index];
  66262. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66263. container.meshes.push(mesh);
  66264. log += (index === 0 ? "\n\tMeshes:" : "");
  66265. log += "\n\t\t" + mesh.toString(fullDetails);
  66266. }
  66267. }
  66268. // Cameras
  66269. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  66270. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  66271. var parsedCamera = parsedData.cameras[index];
  66272. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  66273. container.cameras.push(camera);
  66274. log += (index === 0 ? "\n\tCameras:" : "");
  66275. log += "\n\t\t" + camera.toString(fullDetails);
  66276. }
  66277. }
  66278. // Browsing all the graph to connect the dots
  66279. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  66280. var camera = scene.cameras[index];
  66281. if (camera._waitingParentId) {
  66282. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  66283. camera._waitingParentId = null;
  66284. }
  66285. }
  66286. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66287. var light_1 = scene.lights[index];
  66288. if (light_1 && light_1._waitingParentId) {
  66289. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  66290. light_1._waitingParentId = null;
  66291. }
  66292. }
  66293. // Sounds
  66294. // TODO: add sound
  66295. var loadedSounds = [];
  66296. var loadedSound;
  66297. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66298. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66299. var parsedSound = parsedData.sounds[index];
  66300. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66301. if (!parsedSound.url)
  66302. parsedSound.url = parsedSound.name;
  66303. if (!loadedSounds[parsedSound.url]) {
  66304. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66305. loadedSounds[parsedSound.url] = loadedSound;
  66306. container.sounds.push(loadedSound);
  66307. }
  66308. else {
  66309. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66310. }
  66311. }
  66312. else {
  66313. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66314. }
  66315. }
  66316. }
  66317. loadedSounds = [];
  66318. // Connect parents & children and parse actions
  66319. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  66320. var transformNode = scene.transformNodes[index];
  66321. if (transformNode._waitingParentId) {
  66322. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  66323. transformNode._waitingParentId = null;
  66324. }
  66325. }
  66326. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66327. var mesh = scene.meshes[index];
  66328. if (mesh._waitingParentId) {
  66329. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  66330. mesh._waitingParentId = null;
  66331. }
  66332. if (mesh._waitingActions) {
  66333. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  66334. mesh._waitingActions = null;
  66335. }
  66336. }
  66337. // freeze world matrix application
  66338. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66339. var currentMesh = scene.meshes[index];
  66340. if (currentMesh._waitingFreezeWorldMatrix) {
  66341. currentMesh.freezeWorldMatrix();
  66342. currentMesh._waitingFreezeWorldMatrix = null;
  66343. }
  66344. else {
  66345. currentMesh.computeWorldMatrix(true);
  66346. }
  66347. }
  66348. // Particles Systems
  66349. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66350. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66351. var parsedParticleSystem = parsedData.particleSystems[index];
  66352. if (parsedParticleSystem.activeParticleCount) {
  66353. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66354. container.particleSystems.push(ps);
  66355. }
  66356. else {
  66357. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66358. container.particleSystems.push(ps);
  66359. }
  66360. }
  66361. }
  66362. // Lens flares
  66363. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  66364. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  66365. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  66366. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  66367. container.lensFlareSystems.push(lf);
  66368. }
  66369. }
  66370. // Shadows
  66371. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  66372. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  66373. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  66374. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  66375. container.shadowGenerators.push(sg);
  66376. }
  66377. }
  66378. // Lights exclusions / inclusions
  66379. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66380. var light_2 = scene.lights[index];
  66381. // Excluded check
  66382. if (light_2._excludedMeshesIds.length > 0) {
  66383. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  66384. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  66385. if (excludedMesh) {
  66386. light_2.excludedMeshes.push(excludedMesh);
  66387. }
  66388. }
  66389. light_2._excludedMeshesIds = [];
  66390. }
  66391. // Included check
  66392. if (light_2._includedOnlyMeshesIds.length > 0) {
  66393. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  66394. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  66395. if (includedOnlyMesh) {
  66396. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  66397. }
  66398. }
  66399. light_2._includedOnlyMeshesIds = [];
  66400. }
  66401. }
  66402. // Effect layers
  66403. if (parsedData.effectLayers) {
  66404. for (index = 0; index < parsedData.effectLayers.length; index++) {
  66405. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  66406. container.effectLayers.push(effectLayer);
  66407. }
  66408. }
  66409. // Actions (scene)
  66410. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  66411. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  66412. }
  66413. if (!addToScene) {
  66414. container.removeAllFromScene();
  66415. }
  66416. }
  66417. catch (err) {
  66418. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  66419. if (onError) {
  66420. onError(msg, err);
  66421. }
  66422. else {
  66423. BABYLON.Tools.Log(msg);
  66424. throw err;
  66425. }
  66426. }
  66427. finally {
  66428. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66429. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66430. }
  66431. }
  66432. return container;
  66433. };
  66434. BABYLON.SceneLoader.RegisterPlugin({
  66435. name: "babylon.js",
  66436. extensions: ".babylon",
  66437. canDirectLoad: function (data) {
  66438. if (data.indexOf("babylon") !== -1) {
  66439. return true;
  66440. }
  66441. return false;
  66442. },
  66443. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  66444. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66445. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66446. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66447. // and avoid problems with multiple concurrent .babylon loads.
  66448. var log = "importMesh has failed JSON parse";
  66449. try {
  66450. var parsedData = JSON.parse(data);
  66451. log = "";
  66452. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66453. if (!meshesNames) {
  66454. meshesNames = null;
  66455. }
  66456. else if (!Array.isArray(meshesNames)) {
  66457. meshesNames = [meshesNames];
  66458. }
  66459. var hierarchyIds = new Array();
  66460. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66461. var loadedSkeletonsIds = [];
  66462. var loadedMaterialsIds = [];
  66463. var index;
  66464. var cache;
  66465. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66466. var parsedMesh = parsedData.meshes[index];
  66467. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  66468. if (meshesNames !== null) {
  66469. // Remove found mesh name from list.
  66470. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  66471. }
  66472. //Geometry?
  66473. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  66474. //does the file contain geometries?
  66475. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  66476. //find the correct geometry and add it to the scene
  66477. var found = false;
  66478. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  66479. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  66480. return;
  66481. }
  66482. else {
  66483. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  66484. if (parsedGeometryData.id === parsedMesh.geometryId) {
  66485. switch (geometryType) {
  66486. case "boxes":
  66487. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  66488. break;
  66489. case "spheres":
  66490. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  66491. break;
  66492. case "cylinders":
  66493. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  66494. break;
  66495. case "toruses":
  66496. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  66497. break;
  66498. case "grounds":
  66499. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  66500. break;
  66501. case "planes":
  66502. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  66503. break;
  66504. case "torusKnots":
  66505. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  66506. break;
  66507. case "vertexData":
  66508. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  66509. break;
  66510. }
  66511. found = true;
  66512. }
  66513. });
  66514. }
  66515. });
  66516. if (found === false) {
  66517. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  66518. }
  66519. }
  66520. }
  66521. // Material ?
  66522. if (parsedMesh.materialId) {
  66523. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  66524. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66525. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  66526. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  66527. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  66528. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  66529. var subMatId = parsedMultiMaterial.materials[matIndex];
  66530. loadedMaterialsIds.push(subMatId);
  66531. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  66532. if (mat) {
  66533. log += "\n\tMaterial " + mat.toString(fullDetails);
  66534. }
  66535. }
  66536. loadedMaterialsIds.push(parsedMultiMaterial.id);
  66537. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66538. if (mmat) {
  66539. materialFound = true;
  66540. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  66541. }
  66542. break;
  66543. }
  66544. }
  66545. }
  66546. if (materialFound === false) {
  66547. loadedMaterialsIds.push(parsedMesh.materialId);
  66548. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  66549. if (!mat) {
  66550. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  66551. }
  66552. else {
  66553. log += "\n\tMaterial " + mat.toString(fullDetails);
  66554. }
  66555. }
  66556. }
  66557. // Skeleton ?
  66558. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66559. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  66560. if (skeletonAlreadyLoaded === false) {
  66561. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  66562. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  66563. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  66564. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66565. skeletons.push(skeleton);
  66566. loadedSkeletonsIds.push(parsedSkeleton.id);
  66567. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  66568. }
  66569. }
  66570. }
  66571. }
  66572. // Morph targets ?
  66573. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66574. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66575. var managerData = _a[_i];
  66576. BABYLON.MorphTargetManager.Parse(managerData, scene);
  66577. }
  66578. }
  66579. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66580. meshes.push(mesh);
  66581. log += "\n\tMesh " + mesh.toString(fullDetails);
  66582. }
  66583. }
  66584. // Connecting parents
  66585. var currentMesh;
  66586. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66587. currentMesh = scene.meshes[index];
  66588. if (currentMesh._waitingParentId) {
  66589. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  66590. currentMesh._waitingParentId = null;
  66591. }
  66592. }
  66593. // freeze and compute world matrix application
  66594. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66595. currentMesh = scene.meshes[index];
  66596. if (currentMesh._waitingFreezeWorldMatrix) {
  66597. currentMesh.freezeWorldMatrix();
  66598. currentMesh._waitingFreezeWorldMatrix = null;
  66599. }
  66600. else {
  66601. currentMesh.computeWorldMatrix(true);
  66602. }
  66603. }
  66604. }
  66605. // Particles
  66606. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66607. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66608. var parsedParticleSystem = parsedData.particleSystems[index];
  66609. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  66610. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  66611. }
  66612. }
  66613. }
  66614. return true;
  66615. }
  66616. catch (err) {
  66617. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  66618. if (onError) {
  66619. onError(msg, err);
  66620. }
  66621. else {
  66622. BABYLON.Tools.Log(msg);
  66623. throw err;
  66624. }
  66625. }
  66626. finally {
  66627. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66628. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66629. }
  66630. }
  66631. return false;
  66632. },
  66633. load: function (scene, data, rootUrl, onError) {
  66634. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66635. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66636. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66637. // and avoid problems with multiple concurrent .babylon loads.
  66638. var log = "importScene has failed JSON parse";
  66639. try {
  66640. var parsedData = JSON.parse(data);
  66641. log = "";
  66642. // Scene
  66643. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  66644. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  66645. }
  66646. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  66647. scene.autoClear = parsedData.autoClear;
  66648. }
  66649. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  66650. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  66651. }
  66652. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  66653. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  66654. }
  66655. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  66656. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  66657. }
  66658. // Fog
  66659. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  66660. scene.fogMode = parsedData.fogMode;
  66661. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  66662. scene.fogStart = parsedData.fogStart;
  66663. scene.fogEnd = parsedData.fogEnd;
  66664. scene.fogDensity = parsedData.fogDensity;
  66665. log += "\tFog mode for scene: ";
  66666. switch (scene.fogMode) {
  66667. // getters not compiling, so using hardcoded
  66668. case 1:
  66669. log += "exp\n";
  66670. break;
  66671. case 2:
  66672. log += "exp2\n";
  66673. break;
  66674. case 3:
  66675. log += "linear\n";
  66676. break;
  66677. }
  66678. }
  66679. //Physics
  66680. if (parsedData.physicsEnabled) {
  66681. var physicsPlugin;
  66682. if (parsedData.physicsEngine === "cannon") {
  66683. physicsPlugin = new BABYLON.CannonJSPlugin();
  66684. }
  66685. else if (parsedData.physicsEngine === "oimo") {
  66686. physicsPlugin = new BABYLON.OimoJSPlugin();
  66687. }
  66688. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  66689. //else - default engine, which is currently oimo
  66690. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  66691. scene.enablePhysics(physicsGravity, physicsPlugin);
  66692. }
  66693. // Metadata
  66694. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  66695. scene.metadata = parsedData.metadata;
  66696. }
  66697. //collisions, if defined. otherwise, default is true
  66698. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  66699. scene.collisionsEnabled = parsedData.collisionsEnabled;
  66700. }
  66701. scene.workerCollisions = !!parsedData.workerCollisions;
  66702. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  66703. if (!container) {
  66704. return false;
  66705. }
  66706. if (parsedData.autoAnimate) {
  66707. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  66708. }
  66709. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  66710. scene.setActiveCameraByID(parsedData.activeCameraID);
  66711. }
  66712. // Environment texture
  66713. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  66714. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  66715. if (parsedData.createDefaultSkybox === true) {
  66716. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  66717. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  66718. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  66719. }
  66720. }
  66721. // Finish
  66722. return true;
  66723. }
  66724. catch (err) {
  66725. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  66726. if (onError) {
  66727. onError(msg, err);
  66728. }
  66729. else {
  66730. BABYLON.Tools.Log(msg);
  66731. throw err;
  66732. }
  66733. }
  66734. finally {
  66735. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66736. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66737. }
  66738. }
  66739. return false;
  66740. },
  66741. loadAssetContainer: function (scene, data, rootUrl, onError) {
  66742. var container = loadAssetContainer(scene, data, rootUrl, onError);
  66743. return container;
  66744. }
  66745. });
  66746. })(BABYLON || (BABYLON = {}));
  66747. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  66748. "use strict";
  66749. var BABYLON;
  66750. (function (BABYLON) {
  66751. var FilesInput = /** @class */ (function () {
  66752. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  66753. this.onProcessFileCallback = function () { return true; };
  66754. this._engine = engine;
  66755. this._currentScene = scene;
  66756. this._sceneLoadedCallback = sceneLoadedCallback;
  66757. this._progressCallback = progressCallback;
  66758. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  66759. this._textureLoadingCallback = textureLoadingCallback;
  66760. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  66761. this._onReloadCallback = onReloadCallback;
  66762. this._errorCallback = errorCallback;
  66763. }
  66764. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  66765. var _this = this;
  66766. if (elementToMonitor) {
  66767. this._elementToMonitor = elementToMonitor;
  66768. this._dragEnterHandler = function (e) { _this.drag(e); };
  66769. this._dragOverHandler = function (e) { _this.drag(e); };
  66770. this._dropHandler = function (e) { _this.drop(e); };
  66771. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  66772. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  66773. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  66774. }
  66775. };
  66776. FilesInput.prototype.dispose = function () {
  66777. if (!this._elementToMonitor) {
  66778. return;
  66779. }
  66780. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  66781. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  66782. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  66783. };
  66784. FilesInput.prototype.renderFunction = function () {
  66785. if (this._additionalRenderLoopLogicCallback) {
  66786. this._additionalRenderLoopLogicCallback();
  66787. }
  66788. if (this._currentScene) {
  66789. if (this._textureLoadingCallback) {
  66790. var remaining = this._currentScene.getWaitingItemsCount();
  66791. if (remaining > 0) {
  66792. this._textureLoadingCallback(remaining);
  66793. }
  66794. }
  66795. this._currentScene.render();
  66796. }
  66797. };
  66798. FilesInput.prototype.drag = function (e) {
  66799. e.stopPropagation();
  66800. e.preventDefault();
  66801. };
  66802. FilesInput.prototype.drop = function (eventDrop) {
  66803. eventDrop.stopPropagation();
  66804. eventDrop.preventDefault();
  66805. this.loadFiles(eventDrop);
  66806. };
  66807. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  66808. var _this = this;
  66809. var reader = folder.createReader();
  66810. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  66811. reader.readEntries(function (entries) {
  66812. remaining.count += entries.length;
  66813. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  66814. var entry = entries_1[_i];
  66815. if (entry.isFile) {
  66816. entry.file(function (file) {
  66817. file.correctName = relativePath + file.name;
  66818. files.push(file);
  66819. if (--remaining.count === 0) {
  66820. callback();
  66821. }
  66822. });
  66823. }
  66824. else if (entry.isDirectory) {
  66825. _this._traverseFolder(entry, files, remaining, callback);
  66826. }
  66827. }
  66828. if (--remaining.count) {
  66829. callback();
  66830. }
  66831. });
  66832. };
  66833. FilesInput.prototype._processFiles = function (files) {
  66834. for (var i = 0; i < files.length; i++) {
  66835. var name = files[i].correctName.toLowerCase();
  66836. var extension = name.split('.').pop();
  66837. if (!this.onProcessFileCallback(files[i], name, extension)) {
  66838. continue;
  66839. }
  66840. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  66841. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  66842. this._sceneFileToLoad = files[i];
  66843. }
  66844. else {
  66845. FilesInput.FilesToLoad[name] = files[i];
  66846. }
  66847. }
  66848. };
  66849. FilesInput.prototype.loadFiles = function (event) {
  66850. var _this = this;
  66851. if (this._startingProcessingFilesCallback)
  66852. this._startingProcessingFilesCallback();
  66853. // Handling data transfer via drag'n'drop
  66854. if (event && event.dataTransfer && event.dataTransfer.files) {
  66855. this._filesToLoad = event.dataTransfer.files;
  66856. }
  66857. // Handling files from input files
  66858. if (event && event.target && event.target.files) {
  66859. this._filesToLoad = event.target.files;
  66860. }
  66861. if (this._filesToLoad && this._filesToLoad.length > 0) {
  66862. var files_1 = new Array();
  66863. var folders = [];
  66864. var items = event.dataTransfer ? event.dataTransfer.items : null;
  66865. for (var i = 0; i < this._filesToLoad.length; i++) {
  66866. var fileToLoad = this._filesToLoad[i];
  66867. var name_1 = fileToLoad.name.toLowerCase();
  66868. var entry = void 0;
  66869. fileToLoad.correctName = name_1;
  66870. if (items) {
  66871. var item = items[i];
  66872. if (item.getAsEntry) {
  66873. entry = item.getAsEntry();
  66874. }
  66875. else if (item.webkitGetAsEntry) {
  66876. entry = item.webkitGetAsEntry();
  66877. }
  66878. }
  66879. if (!entry) {
  66880. files_1.push(fileToLoad);
  66881. }
  66882. else {
  66883. if (entry.isDirectory) {
  66884. folders.push(entry);
  66885. }
  66886. else {
  66887. files_1.push(fileToLoad);
  66888. }
  66889. }
  66890. }
  66891. if (folders.length === 0) {
  66892. this._processFiles(files_1);
  66893. this._processReload();
  66894. }
  66895. else {
  66896. var remaining = { count: folders.length };
  66897. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  66898. var folder = folders_1[_i];
  66899. this._traverseFolder(folder, files_1, remaining, function () {
  66900. _this._processFiles(files_1);
  66901. if (remaining.count === 0) {
  66902. _this._processReload();
  66903. }
  66904. });
  66905. }
  66906. }
  66907. }
  66908. };
  66909. FilesInput.prototype._processReload = function () {
  66910. if (this._onReloadCallback) {
  66911. this._onReloadCallback(this._sceneFileToLoad);
  66912. }
  66913. else {
  66914. this.reload();
  66915. }
  66916. };
  66917. FilesInput.prototype.reload = function () {
  66918. var _this = this;
  66919. // If a scene file has been provided
  66920. if (this._sceneFileToLoad) {
  66921. if (this._currentScene) {
  66922. if (BABYLON.Tools.errorsCount > 0) {
  66923. BABYLON.Tools.ClearLogCache();
  66924. }
  66925. this._engine.stopRenderLoop();
  66926. this._currentScene.dispose();
  66927. }
  66928. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  66929. if (_this._progressCallback) {
  66930. _this._progressCallback(progress);
  66931. }
  66932. }).then(function (scene) {
  66933. _this._currentScene = scene;
  66934. if (_this._sceneLoadedCallback) {
  66935. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  66936. }
  66937. // Wait for textures and shaders to be ready
  66938. _this._currentScene.executeWhenReady(function () {
  66939. _this._engine.runRenderLoop(function () {
  66940. _this.renderFunction();
  66941. });
  66942. });
  66943. }).catch(function (error) {
  66944. if (_this._errorCallback) {
  66945. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  66946. }
  66947. });
  66948. }
  66949. else {
  66950. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  66951. }
  66952. };
  66953. FilesInput.FilesToLoad = {};
  66954. return FilesInput;
  66955. }());
  66956. BABYLON.FilesInput = FilesInput;
  66957. })(BABYLON || (BABYLON = {}));
  66958. //# sourceMappingURL=babylon.filesInput.js.map
  66959. "use strict";
  66960. var BABYLON;
  66961. (function (BABYLON) {
  66962. /**
  66963. * This class implement a typical dictionary using a string as key and the generic type T as value.
  66964. * The underlying implementation relies on an associative array to ensure the best performances.
  66965. * The value can be anything including 'null' but except 'undefined'
  66966. */
  66967. var StringDictionary = /** @class */ (function () {
  66968. function StringDictionary() {
  66969. this._count = 0;
  66970. this._data = {};
  66971. }
  66972. /**
  66973. * This will clear this dictionary and copy the content from the 'source' one.
  66974. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  66975. * @param source the dictionary to take the content from and copy to this dictionary
  66976. */
  66977. StringDictionary.prototype.copyFrom = function (source) {
  66978. var _this = this;
  66979. this.clear();
  66980. source.forEach(function (t, v) { return _this.add(t, v); });
  66981. };
  66982. /**
  66983. * Get a value based from its key
  66984. * @param key the given key to get the matching value from
  66985. * @return the value if found, otherwise undefined is returned
  66986. */
  66987. StringDictionary.prototype.get = function (key) {
  66988. var val = this._data[key];
  66989. if (val !== undefined) {
  66990. return val;
  66991. }
  66992. return undefined;
  66993. };
  66994. /**
  66995. * Get a value from its key or add it if it doesn't exist.
  66996. * This method will ensure you that a given key/data will be present in the dictionary.
  66997. * @param key the given key to get the matching value from
  66998. * @param factory the factory that will create the value if the key is not present in the dictionary.
  66999. * The factory will only be invoked if there's no data for the given key.
  67000. * @return the value corresponding to the key.
  67001. */
  67002. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67003. var val = this.get(key);
  67004. if (val !== undefined) {
  67005. return val;
  67006. }
  67007. val = factory(key);
  67008. if (val) {
  67009. this.add(key, val);
  67010. }
  67011. return val;
  67012. };
  67013. /**
  67014. * Get a value from its key if present in the dictionary otherwise add it
  67015. * @param key the key to get the value from
  67016. * @param val if there's no such key/value pair in the dictionary add it with this value
  67017. * @return the value corresponding to the key
  67018. */
  67019. StringDictionary.prototype.getOrAdd = function (key, val) {
  67020. var curVal = this.get(key);
  67021. if (curVal !== undefined) {
  67022. return curVal;
  67023. }
  67024. this.add(key, val);
  67025. return val;
  67026. };
  67027. /**
  67028. * Check if there's a given key in the dictionary
  67029. * @param key the key to check for
  67030. * @return true if the key is present, false otherwise
  67031. */
  67032. StringDictionary.prototype.contains = function (key) {
  67033. return this._data[key] !== undefined;
  67034. };
  67035. /**
  67036. * Add a new key and its corresponding value
  67037. * @param key the key to add
  67038. * @param value the value corresponding to the key
  67039. * @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
  67040. */
  67041. StringDictionary.prototype.add = function (key, value) {
  67042. if (this._data[key] !== undefined) {
  67043. return false;
  67044. }
  67045. this._data[key] = value;
  67046. ++this._count;
  67047. return true;
  67048. };
  67049. StringDictionary.prototype.set = function (key, value) {
  67050. if (this._data[key] === undefined) {
  67051. return false;
  67052. }
  67053. this._data[key] = value;
  67054. return true;
  67055. };
  67056. /**
  67057. * Get the element of the given key and remove it from the dictionary
  67058. * @param key
  67059. */
  67060. StringDictionary.prototype.getAndRemove = function (key) {
  67061. var val = this.get(key);
  67062. if (val !== undefined) {
  67063. delete this._data[key];
  67064. --this._count;
  67065. return val;
  67066. }
  67067. return null;
  67068. };
  67069. /**
  67070. * Remove a key/value from the dictionary.
  67071. * @param key the key to remove
  67072. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67073. */
  67074. StringDictionary.prototype.remove = function (key) {
  67075. if (this.contains(key)) {
  67076. delete this._data[key];
  67077. --this._count;
  67078. return true;
  67079. }
  67080. return false;
  67081. };
  67082. /**
  67083. * Clear the whole content of the dictionary
  67084. */
  67085. StringDictionary.prototype.clear = function () {
  67086. this._data = {};
  67087. this._count = 0;
  67088. };
  67089. Object.defineProperty(StringDictionary.prototype, "count", {
  67090. get: function () {
  67091. return this._count;
  67092. },
  67093. enumerable: true,
  67094. configurable: true
  67095. });
  67096. /**
  67097. * Execute a callback on each key/val of the dictionary.
  67098. * Note that you can remove any element in this dictionary in the callback implementation
  67099. * @param callback the callback to execute on a given key/value pair
  67100. */
  67101. StringDictionary.prototype.forEach = function (callback) {
  67102. for (var cur in this._data) {
  67103. var val = this._data[cur];
  67104. callback(cur, val);
  67105. }
  67106. };
  67107. /**
  67108. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67109. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67110. * Note that you can remove any element in this dictionary in the callback implementation
  67111. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67112. */
  67113. StringDictionary.prototype.first = function (callback) {
  67114. for (var cur in this._data) {
  67115. var val = this._data[cur];
  67116. var res = callback(cur, val);
  67117. if (res) {
  67118. return res;
  67119. }
  67120. }
  67121. return null;
  67122. };
  67123. return StringDictionary;
  67124. }());
  67125. BABYLON.StringDictionary = StringDictionary;
  67126. })(BABYLON || (BABYLON = {}));
  67127. //# sourceMappingURL=babylon.stringDictionary.js.map
  67128. "use strict";
  67129. var BABYLON;
  67130. (function (BABYLON) {
  67131. var Tags = /** @class */ (function () {
  67132. function Tags() {
  67133. }
  67134. Tags.EnableFor = function (obj) {
  67135. obj._tags = obj._tags || {};
  67136. obj.hasTags = function () {
  67137. return Tags.HasTags(obj);
  67138. };
  67139. obj.addTags = function (tagsString) {
  67140. return Tags.AddTagsTo(obj, tagsString);
  67141. };
  67142. obj.removeTags = function (tagsString) {
  67143. return Tags.RemoveTagsFrom(obj, tagsString);
  67144. };
  67145. obj.matchesTagsQuery = function (tagsQuery) {
  67146. return Tags.MatchesQuery(obj, tagsQuery);
  67147. };
  67148. };
  67149. Tags.DisableFor = function (obj) {
  67150. delete obj._tags;
  67151. delete obj.hasTags;
  67152. delete obj.addTags;
  67153. delete obj.removeTags;
  67154. delete obj.matchesTagsQuery;
  67155. };
  67156. Tags.HasTags = function (obj) {
  67157. if (!obj._tags) {
  67158. return false;
  67159. }
  67160. return !BABYLON.Tools.IsEmpty(obj._tags);
  67161. };
  67162. Tags.GetTags = function (obj, asString) {
  67163. if (asString === void 0) { asString = true; }
  67164. if (!obj._tags) {
  67165. return null;
  67166. }
  67167. if (asString) {
  67168. var tagsArray = [];
  67169. for (var tag in obj._tags) {
  67170. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  67171. tagsArray.push(tag);
  67172. }
  67173. }
  67174. return tagsArray.join(" ");
  67175. }
  67176. else {
  67177. return obj._tags;
  67178. }
  67179. };
  67180. // the tags 'true' and 'false' are reserved and cannot be used as tags
  67181. // a tag cannot start with '||', '&&', and '!'
  67182. // it cannot contain whitespaces
  67183. Tags.AddTagsTo = function (obj, tagsString) {
  67184. if (!tagsString) {
  67185. return;
  67186. }
  67187. if (typeof tagsString !== "string") {
  67188. return;
  67189. }
  67190. var tags = tagsString.split(" ");
  67191. tags.forEach(function (tag, index, array) {
  67192. Tags._AddTagTo(obj, tag);
  67193. });
  67194. };
  67195. Tags._AddTagTo = function (obj, tag) {
  67196. tag = tag.trim();
  67197. if (tag === "" || tag === "true" || tag === "false") {
  67198. return;
  67199. }
  67200. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  67201. return;
  67202. }
  67203. Tags.EnableFor(obj);
  67204. obj._tags[tag] = true;
  67205. };
  67206. Tags.RemoveTagsFrom = function (obj, tagsString) {
  67207. if (!Tags.HasTags(obj)) {
  67208. return;
  67209. }
  67210. var tags = tagsString.split(" ");
  67211. for (var t in tags) {
  67212. Tags._RemoveTagFrom(obj, tags[t]);
  67213. }
  67214. };
  67215. Tags._RemoveTagFrom = function (obj, tag) {
  67216. delete obj._tags[tag];
  67217. };
  67218. Tags.MatchesQuery = function (obj, tagsQuery) {
  67219. if (tagsQuery === undefined) {
  67220. return true;
  67221. }
  67222. if (tagsQuery === "") {
  67223. return Tags.HasTags(obj);
  67224. }
  67225. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  67226. };
  67227. return Tags;
  67228. }());
  67229. BABYLON.Tags = Tags;
  67230. })(BABYLON || (BABYLON = {}));
  67231. //# sourceMappingURL=babylon.tags.js.map
  67232. "use strict";
  67233. var BABYLON;
  67234. (function (BABYLON) {
  67235. var AndOrNotEvaluator = /** @class */ (function () {
  67236. function AndOrNotEvaluator() {
  67237. }
  67238. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  67239. if (!query.match(/\([^\(\)]*\)/g)) {
  67240. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  67241. }
  67242. else {
  67243. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  67244. // remove parenthesis
  67245. r = r.slice(1, r.length - 1);
  67246. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  67247. });
  67248. }
  67249. if (query === "true") {
  67250. return true;
  67251. }
  67252. if (query === "false") {
  67253. return false;
  67254. }
  67255. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67256. };
  67257. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67258. evaluateCallback = evaluateCallback || (function (r) {
  67259. return r === "true" ? true : false;
  67260. });
  67261. var result;
  67262. var or = parenthesisContent.split("||");
  67263. for (var i in or) {
  67264. if (or.hasOwnProperty(i)) {
  67265. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  67266. var and = ori.split("&&");
  67267. if (and.length > 1) {
  67268. for (var j = 0; j < and.length; ++j) {
  67269. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  67270. if (andj !== "true" && andj !== "false") {
  67271. if (andj[0] === "!") {
  67272. result = !evaluateCallback(andj.substring(1));
  67273. }
  67274. else {
  67275. result = evaluateCallback(andj);
  67276. }
  67277. }
  67278. else {
  67279. result = andj === "true" ? true : false;
  67280. }
  67281. if (!result) {
  67282. ori = "false";
  67283. break;
  67284. }
  67285. }
  67286. }
  67287. if (result || ori === "true") {
  67288. result = true;
  67289. break;
  67290. }
  67291. // result equals false (or undefined)
  67292. if (ori !== "true" && ori !== "false") {
  67293. if (ori[0] === "!") {
  67294. result = !evaluateCallback(ori.substring(1));
  67295. }
  67296. else {
  67297. result = evaluateCallback(ori);
  67298. }
  67299. }
  67300. else {
  67301. result = ori === "true" ? true : false;
  67302. }
  67303. }
  67304. }
  67305. // the whole parenthesis scope is replaced by 'true' or 'false'
  67306. return result ? "true" : "false";
  67307. };
  67308. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  67309. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  67310. // remove whitespaces
  67311. r = r.replace(/[\s]/g, function () { return ""; });
  67312. return r.length % 2 ? "!" : "";
  67313. });
  67314. booleanString = booleanString.trim();
  67315. if (booleanString === "!true") {
  67316. booleanString = "false";
  67317. }
  67318. else if (booleanString === "!false") {
  67319. booleanString = "true";
  67320. }
  67321. return booleanString;
  67322. };
  67323. return AndOrNotEvaluator;
  67324. }());
  67325. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  67326. })(BABYLON || (BABYLON = {}));
  67327. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  67328. "use strict";
  67329. var BABYLON;
  67330. (function (BABYLON) {
  67331. var Database = /** @class */ (function () {
  67332. function Database(urlToScene, callbackManifestChecked) {
  67333. // Handling various flavors of prefixed version of IndexedDB
  67334. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  67335. this.callbackManifestChecked = callbackManifestChecked;
  67336. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  67337. this.db = null;
  67338. this._enableSceneOffline = false;
  67339. this._enableTexturesOffline = false;
  67340. this.manifestVersionFound = 0;
  67341. this.mustUpdateRessources = false;
  67342. this.hasReachedQuota = false;
  67343. if (!Database.IDBStorageEnabled) {
  67344. this.callbackManifestChecked(true);
  67345. }
  67346. else {
  67347. this.checkManifestFile();
  67348. }
  67349. }
  67350. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  67351. get: function () {
  67352. return this._enableSceneOffline;
  67353. },
  67354. enumerable: true,
  67355. configurable: true
  67356. });
  67357. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  67358. get: function () {
  67359. return this._enableTexturesOffline;
  67360. },
  67361. enumerable: true,
  67362. configurable: true
  67363. });
  67364. Database.prototype.checkManifestFile = function () {
  67365. var _this = this;
  67366. var noManifestFile = function () {
  67367. _this._enableSceneOffline = false;
  67368. _this._enableTexturesOffline = false;
  67369. _this.callbackManifestChecked(false);
  67370. };
  67371. var timeStampUsed = false;
  67372. var manifestURL = this.currentSceneUrl + ".manifest";
  67373. var xhr = new XMLHttpRequest();
  67374. if (navigator.onLine) {
  67375. // Adding a timestamp to by-pass browsers' cache
  67376. timeStampUsed = true;
  67377. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  67378. }
  67379. xhr.open("GET", manifestURL, true);
  67380. xhr.addEventListener("load", function () {
  67381. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67382. try {
  67383. var manifestFile = JSON.parse(xhr.response);
  67384. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  67385. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  67386. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  67387. _this.manifestVersionFound = manifestFile.version;
  67388. }
  67389. if (_this.callbackManifestChecked) {
  67390. _this.callbackManifestChecked(true);
  67391. }
  67392. }
  67393. catch (ex) {
  67394. noManifestFile();
  67395. }
  67396. }
  67397. else {
  67398. noManifestFile();
  67399. }
  67400. }, false);
  67401. xhr.addEventListener("error", function (event) {
  67402. if (timeStampUsed) {
  67403. timeStampUsed = false;
  67404. // Let's retry without the timeStamp
  67405. // It could fail when coupled with HTML5 Offline API
  67406. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  67407. xhr.open("GET", retryManifestURL, true);
  67408. xhr.send();
  67409. }
  67410. else {
  67411. noManifestFile();
  67412. }
  67413. }, false);
  67414. try {
  67415. xhr.send();
  67416. }
  67417. catch (ex) {
  67418. BABYLON.Tools.Error("Error on XHR send request.");
  67419. this.callbackManifestChecked(false);
  67420. }
  67421. };
  67422. Database.prototype.openAsync = function (successCallback, errorCallback) {
  67423. var _this = this;
  67424. var handleError = function () {
  67425. _this.isSupported = false;
  67426. if (errorCallback)
  67427. errorCallback();
  67428. };
  67429. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  67430. // Your browser doesn't support IndexedDB
  67431. this.isSupported = false;
  67432. if (errorCallback)
  67433. errorCallback();
  67434. }
  67435. else {
  67436. // If the DB hasn't been opened or created yet
  67437. if (!this.db) {
  67438. this.hasReachedQuota = false;
  67439. this.isSupported = true;
  67440. var request = this.idbFactory.open("babylonjs", 1);
  67441. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  67442. request.onerror = function (event) {
  67443. handleError();
  67444. };
  67445. // executes when a version change transaction cannot complete due to other active transactions
  67446. request.onblocked = function (event) {
  67447. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  67448. handleError();
  67449. };
  67450. // DB has been opened successfully
  67451. request.onsuccess = function (event) {
  67452. _this.db = request.result;
  67453. successCallback();
  67454. };
  67455. // Initialization of the DB. Creating Scenes & Textures stores
  67456. request.onupgradeneeded = function (event) {
  67457. _this.db = (event.target).result;
  67458. if (_this.db) {
  67459. try {
  67460. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  67461. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  67462. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  67463. }
  67464. catch (ex) {
  67465. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  67466. handleError();
  67467. }
  67468. }
  67469. };
  67470. }
  67471. else {
  67472. if (successCallback)
  67473. successCallback();
  67474. }
  67475. }
  67476. };
  67477. Database.prototype.loadImageFromDB = function (url, image) {
  67478. var _this = this;
  67479. var completeURL = Database.ReturnFullUrlLocation(url);
  67480. var saveAndLoadImage = function () {
  67481. if (!_this.hasReachedQuota && _this.db !== null) {
  67482. // the texture is not yet in the DB, let's try to save it
  67483. _this._saveImageIntoDBAsync(completeURL, image);
  67484. }
  67485. else {
  67486. image.src = url;
  67487. }
  67488. };
  67489. if (!this.mustUpdateRessources) {
  67490. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  67491. }
  67492. else {
  67493. saveAndLoadImage();
  67494. }
  67495. };
  67496. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  67497. if (this.isSupported && this.db !== null) {
  67498. var texture;
  67499. var transaction = this.db.transaction(["textures"]);
  67500. transaction.onabort = function (event) {
  67501. image.src = url;
  67502. };
  67503. transaction.oncomplete = function (event) {
  67504. var blobTextureURL;
  67505. if (texture) {
  67506. var URL = window.URL || window.webkitURL;
  67507. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  67508. image.onerror = function () {
  67509. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  67510. image.src = url;
  67511. };
  67512. image.src = blobTextureURL;
  67513. }
  67514. else {
  67515. notInDBCallback();
  67516. }
  67517. };
  67518. var getRequest = transaction.objectStore("textures").get(url);
  67519. getRequest.onsuccess = function (event) {
  67520. texture = (event.target).result;
  67521. };
  67522. getRequest.onerror = function (event) {
  67523. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  67524. image.src = url;
  67525. };
  67526. }
  67527. else {
  67528. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67529. image.src = url;
  67530. }
  67531. };
  67532. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  67533. var _this = this;
  67534. if (this.isSupported) {
  67535. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  67536. var generateBlobUrl = function () {
  67537. var blobTextureURL;
  67538. if (blob) {
  67539. var URL = window.URL || window.webkitURL;
  67540. try {
  67541. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  67542. }
  67543. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  67544. catch (ex) {
  67545. blobTextureURL = URL.createObjectURL(blob);
  67546. }
  67547. }
  67548. if (blobTextureURL) {
  67549. image.src = blobTextureURL;
  67550. }
  67551. };
  67552. if (Database.IsUASupportingBlobStorage) {
  67553. var xhr = new XMLHttpRequest(), blob;
  67554. xhr.open("GET", url, true);
  67555. xhr.responseType = "blob";
  67556. xhr.addEventListener("load", function () {
  67557. if (xhr.status === 200 && _this.db) {
  67558. // Blob as response (XHR2)
  67559. blob = xhr.response;
  67560. var transaction = _this.db.transaction(["textures"], "readwrite");
  67561. // the transaction could abort because of a QuotaExceededError error
  67562. transaction.onabort = function (event) {
  67563. try {
  67564. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67565. var srcElement = (event.srcElement || event.target);
  67566. var error = srcElement.error;
  67567. if (error && error.name === "QuotaExceededError") {
  67568. _this.hasReachedQuota = true;
  67569. }
  67570. }
  67571. catch (ex) { }
  67572. generateBlobUrl();
  67573. };
  67574. transaction.oncomplete = function (event) {
  67575. generateBlobUrl();
  67576. };
  67577. var newTexture = { textureUrl: url, data: blob };
  67578. try {
  67579. // Put the blob into the dabase
  67580. var addRequest = transaction.objectStore("textures").put(newTexture);
  67581. addRequest.onsuccess = function (event) {
  67582. };
  67583. addRequest.onerror = function (event) {
  67584. generateBlobUrl();
  67585. };
  67586. }
  67587. catch (ex) {
  67588. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  67589. if (ex.code === 25) {
  67590. Database.IsUASupportingBlobStorage = false;
  67591. }
  67592. image.src = url;
  67593. }
  67594. }
  67595. else {
  67596. image.src = url;
  67597. }
  67598. }, false);
  67599. xhr.addEventListener("error", function (event) {
  67600. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  67601. image.src = url;
  67602. }, false);
  67603. xhr.send();
  67604. }
  67605. else {
  67606. image.src = url;
  67607. }
  67608. }
  67609. else {
  67610. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67611. image.src = url;
  67612. }
  67613. };
  67614. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  67615. var _this = this;
  67616. var updateVersion = function () {
  67617. // the version is not yet in the DB or we need to update it
  67618. _this._saveVersionIntoDBAsync(url, versionLoaded);
  67619. };
  67620. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  67621. };
  67622. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  67623. var _this = this;
  67624. if (this.isSupported && this.db) {
  67625. var version;
  67626. try {
  67627. var transaction = this.db.transaction(["versions"]);
  67628. transaction.oncomplete = function (event) {
  67629. if (version) {
  67630. // If the version in the JSON file is > than the version in DB
  67631. if (_this.manifestVersionFound > version.data) {
  67632. _this.mustUpdateRessources = true;
  67633. updateInDBCallback();
  67634. }
  67635. else {
  67636. callback(version.data);
  67637. }
  67638. }
  67639. else {
  67640. _this.mustUpdateRessources = true;
  67641. updateInDBCallback();
  67642. }
  67643. };
  67644. transaction.onabort = function (event) {
  67645. callback(-1);
  67646. };
  67647. var getRequest = transaction.objectStore("versions").get(url);
  67648. getRequest.onsuccess = function (event) {
  67649. version = (event.target).result;
  67650. };
  67651. getRequest.onerror = function (event) {
  67652. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  67653. callback(-1);
  67654. };
  67655. }
  67656. catch (ex) {
  67657. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  67658. callback(-1);
  67659. }
  67660. }
  67661. else {
  67662. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67663. callback(-1);
  67664. }
  67665. };
  67666. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  67667. var _this = this;
  67668. if (this.isSupported && !this.hasReachedQuota && this.db) {
  67669. try {
  67670. // Open a transaction to the database
  67671. var transaction = this.db.transaction(["versions"], "readwrite");
  67672. // the transaction could abort because of a QuotaExceededError error
  67673. transaction.onabort = function (event) {
  67674. try {
  67675. var error = event.srcElement['error'];
  67676. if (error && error.name === "QuotaExceededError") {
  67677. _this.hasReachedQuota = true;
  67678. }
  67679. }
  67680. catch (ex) { }
  67681. callback(-1);
  67682. };
  67683. transaction.oncomplete = function (event) {
  67684. callback(_this.manifestVersionFound);
  67685. };
  67686. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  67687. // Put the scene into the database
  67688. var addRequest = transaction.objectStore("versions").put(newVersion);
  67689. addRequest.onsuccess = function (event) {
  67690. };
  67691. addRequest.onerror = function (event) {
  67692. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  67693. };
  67694. }
  67695. catch (ex) {
  67696. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  67697. callback(-1);
  67698. }
  67699. }
  67700. else {
  67701. callback(-1);
  67702. }
  67703. };
  67704. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  67705. var _this = this;
  67706. var completeUrl = Database.ReturnFullUrlLocation(url);
  67707. var saveAndLoadFile = function () {
  67708. // the scene is not yet in the DB, let's try to save it
  67709. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  67710. };
  67711. this._checkVersionFromDB(completeUrl, function (version) {
  67712. if (version !== -1) {
  67713. if (!_this.mustUpdateRessources) {
  67714. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  67715. }
  67716. else {
  67717. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  67718. }
  67719. }
  67720. else {
  67721. if (errorCallback) {
  67722. errorCallback();
  67723. }
  67724. }
  67725. });
  67726. };
  67727. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  67728. if (this.isSupported && this.db) {
  67729. var targetStore;
  67730. if (url.indexOf(".babylon") !== -1) {
  67731. targetStore = "scenes";
  67732. }
  67733. else {
  67734. targetStore = "textures";
  67735. }
  67736. var file;
  67737. var transaction = this.db.transaction([targetStore]);
  67738. transaction.oncomplete = function (event) {
  67739. if (file) {
  67740. callback(file.data);
  67741. }
  67742. else {
  67743. notInDBCallback();
  67744. }
  67745. };
  67746. transaction.onabort = function (event) {
  67747. notInDBCallback();
  67748. };
  67749. var getRequest = transaction.objectStore(targetStore).get(url);
  67750. getRequest.onsuccess = function (event) {
  67751. file = (event.target).result;
  67752. };
  67753. getRequest.onerror = function (event) {
  67754. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  67755. notInDBCallback();
  67756. };
  67757. }
  67758. else {
  67759. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67760. callback();
  67761. }
  67762. };
  67763. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  67764. var _this = this;
  67765. if (this.isSupported) {
  67766. var targetStore;
  67767. if (url.indexOf(".babylon") !== -1) {
  67768. targetStore = "scenes";
  67769. }
  67770. else {
  67771. targetStore = "textures";
  67772. }
  67773. // Create XHR
  67774. var xhr = new XMLHttpRequest();
  67775. var fileData;
  67776. xhr.open("GET", url, true);
  67777. if (useArrayBuffer) {
  67778. xhr.responseType = "arraybuffer";
  67779. }
  67780. if (progressCallback) {
  67781. xhr.onprogress = progressCallback;
  67782. }
  67783. xhr.addEventListener("load", function () {
  67784. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  67785. // Blob as response (XHR2)
  67786. //fileData = xhr.responseText;
  67787. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  67788. if (!_this.hasReachedQuota && _this.db) {
  67789. // Open a transaction to the database
  67790. var transaction = _this.db.transaction([targetStore], "readwrite");
  67791. // the transaction could abort because of a QuotaExceededError error
  67792. transaction.onabort = function (event) {
  67793. try {
  67794. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67795. var error = event.srcElement['error'];
  67796. if (error && error.name === "QuotaExceededError") {
  67797. _this.hasReachedQuota = true;
  67798. }
  67799. }
  67800. catch (ex) { }
  67801. callback(fileData);
  67802. };
  67803. transaction.oncomplete = function (event) {
  67804. callback(fileData);
  67805. };
  67806. var newFile;
  67807. if (targetStore === "scenes") {
  67808. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  67809. }
  67810. else {
  67811. newFile = { textureUrl: url, data: fileData };
  67812. }
  67813. try {
  67814. // Put the scene into the database
  67815. var addRequest = transaction.objectStore(targetStore).put(newFile);
  67816. addRequest.onsuccess = function (event) {
  67817. };
  67818. addRequest.onerror = function (event) {
  67819. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  67820. };
  67821. }
  67822. catch (ex) {
  67823. callback(fileData);
  67824. }
  67825. }
  67826. else {
  67827. callback(fileData);
  67828. }
  67829. }
  67830. else {
  67831. callback();
  67832. }
  67833. }, false);
  67834. xhr.addEventListener("error", function (event) {
  67835. BABYLON.Tools.Error("error on XHR request.");
  67836. callback();
  67837. }, false);
  67838. xhr.send();
  67839. }
  67840. else {
  67841. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67842. callback();
  67843. }
  67844. };
  67845. Database.IsUASupportingBlobStorage = true;
  67846. Database.IDBStorageEnabled = true;
  67847. Database.parseURL = function (url) {
  67848. var a = document.createElement('a');
  67849. a.href = url;
  67850. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  67851. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  67852. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  67853. return absLocation;
  67854. };
  67855. Database.ReturnFullUrlLocation = function (url) {
  67856. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  67857. return (Database.parseURL(window.location.href) + url);
  67858. }
  67859. else {
  67860. return url;
  67861. }
  67862. };
  67863. return Database;
  67864. }());
  67865. BABYLON.Database = Database;
  67866. })(BABYLON || (BABYLON = {}));
  67867. //# sourceMappingURL=babylon.database.js.map
  67868. "use strict";
  67869. var BABYLON;
  67870. (function (BABYLON) {
  67871. var FresnelParameters = /** @class */ (function () {
  67872. function FresnelParameters() {
  67873. this._isEnabled = true;
  67874. this.leftColor = BABYLON.Color3.White();
  67875. this.rightColor = BABYLON.Color3.Black();
  67876. this.bias = 0;
  67877. this.power = 1;
  67878. }
  67879. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  67880. get: function () {
  67881. return this._isEnabled;
  67882. },
  67883. set: function (value) {
  67884. if (this._isEnabled === value) {
  67885. return;
  67886. }
  67887. this._isEnabled = value;
  67888. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  67889. },
  67890. enumerable: true,
  67891. configurable: true
  67892. });
  67893. FresnelParameters.prototype.clone = function () {
  67894. var newFresnelParameters = new FresnelParameters();
  67895. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  67896. return newFresnelParameters;
  67897. };
  67898. FresnelParameters.prototype.serialize = function () {
  67899. var serializationObject = {};
  67900. serializationObject.isEnabled = this.isEnabled;
  67901. serializationObject.leftColor = this.leftColor.asArray();
  67902. serializationObject.rightColor = this.rightColor.asArray();
  67903. serializationObject.bias = this.bias;
  67904. serializationObject.power = this.power;
  67905. return serializationObject;
  67906. };
  67907. FresnelParameters.Parse = function (parsedFresnelParameters) {
  67908. var fresnelParameters = new FresnelParameters();
  67909. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  67910. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  67911. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  67912. fresnelParameters.bias = parsedFresnelParameters.bias;
  67913. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  67914. return fresnelParameters;
  67915. };
  67916. return FresnelParameters;
  67917. }());
  67918. BABYLON.FresnelParameters = FresnelParameters;
  67919. })(BABYLON || (BABYLON = {}));
  67920. //# sourceMappingURL=babylon.fresnelParameters.js.map
  67921. "use strict";
  67922. var BABYLON;
  67923. (function (BABYLON) {
  67924. var MultiMaterial = /** @class */ (function (_super) {
  67925. __extends(MultiMaterial, _super);
  67926. function MultiMaterial(name, scene) {
  67927. var _this = _super.call(this, name, scene, true) || this;
  67928. scene.multiMaterials.push(_this);
  67929. _this.subMaterials = new Array();
  67930. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  67931. return _this;
  67932. }
  67933. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  67934. get: function () {
  67935. return this._subMaterials;
  67936. },
  67937. set: function (value) {
  67938. this._subMaterials = value;
  67939. this._hookArray(value);
  67940. },
  67941. enumerable: true,
  67942. configurable: true
  67943. });
  67944. MultiMaterial.prototype._hookArray = function (array) {
  67945. var _this = this;
  67946. var oldPush = array.push;
  67947. array.push = function () {
  67948. var items = [];
  67949. for (var _i = 0; _i < arguments.length; _i++) {
  67950. items[_i] = arguments[_i];
  67951. }
  67952. var result = oldPush.apply(array, items);
  67953. _this._markAllSubMeshesAsTexturesDirty();
  67954. return result;
  67955. };
  67956. var oldSplice = array.splice;
  67957. array.splice = function (index, deleteCount) {
  67958. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67959. _this._markAllSubMeshesAsTexturesDirty();
  67960. return deleted;
  67961. };
  67962. };
  67963. // Properties
  67964. MultiMaterial.prototype.getSubMaterial = function (index) {
  67965. if (index < 0 || index >= this.subMaterials.length) {
  67966. return this.getScene().defaultMaterial;
  67967. }
  67968. return this.subMaterials[index];
  67969. };
  67970. MultiMaterial.prototype.getActiveTextures = function () {
  67971. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  67972. if (subMaterial) {
  67973. return subMaterial.getActiveTextures();
  67974. }
  67975. else {
  67976. return [];
  67977. }
  67978. }));
  67979. var _a;
  67980. };
  67981. // Methods
  67982. MultiMaterial.prototype.getClassName = function () {
  67983. return "MultiMaterial";
  67984. };
  67985. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  67986. for (var index = 0; index < this.subMaterials.length; index++) {
  67987. var subMaterial = this.subMaterials[index];
  67988. if (subMaterial) {
  67989. if (subMaterial.storeEffectOnSubMeshes) {
  67990. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  67991. return false;
  67992. }
  67993. continue;
  67994. }
  67995. if (!subMaterial.isReady(mesh)) {
  67996. return false;
  67997. }
  67998. }
  67999. }
  68000. return true;
  68001. };
  68002. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68003. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68004. for (var index = 0; index < this.subMaterials.length; index++) {
  68005. var subMaterial = null;
  68006. var current = this.subMaterials[index];
  68007. if (cloneChildren && current) {
  68008. subMaterial = current.clone(name + "-" + current.name);
  68009. }
  68010. else {
  68011. subMaterial = this.subMaterials[index];
  68012. }
  68013. newMultiMaterial.subMaterials.push(subMaterial);
  68014. }
  68015. return newMultiMaterial;
  68016. };
  68017. MultiMaterial.prototype.serialize = function () {
  68018. var serializationObject = {};
  68019. serializationObject.name = this.name;
  68020. serializationObject.id = this.id;
  68021. if (BABYLON.Tags) {
  68022. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68023. }
  68024. serializationObject.materials = [];
  68025. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68026. var subMat = this.subMaterials[matIndex];
  68027. if (subMat) {
  68028. serializationObject.materials.push(subMat.id);
  68029. }
  68030. else {
  68031. serializationObject.materials.push(null);
  68032. }
  68033. }
  68034. return serializationObject;
  68035. };
  68036. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68037. var scene = this.getScene();
  68038. if (!scene) {
  68039. return;
  68040. }
  68041. var index = scene.multiMaterials.indexOf(this);
  68042. if (index >= 0) {
  68043. scene.multiMaterials.splice(index, 1);
  68044. }
  68045. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68046. };
  68047. return MultiMaterial;
  68048. }(BABYLON.Material));
  68049. BABYLON.MultiMaterial = MultiMaterial;
  68050. })(BABYLON || (BABYLON = {}));
  68051. //# sourceMappingURL=babylon.multiMaterial.js.map
  68052. "use strict";
  68053. var BABYLON;
  68054. (function (BABYLON) {
  68055. var FreeCameraTouchInput = /** @class */ (function () {
  68056. function FreeCameraTouchInput() {
  68057. this._offsetX = null;
  68058. this._offsetY = null;
  68059. this._pointerPressed = new Array();
  68060. this.touchAngularSensibility = 200000.0;
  68061. this.touchMoveSensibility = 250.0;
  68062. }
  68063. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68064. var _this = this;
  68065. var previousPosition = null;
  68066. if (this._pointerInput === undefined) {
  68067. this._onLostFocus = function (evt) {
  68068. _this._offsetX = null;
  68069. _this._offsetY = null;
  68070. };
  68071. this._pointerInput = function (p, s) {
  68072. var evt = p.event;
  68073. if (evt.pointerType === "mouse") {
  68074. return;
  68075. }
  68076. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68077. if (!noPreventDefault) {
  68078. evt.preventDefault();
  68079. }
  68080. _this._pointerPressed.push(evt.pointerId);
  68081. if (_this._pointerPressed.length !== 1) {
  68082. return;
  68083. }
  68084. previousPosition = {
  68085. x: evt.clientX,
  68086. y: evt.clientY
  68087. };
  68088. }
  68089. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68090. if (!noPreventDefault) {
  68091. evt.preventDefault();
  68092. }
  68093. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68094. if (index === -1) {
  68095. return;
  68096. }
  68097. _this._pointerPressed.splice(index, 1);
  68098. if (index != 0) {
  68099. return;
  68100. }
  68101. previousPosition = null;
  68102. _this._offsetX = null;
  68103. _this._offsetY = null;
  68104. }
  68105. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68106. if (!noPreventDefault) {
  68107. evt.preventDefault();
  68108. }
  68109. if (!previousPosition) {
  68110. return;
  68111. }
  68112. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68113. if (index != 0) {
  68114. return;
  68115. }
  68116. _this._offsetX = evt.clientX - previousPosition.x;
  68117. _this._offsetY = -(evt.clientY - previousPosition.y);
  68118. }
  68119. };
  68120. }
  68121. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  68122. if (this._onLostFocus) {
  68123. element.addEventListener("blur", this._onLostFocus);
  68124. }
  68125. };
  68126. FreeCameraTouchInput.prototype.detachControl = function (element) {
  68127. if (this._pointerInput && element) {
  68128. if (this._observer) {
  68129. this.camera.getScene().onPointerObservable.remove(this._observer);
  68130. this._observer = null;
  68131. }
  68132. if (this._onLostFocus) {
  68133. element.removeEventListener("blur", this._onLostFocus);
  68134. this._onLostFocus = null;
  68135. }
  68136. this._pointerPressed = [];
  68137. this._offsetX = null;
  68138. this._offsetY = null;
  68139. }
  68140. };
  68141. FreeCameraTouchInput.prototype.checkInputs = function () {
  68142. if (this._offsetX && this._offsetY) {
  68143. var camera = this.camera;
  68144. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  68145. if (this._pointerPressed.length > 1) {
  68146. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  68147. }
  68148. else {
  68149. var speed = camera._computeLocalCameraSpeed();
  68150. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  68151. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  68152. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  68153. }
  68154. }
  68155. };
  68156. FreeCameraTouchInput.prototype.getClassName = function () {
  68157. return "FreeCameraTouchInput";
  68158. };
  68159. FreeCameraTouchInput.prototype.getSimpleName = function () {
  68160. return "touch";
  68161. };
  68162. __decorate([
  68163. BABYLON.serialize()
  68164. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  68165. __decorate([
  68166. BABYLON.serialize()
  68167. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  68168. return FreeCameraTouchInput;
  68169. }());
  68170. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  68171. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  68172. })(BABYLON || (BABYLON = {}));
  68173. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  68174. "use strict";
  68175. var BABYLON;
  68176. (function (BABYLON) {
  68177. // We're mainly based on the logic defined into the FreeCamera code
  68178. var TouchCamera = /** @class */ (function (_super) {
  68179. __extends(TouchCamera, _super);
  68180. //-- end properties for backward compatibility for inputs
  68181. function TouchCamera(name, position, scene) {
  68182. var _this = _super.call(this, name, position, scene) || this;
  68183. _this.inputs.addTouch();
  68184. _this._setupInputs();
  68185. return _this;
  68186. }
  68187. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  68188. //-- Begin properties for backward compatibility for inputs
  68189. get: function () {
  68190. var touch = this.inputs.attached["touch"];
  68191. if (touch)
  68192. return touch.touchAngularSensibility;
  68193. return 0;
  68194. },
  68195. set: function (value) {
  68196. var touch = this.inputs.attached["touch"];
  68197. if (touch)
  68198. touch.touchAngularSensibility = value;
  68199. },
  68200. enumerable: true,
  68201. configurable: true
  68202. });
  68203. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  68204. get: function () {
  68205. var touch = this.inputs.attached["touch"];
  68206. if (touch)
  68207. return touch.touchMoveSensibility;
  68208. return 0;
  68209. },
  68210. set: function (value) {
  68211. var touch = this.inputs.attached["touch"];
  68212. if (touch)
  68213. touch.touchMoveSensibility = value;
  68214. },
  68215. enumerable: true,
  68216. configurable: true
  68217. });
  68218. TouchCamera.prototype.getClassName = function () {
  68219. return "TouchCamera";
  68220. };
  68221. TouchCamera.prototype._setupInputs = function () {
  68222. var mouse = this.inputs.attached["mouse"];
  68223. if (mouse) {
  68224. mouse.touchEnabled = false;
  68225. }
  68226. };
  68227. return TouchCamera;
  68228. }(BABYLON.FreeCamera));
  68229. BABYLON.TouchCamera = TouchCamera;
  68230. })(BABYLON || (BABYLON = {}));
  68231. //# sourceMappingURL=babylon.touchCamera.js.map
  68232. "use strict";
  68233. var BABYLON;
  68234. (function (BABYLON) {
  68235. var ProceduralTexture = /** @class */ (function (_super) {
  68236. __extends(ProceduralTexture, _super);
  68237. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  68238. if (fallbackTexture === void 0) { fallbackTexture = null; }
  68239. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68240. if (isCube === void 0) { isCube = false; }
  68241. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  68242. _this.isCube = isCube;
  68243. _this.isEnabled = true;
  68244. _this._currentRefreshId = -1;
  68245. _this._refreshRate = 1;
  68246. _this._vertexBuffers = {};
  68247. _this._uniforms = new Array();
  68248. _this._samplers = new Array();
  68249. _this._textures = {};
  68250. _this._floats = {};
  68251. _this._floatsArrays = {};
  68252. _this._colors3 = {};
  68253. _this._colors4 = {};
  68254. _this._vectors2 = {};
  68255. _this._vectors3 = {};
  68256. _this._matrices = {};
  68257. _this._fallbackTextureUsed = false;
  68258. scene.proceduralTextures.push(_this);
  68259. _this._engine = scene.getEngine();
  68260. _this.name = name;
  68261. _this.isRenderTarget = true;
  68262. _this._size = size;
  68263. _this._generateMipMaps = generateMipMaps;
  68264. _this.setFragment(fragment);
  68265. _this._fallbackTexture = fallbackTexture;
  68266. if (isCube) {
  68267. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  68268. _this.setFloat("face", 0);
  68269. }
  68270. else {
  68271. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  68272. }
  68273. // VBO
  68274. var vertices = [];
  68275. vertices.push(1, 1);
  68276. vertices.push(-1, 1);
  68277. vertices.push(-1, -1);
  68278. vertices.push(1, -1);
  68279. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68280. _this._createIndexBuffer();
  68281. return _this;
  68282. }
  68283. ProceduralTexture.prototype._createIndexBuffer = function () {
  68284. var engine = this._engine;
  68285. // Indices
  68286. var indices = [];
  68287. indices.push(0);
  68288. indices.push(1);
  68289. indices.push(2);
  68290. indices.push(0);
  68291. indices.push(2);
  68292. indices.push(3);
  68293. this._indexBuffer = engine.createIndexBuffer(indices);
  68294. };
  68295. ProceduralTexture.prototype._rebuild = function () {
  68296. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68297. if (vb) {
  68298. vb._rebuild();
  68299. }
  68300. this._createIndexBuffer();
  68301. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68302. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68303. }
  68304. };
  68305. ProceduralTexture.prototype.reset = function () {
  68306. if (this._effect === undefined) {
  68307. return;
  68308. }
  68309. var engine = this._engine;
  68310. engine._releaseEffect(this._effect);
  68311. };
  68312. ProceduralTexture.prototype.isReady = function () {
  68313. var _this = this;
  68314. var engine = this._engine;
  68315. var shaders;
  68316. if (!this._fragment) {
  68317. return false;
  68318. }
  68319. if (this._fallbackTextureUsed) {
  68320. return true;
  68321. }
  68322. if (this._fragment.fragmentElement !== undefined) {
  68323. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  68324. }
  68325. else {
  68326. shaders = { vertex: "procedural", fragment: this._fragment };
  68327. }
  68328. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  68329. _this.releaseInternalTexture();
  68330. if (_this._fallbackTexture) {
  68331. _this._texture = _this._fallbackTexture._texture;
  68332. if (_this._texture) {
  68333. _this._texture.incrementReferences();
  68334. }
  68335. }
  68336. _this._fallbackTextureUsed = true;
  68337. });
  68338. return this._effect.isReady();
  68339. };
  68340. ProceduralTexture.prototype.resetRefreshCounter = function () {
  68341. this._currentRefreshId = -1;
  68342. };
  68343. ProceduralTexture.prototype.setFragment = function (fragment) {
  68344. this._fragment = fragment;
  68345. };
  68346. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  68347. get: function () {
  68348. return this._refreshRate;
  68349. },
  68350. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  68351. set: function (value) {
  68352. this._refreshRate = value;
  68353. this.resetRefreshCounter();
  68354. },
  68355. enumerable: true,
  68356. configurable: true
  68357. });
  68358. ProceduralTexture.prototype._shouldRender = function () {
  68359. if (!this.isEnabled || !this.isReady() || !this._texture) {
  68360. return false;
  68361. }
  68362. if (this._fallbackTextureUsed) {
  68363. return false;
  68364. }
  68365. if (this._currentRefreshId === -1) {
  68366. this._currentRefreshId = 1;
  68367. return true;
  68368. }
  68369. if (this.refreshRate === this._currentRefreshId) {
  68370. this._currentRefreshId = 1;
  68371. return true;
  68372. }
  68373. this._currentRefreshId++;
  68374. return false;
  68375. };
  68376. ProceduralTexture.prototype.getRenderSize = function () {
  68377. return this._size;
  68378. };
  68379. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  68380. if (this._fallbackTextureUsed) {
  68381. return;
  68382. }
  68383. this.releaseInternalTexture();
  68384. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  68385. };
  68386. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  68387. if (this._uniforms.indexOf(uniformName) === -1) {
  68388. this._uniforms.push(uniformName);
  68389. }
  68390. };
  68391. ProceduralTexture.prototype.setTexture = function (name, texture) {
  68392. if (this._samplers.indexOf(name) === -1) {
  68393. this._samplers.push(name);
  68394. }
  68395. this._textures[name] = texture;
  68396. return this;
  68397. };
  68398. ProceduralTexture.prototype.setFloat = function (name, value) {
  68399. this._checkUniform(name);
  68400. this._floats[name] = value;
  68401. return this;
  68402. };
  68403. ProceduralTexture.prototype.setFloats = function (name, value) {
  68404. this._checkUniform(name);
  68405. this._floatsArrays[name] = value;
  68406. return this;
  68407. };
  68408. ProceduralTexture.prototype.setColor3 = function (name, value) {
  68409. this._checkUniform(name);
  68410. this._colors3[name] = value;
  68411. return this;
  68412. };
  68413. ProceduralTexture.prototype.setColor4 = function (name, value) {
  68414. this._checkUniform(name);
  68415. this._colors4[name] = value;
  68416. return this;
  68417. };
  68418. ProceduralTexture.prototype.setVector2 = function (name, value) {
  68419. this._checkUniform(name);
  68420. this._vectors2[name] = value;
  68421. return this;
  68422. };
  68423. ProceduralTexture.prototype.setVector3 = function (name, value) {
  68424. this._checkUniform(name);
  68425. this._vectors3[name] = value;
  68426. return this;
  68427. };
  68428. ProceduralTexture.prototype.setMatrix = function (name, value) {
  68429. this._checkUniform(name);
  68430. this._matrices[name] = value;
  68431. return this;
  68432. };
  68433. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68434. var scene = this.getScene();
  68435. if (!scene) {
  68436. return;
  68437. }
  68438. var engine = this._engine;
  68439. // Render
  68440. engine.enableEffect(this._effect);
  68441. engine.setState(false);
  68442. // Texture
  68443. for (var name in this._textures) {
  68444. this._effect.setTexture(name, this._textures[name]);
  68445. }
  68446. // Float
  68447. for (name in this._floats) {
  68448. this._effect.setFloat(name, this._floats[name]);
  68449. }
  68450. // Floats
  68451. for (name in this._floatsArrays) {
  68452. this._effect.setArray(name, this._floatsArrays[name]);
  68453. }
  68454. // Color3
  68455. for (name in this._colors3) {
  68456. this._effect.setColor3(name, this._colors3[name]);
  68457. }
  68458. // Color4
  68459. for (name in this._colors4) {
  68460. var color = this._colors4[name];
  68461. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  68462. }
  68463. // Vector2
  68464. for (name in this._vectors2) {
  68465. this._effect.setVector2(name, this._vectors2[name]);
  68466. }
  68467. // Vector3
  68468. for (name in this._vectors3) {
  68469. this._effect.setVector3(name, this._vectors3[name]);
  68470. }
  68471. // Matrix
  68472. for (name in this._matrices) {
  68473. this._effect.setMatrix(name, this._matrices[name]);
  68474. }
  68475. if (!this._texture) {
  68476. return;
  68477. }
  68478. if (this.isCube) {
  68479. for (var face = 0; face < 6; face++) {
  68480. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  68481. // VBOs
  68482. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68483. this._effect.setFloat("face", face);
  68484. // Clear
  68485. engine.clear(scene.clearColor, true, true, true);
  68486. // Draw order
  68487. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68488. // Mipmaps
  68489. if (face === 5) {
  68490. engine.generateMipMapsForCubemap(this._texture);
  68491. }
  68492. }
  68493. }
  68494. else {
  68495. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  68496. // VBOs
  68497. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68498. // Clear
  68499. engine.clear(scene.clearColor, true, true, true);
  68500. // Draw order
  68501. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68502. }
  68503. // Unbind
  68504. engine.unBindFramebuffer(this._texture, this.isCube);
  68505. if (this.onGenerated) {
  68506. this.onGenerated();
  68507. }
  68508. };
  68509. ProceduralTexture.prototype.clone = function () {
  68510. var textureSize = this.getSize();
  68511. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  68512. // Base texture
  68513. newTexture.hasAlpha = this.hasAlpha;
  68514. newTexture.level = this.level;
  68515. // RenderTarget Texture
  68516. newTexture.coordinatesMode = this.coordinatesMode;
  68517. return newTexture;
  68518. };
  68519. ProceduralTexture.prototype.dispose = function () {
  68520. var scene = this.getScene();
  68521. if (!scene) {
  68522. return;
  68523. }
  68524. var index = scene.proceduralTextures.indexOf(this);
  68525. if (index >= 0) {
  68526. scene.proceduralTextures.splice(index, 1);
  68527. }
  68528. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68529. if (vertexBuffer) {
  68530. vertexBuffer.dispose();
  68531. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68532. }
  68533. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  68534. this._indexBuffer = null;
  68535. }
  68536. _super.prototype.dispose.call(this);
  68537. };
  68538. return ProceduralTexture;
  68539. }(BABYLON.Texture));
  68540. BABYLON.ProceduralTexture = ProceduralTexture;
  68541. })(BABYLON || (BABYLON = {}));
  68542. //# sourceMappingURL=babylon.proceduralTexture.js.map
  68543. "use strict";
  68544. var BABYLON;
  68545. (function (BABYLON) {
  68546. var CustomProceduralTexture = /** @class */ (function (_super) {
  68547. __extends(CustomProceduralTexture, _super);
  68548. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  68549. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  68550. _this._animate = true;
  68551. _this._time = 0;
  68552. _this._texturePath = texturePath;
  68553. //Try to load json
  68554. _this.loadJson(texturePath);
  68555. _this.refreshRate = 1;
  68556. return _this;
  68557. }
  68558. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  68559. var _this = this;
  68560. var noConfigFile = function () {
  68561. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  68562. try {
  68563. _this.setFragment(_this._texturePath);
  68564. }
  68565. catch (ex) {
  68566. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  68567. }
  68568. };
  68569. var configFileUrl = jsonUrl + "/config.json";
  68570. var xhr = new XMLHttpRequest();
  68571. xhr.open("GET", configFileUrl, true);
  68572. xhr.addEventListener("load", function () {
  68573. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68574. try {
  68575. _this._config = JSON.parse(xhr.response);
  68576. _this.updateShaderUniforms();
  68577. _this.updateTextures();
  68578. _this.setFragment(_this._texturePath + "/custom");
  68579. _this._animate = _this._config.animate;
  68580. _this.refreshRate = _this._config.refreshrate;
  68581. }
  68582. catch (ex) {
  68583. noConfigFile();
  68584. }
  68585. }
  68586. else {
  68587. noConfigFile();
  68588. }
  68589. }, false);
  68590. xhr.addEventListener("error", function () {
  68591. noConfigFile();
  68592. }, false);
  68593. try {
  68594. xhr.send();
  68595. }
  68596. catch (ex) {
  68597. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  68598. }
  68599. };
  68600. CustomProceduralTexture.prototype.isReady = function () {
  68601. if (!_super.prototype.isReady.call(this)) {
  68602. return false;
  68603. }
  68604. for (var name in this._textures) {
  68605. var texture = this._textures[name];
  68606. if (!texture.isReady()) {
  68607. return false;
  68608. }
  68609. }
  68610. return true;
  68611. };
  68612. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68613. var scene = this.getScene();
  68614. if (this._animate && scene) {
  68615. this._time += scene.getAnimationRatio() * 0.03;
  68616. this.updateShaderUniforms();
  68617. }
  68618. _super.prototype.render.call(this, useCameraPostProcess);
  68619. };
  68620. CustomProceduralTexture.prototype.updateTextures = function () {
  68621. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  68622. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  68623. }
  68624. };
  68625. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  68626. if (this._config) {
  68627. for (var j = 0; j < this._config.uniforms.length; j++) {
  68628. var uniform = this._config.uniforms[j];
  68629. switch (uniform.type) {
  68630. case "float":
  68631. this.setFloat(uniform.name, uniform.value);
  68632. break;
  68633. case "color3":
  68634. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  68635. break;
  68636. case "color4":
  68637. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  68638. break;
  68639. case "vector2":
  68640. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  68641. break;
  68642. case "vector3":
  68643. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  68644. break;
  68645. }
  68646. }
  68647. }
  68648. this.setFloat("time", this._time);
  68649. };
  68650. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  68651. get: function () {
  68652. return this._animate;
  68653. },
  68654. set: function (value) {
  68655. this._animate = value;
  68656. },
  68657. enumerable: true,
  68658. configurable: true
  68659. });
  68660. return CustomProceduralTexture;
  68661. }(BABYLON.ProceduralTexture));
  68662. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  68663. })(BABYLON || (BABYLON = {}));
  68664. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  68665. "use strict";
  68666. var BABYLON;
  68667. (function (BABYLON) {
  68668. var FreeCameraGamepadInput = /** @class */ (function () {
  68669. function FreeCameraGamepadInput() {
  68670. this.gamepadAngularSensibility = 200;
  68671. this.gamepadMoveSensibility = 40;
  68672. // private members
  68673. this._cameraTransform = BABYLON.Matrix.Identity();
  68674. this._deltaTransform = BABYLON.Vector3.Zero();
  68675. this._vector3 = BABYLON.Vector3.Zero();
  68676. this._vector2 = BABYLON.Vector2.Zero();
  68677. }
  68678. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68679. var _this = this;
  68680. var manager = this.camera.getScene().gamepadManager;
  68681. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68682. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68683. // prioritize XBOX gamepads.
  68684. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68685. _this.gamepad = gamepad;
  68686. }
  68687. }
  68688. });
  68689. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68690. if (_this.gamepad === gamepad) {
  68691. _this.gamepad = null;
  68692. }
  68693. });
  68694. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68695. };
  68696. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  68697. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68698. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68699. this.gamepad = null;
  68700. };
  68701. FreeCameraGamepadInput.prototype.checkInputs = function () {
  68702. if (this.gamepad && this.gamepad.leftStick) {
  68703. var camera = this.camera;
  68704. var LSValues = this.gamepad.leftStick;
  68705. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  68706. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68707. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  68708. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  68709. var RSValues = this.gamepad.rightStick;
  68710. if (RSValues) {
  68711. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  68712. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  68713. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  68714. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  68715. }
  68716. else {
  68717. RSValues = { x: 0, y: 0 };
  68718. }
  68719. if (!camera.rotationQuaternion) {
  68720. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  68721. }
  68722. else {
  68723. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  68724. }
  68725. var speed = camera._computeLocalCameraSpeed() * 50.0;
  68726. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  68727. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  68728. camera.cameraDirection.addInPlace(this._deltaTransform);
  68729. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  68730. camera.cameraRotation.addInPlace(this._vector2);
  68731. }
  68732. };
  68733. FreeCameraGamepadInput.prototype.getClassName = function () {
  68734. return "FreeCameraGamepadInput";
  68735. };
  68736. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  68737. return "gamepad";
  68738. };
  68739. __decorate([
  68740. BABYLON.serialize()
  68741. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  68742. __decorate([
  68743. BABYLON.serialize()
  68744. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68745. return FreeCameraGamepadInput;
  68746. }());
  68747. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  68748. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  68749. })(BABYLON || (BABYLON = {}));
  68750. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  68751. "use strict";
  68752. var BABYLON;
  68753. (function (BABYLON) {
  68754. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  68755. function ArcRotateCameraGamepadInput() {
  68756. this.gamepadRotationSensibility = 80;
  68757. this.gamepadMoveSensibility = 40;
  68758. }
  68759. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68760. var _this = this;
  68761. var manager = this.camera.getScene().gamepadManager;
  68762. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68763. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68764. // prioritize XBOX gamepads.
  68765. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68766. _this.gamepad = gamepad;
  68767. }
  68768. }
  68769. });
  68770. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68771. if (_this.gamepad === gamepad) {
  68772. _this.gamepad = null;
  68773. }
  68774. });
  68775. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68776. };
  68777. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  68778. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68779. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68780. this.gamepad = null;
  68781. };
  68782. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  68783. if (this.gamepad) {
  68784. var camera = this.camera;
  68785. var RSValues = this.gamepad.rightStick;
  68786. if (RSValues) {
  68787. if (RSValues.x != 0) {
  68788. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  68789. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  68790. camera.inertialAlphaOffset += normalizedRX;
  68791. }
  68792. }
  68793. if (RSValues.y != 0) {
  68794. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  68795. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  68796. camera.inertialBetaOffset += normalizedRY;
  68797. }
  68798. }
  68799. }
  68800. var LSValues = this.gamepad.leftStick;
  68801. if (LSValues && LSValues.y != 0) {
  68802. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68803. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  68804. this.camera.inertialRadiusOffset -= normalizedLY;
  68805. }
  68806. }
  68807. }
  68808. };
  68809. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  68810. return "ArcRotateCameraGamepadInput";
  68811. };
  68812. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  68813. return "gamepad";
  68814. };
  68815. __decorate([
  68816. BABYLON.serialize()
  68817. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  68818. __decorate([
  68819. BABYLON.serialize()
  68820. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68821. return ArcRotateCameraGamepadInput;
  68822. }());
  68823. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  68824. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  68825. })(BABYLON || (BABYLON = {}));
  68826. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  68827. "use strict";
  68828. var BABYLON;
  68829. (function (BABYLON) {
  68830. var GamepadManager = /** @class */ (function () {
  68831. function GamepadManager(_scene) {
  68832. var _this = this;
  68833. this._scene = _scene;
  68834. this._babylonGamepads = [];
  68835. this._oneGamepadConnected = false;
  68836. this._isMonitoring = false;
  68837. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  68838. if (!BABYLON.Tools.IsWindowObjectExist()) {
  68839. this._gamepadEventSupported = false;
  68840. }
  68841. else {
  68842. this._gamepadEventSupported = 'GamepadEvent' in window;
  68843. this._gamepadSupport = (navigator.getGamepads ||
  68844. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  68845. }
  68846. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  68847. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  68848. for (var i in _this._babylonGamepads) {
  68849. var gamepad = _this._babylonGamepads[i];
  68850. if (gamepad && gamepad._isConnected) {
  68851. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  68852. }
  68853. }
  68854. });
  68855. this._onGamepadConnectedEvent = function (evt) {
  68856. var gamepad = evt.gamepad;
  68857. if (gamepad.index in _this._babylonGamepads) {
  68858. if (_this._babylonGamepads[gamepad.index].isConnected) {
  68859. return;
  68860. }
  68861. }
  68862. var newGamepad;
  68863. if (_this._babylonGamepads[gamepad.index]) {
  68864. newGamepad = _this._babylonGamepads[gamepad.index];
  68865. newGamepad.browserGamepad = gamepad;
  68866. newGamepad._isConnected = true;
  68867. }
  68868. else {
  68869. newGamepad = _this._addNewGamepad(gamepad);
  68870. }
  68871. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68872. _this._startMonitoringGamepads();
  68873. };
  68874. this._onGamepadDisconnectedEvent = function (evt) {
  68875. var gamepad = evt.gamepad;
  68876. // Remove the gamepad from the list of gamepads to monitor.
  68877. for (var i in _this._babylonGamepads) {
  68878. if (_this._babylonGamepads[i].index === gamepad.index) {
  68879. var disconnectedGamepad = _this._babylonGamepads[i];
  68880. disconnectedGamepad._isConnected = false;
  68881. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  68882. break;
  68883. }
  68884. }
  68885. };
  68886. if (this._gamepadSupport) {
  68887. //first add already-connected gamepads
  68888. this._updateGamepadObjects();
  68889. if (this._babylonGamepads.length) {
  68890. this._startMonitoringGamepads();
  68891. }
  68892. // Checking if the gamepad connected event is supported (like in Firefox)
  68893. if (this._gamepadEventSupported) {
  68894. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  68895. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  68896. }
  68897. else {
  68898. this._startMonitoringGamepads();
  68899. }
  68900. }
  68901. }
  68902. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  68903. get: function () {
  68904. return this._babylonGamepads;
  68905. },
  68906. enumerable: true,
  68907. configurable: true
  68908. });
  68909. GamepadManager.prototype.getGamepadByType = function (type) {
  68910. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  68911. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  68912. var gamepad = _a[_i];
  68913. if (gamepad && gamepad.type === type) {
  68914. return gamepad;
  68915. }
  68916. }
  68917. return null;
  68918. };
  68919. GamepadManager.prototype.dispose = function () {
  68920. if (this._gamepadEventSupported) {
  68921. if (this._onGamepadConnectedEvent) {
  68922. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  68923. }
  68924. if (this._onGamepadDisconnectedEvent) {
  68925. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  68926. }
  68927. this._onGamepadConnectedEvent = null;
  68928. this._onGamepadDisconnectedEvent = null;
  68929. }
  68930. this._babylonGamepads.forEach(function (gamepad) {
  68931. gamepad.dispose();
  68932. });
  68933. this.onGamepadConnectedObservable.clear();
  68934. this.onGamepadDisconnectedObservable.clear();
  68935. this._oneGamepadConnected = false;
  68936. this._stopMonitoringGamepads();
  68937. this._babylonGamepads = [];
  68938. };
  68939. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  68940. if (!this._oneGamepadConnected) {
  68941. this._oneGamepadConnected = true;
  68942. }
  68943. var newGamepad;
  68944. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  68945. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  68946. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  68947. }
  68948. else if (gamepad.pose) {
  68949. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  68950. }
  68951. else {
  68952. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  68953. }
  68954. this._babylonGamepads[newGamepad.index] = newGamepad;
  68955. return newGamepad;
  68956. };
  68957. GamepadManager.prototype._startMonitoringGamepads = function () {
  68958. if (!this._isMonitoring) {
  68959. this._isMonitoring = true;
  68960. //back-comp
  68961. if (!this._scene) {
  68962. this._checkGamepadsStatus();
  68963. }
  68964. }
  68965. };
  68966. GamepadManager.prototype._stopMonitoringGamepads = function () {
  68967. this._isMonitoring = false;
  68968. };
  68969. GamepadManager.prototype._checkGamepadsStatus = function () {
  68970. var _this = this;
  68971. // Hack to be compatible Chrome
  68972. this._updateGamepadObjects();
  68973. for (var i in this._babylonGamepads) {
  68974. var gamepad = this._babylonGamepads[i];
  68975. if (!gamepad || !gamepad.isConnected) {
  68976. continue;
  68977. }
  68978. gamepad.update();
  68979. }
  68980. if (this._isMonitoring && !this._scene) {
  68981. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  68982. }
  68983. };
  68984. // This function is called only on Chrome, which does not properly support
  68985. // connection/disconnection events and forces you to recopy again the gamepad object
  68986. GamepadManager.prototype._updateGamepadObjects = function () {
  68987. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  68988. for (var i = 0; i < gamepads.length; i++) {
  68989. if (gamepads[i]) {
  68990. if (!this._babylonGamepads[gamepads[i].index]) {
  68991. var newGamepad = this._addNewGamepad(gamepads[i]);
  68992. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68993. }
  68994. else {
  68995. // Forced to copy again this object for Chrome for unknown reason
  68996. this._babylonGamepads[i].browserGamepad = gamepads[i];
  68997. if (!this._babylonGamepads[i].isConnected) {
  68998. this._babylonGamepads[i]._isConnected = true;
  68999. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69000. }
  69001. }
  69002. }
  69003. }
  69004. };
  69005. return GamepadManager;
  69006. }());
  69007. BABYLON.GamepadManager = GamepadManager;
  69008. })(BABYLON || (BABYLON = {}));
  69009. //# sourceMappingURL=babylon.gamepadManager.js.map
  69010. "use strict";
  69011. var BABYLON;
  69012. (function (BABYLON) {
  69013. var StickValues = /** @class */ (function () {
  69014. function StickValues(x, y) {
  69015. this.x = x;
  69016. this.y = y;
  69017. }
  69018. return StickValues;
  69019. }());
  69020. BABYLON.StickValues = StickValues;
  69021. var Gamepad = /** @class */ (function () {
  69022. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69023. if (leftStickX === void 0) { leftStickX = 0; }
  69024. if (leftStickY === void 0) { leftStickY = 1; }
  69025. if (rightStickX === void 0) { rightStickX = 2; }
  69026. if (rightStickY === void 0) { rightStickY = 3; }
  69027. this.id = id;
  69028. this.index = index;
  69029. this.browserGamepad = browserGamepad;
  69030. this._isConnected = true;
  69031. this._invertLeftStickY = false;
  69032. this.type = Gamepad.GAMEPAD;
  69033. this._leftStickAxisX = leftStickX;
  69034. this._leftStickAxisY = leftStickY;
  69035. this._rightStickAxisX = rightStickX;
  69036. this._rightStickAxisY = rightStickY;
  69037. if (this.browserGamepad.axes.length >= 2) {
  69038. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69039. }
  69040. if (this.browserGamepad.axes.length >= 4) {
  69041. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69042. }
  69043. }
  69044. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69045. get: function () {
  69046. return this._isConnected;
  69047. },
  69048. enumerable: true,
  69049. configurable: true
  69050. });
  69051. Gamepad.prototype.onleftstickchanged = function (callback) {
  69052. this._onleftstickchanged = callback;
  69053. };
  69054. Gamepad.prototype.onrightstickchanged = function (callback) {
  69055. this._onrightstickchanged = callback;
  69056. };
  69057. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69058. get: function () {
  69059. return this._leftStick;
  69060. },
  69061. set: function (newValues) {
  69062. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69063. this._onleftstickchanged(newValues);
  69064. }
  69065. this._leftStick = newValues;
  69066. },
  69067. enumerable: true,
  69068. configurable: true
  69069. });
  69070. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69071. get: function () {
  69072. return this._rightStick;
  69073. },
  69074. set: function (newValues) {
  69075. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69076. this._onrightstickchanged(newValues);
  69077. }
  69078. this._rightStick = newValues;
  69079. },
  69080. enumerable: true,
  69081. configurable: true
  69082. });
  69083. Gamepad.prototype.update = function () {
  69084. if (this._leftStick) {
  69085. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69086. if (this._invertLeftStickY) {
  69087. this.leftStick.y *= -1;
  69088. }
  69089. }
  69090. if (this._rightStick) {
  69091. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69092. }
  69093. };
  69094. Gamepad.prototype.dispose = function () {
  69095. };
  69096. Gamepad.GAMEPAD = 0;
  69097. Gamepad.GENERIC = 1;
  69098. Gamepad.XBOX = 2;
  69099. Gamepad.POSE_ENABLED = 3;
  69100. return Gamepad;
  69101. }());
  69102. BABYLON.Gamepad = Gamepad;
  69103. var GenericPad = /** @class */ (function (_super) {
  69104. __extends(GenericPad, _super);
  69105. function GenericPad(id, index, browserGamepad) {
  69106. var _this = _super.call(this, id, index, browserGamepad) || this;
  69107. _this.onButtonDownObservable = new BABYLON.Observable();
  69108. _this.onButtonUpObservable = new BABYLON.Observable();
  69109. _this.type = Gamepad.GENERIC;
  69110. _this._buttons = new Array(browserGamepad.buttons.length);
  69111. return _this;
  69112. }
  69113. GenericPad.prototype.onbuttondown = function (callback) {
  69114. this._onbuttondown = callback;
  69115. };
  69116. GenericPad.prototype.onbuttonup = function (callback) {
  69117. this._onbuttonup = callback;
  69118. };
  69119. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  69120. if (newValue !== currentValue) {
  69121. if (newValue === 1) {
  69122. if (this._onbuttondown) {
  69123. this._onbuttondown(buttonIndex);
  69124. }
  69125. this.onButtonDownObservable.notifyObservers(buttonIndex);
  69126. }
  69127. if (newValue === 0) {
  69128. if (this._onbuttonup) {
  69129. this._onbuttonup(buttonIndex);
  69130. }
  69131. this.onButtonUpObservable.notifyObservers(buttonIndex);
  69132. }
  69133. }
  69134. return newValue;
  69135. };
  69136. GenericPad.prototype.update = function () {
  69137. _super.prototype.update.call(this);
  69138. for (var index = 0; index < this._buttons.length; index++) {
  69139. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  69140. }
  69141. };
  69142. GenericPad.prototype.dispose = function () {
  69143. _super.prototype.dispose.call(this);
  69144. this.onButtonDownObservable.clear();
  69145. this.onButtonUpObservable.clear();
  69146. };
  69147. return GenericPad;
  69148. }(Gamepad));
  69149. BABYLON.GenericPad = GenericPad;
  69150. })(BABYLON || (BABYLON = {}));
  69151. //# sourceMappingURL=babylon.gamepad.js.map
  69152. "use strict";
  69153. var BABYLON;
  69154. (function (BABYLON) {
  69155. var Xbox360Button;
  69156. (function (Xbox360Button) {
  69157. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  69158. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  69159. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  69160. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  69161. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  69162. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  69163. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  69164. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  69165. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  69166. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  69167. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  69168. var Xbox360Dpad;
  69169. (function (Xbox360Dpad) {
  69170. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  69171. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  69172. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  69173. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  69174. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  69175. var Xbox360Pad = /** @class */ (function (_super) {
  69176. __extends(Xbox360Pad, _super);
  69177. function Xbox360Pad(id, index, gamepad, xboxOne) {
  69178. if (xboxOne === void 0) { xboxOne = false; }
  69179. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  69180. _this._leftTrigger = 0;
  69181. _this._rightTrigger = 0;
  69182. _this.onButtonDownObservable = new BABYLON.Observable();
  69183. _this.onButtonUpObservable = new BABYLON.Observable();
  69184. _this.onPadDownObservable = new BABYLON.Observable();
  69185. _this.onPadUpObservable = new BABYLON.Observable();
  69186. _this._buttonA = 0;
  69187. _this._buttonB = 0;
  69188. _this._buttonX = 0;
  69189. _this._buttonY = 0;
  69190. _this._buttonBack = 0;
  69191. _this._buttonStart = 0;
  69192. _this._buttonLB = 0;
  69193. _this._buttonRB = 0;
  69194. _this._buttonLeftStick = 0;
  69195. _this._buttonRightStick = 0;
  69196. _this._dPadUp = 0;
  69197. _this._dPadDown = 0;
  69198. _this._dPadLeft = 0;
  69199. _this._dPadRight = 0;
  69200. _this._isXboxOnePad = false;
  69201. _this.type = BABYLON.Gamepad.XBOX;
  69202. _this._isXboxOnePad = xboxOne;
  69203. return _this;
  69204. }
  69205. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  69206. this._onlefttriggerchanged = callback;
  69207. };
  69208. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  69209. this._onrighttriggerchanged = callback;
  69210. };
  69211. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  69212. get: function () {
  69213. return this._leftTrigger;
  69214. },
  69215. set: function (newValue) {
  69216. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  69217. this._onlefttriggerchanged(newValue);
  69218. }
  69219. this._leftTrigger = newValue;
  69220. },
  69221. enumerable: true,
  69222. configurable: true
  69223. });
  69224. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  69225. get: function () {
  69226. return this._rightTrigger;
  69227. },
  69228. set: function (newValue) {
  69229. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  69230. this._onrighttriggerchanged(newValue);
  69231. }
  69232. this._rightTrigger = newValue;
  69233. },
  69234. enumerable: true,
  69235. configurable: true
  69236. });
  69237. Xbox360Pad.prototype.onbuttondown = function (callback) {
  69238. this._onbuttondown = callback;
  69239. };
  69240. Xbox360Pad.prototype.onbuttonup = function (callback) {
  69241. this._onbuttonup = callback;
  69242. };
  69243. Xbox360Pad.prototype.ondpaddown = function (callback) {
  69244. this._ondpaddown = callback;
  69245. };
  69246. Xbox360Pad.prototype.ondpadup = function (callback) {
  69247. this._ondpadup = callback;
  69248. };
  69249. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  69250. if (newValue !== currentValue) {
  69251. if (newValue === 1) {
  69252. if (this._onbuttondown) {
  69253. this._onbuttondown(buttonType);
  69254. }
  69255. this.onButtonDownObservable.notifyObservers(buttonType);
  69256. }
  69257. if (newValue === 0) {
  69258. if (this._onbuttonup) {
  69259. this._onbuttonup(buttonType);
  69260. }
  69261. this.onButtonUpObservable.notifyObservers(buttonType);
  69262. }
  69263. }
  69264. return newValue;
  69265. };
  69266. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  69267. if (newValue !== currentValue) {
  69268. if (newValue === 1) {
  69269. if (this._ondpaddown) {
  69270. this._ondpaddown(buttonType);
  69271. }
  69272. this.onPadDownObservable.notifyObservers(buttonType);
  69273. }
  69274. if (newValue === 0) {
  69275. if (this._ondpadup) {
  69276. this._ondpadup(buttonType);
  69277. }
  69278. this.onPadUpObservable.notifyObservers(buttonType);
  69279. }
  69280. }
  69281. return newValue;
  69282. };
  69283. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  69284. get: function () {
  69285. return this._buttonA;
  69286. },
  69287. set: function (value) {
  69288. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  69289. },
  69290. enumerable: true,
  69291. configurable: true
  69292. });
  69293. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  69294. get: function () {
  69295. return this._buttonB;
  69296. },
  69297. set: function (value) {
  69298. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  69299. },
  69300. enumerable: true,
  69301. configurable: true
  69302. });
  69303. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  69304. get: function () {
  69305. return this._buttonX;
  69306. },
  69307. set: function (value) {
  69308. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  69309. },
  69310. enumerable: true,
  69311. configurable: true
  69312. });
  69313. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  69314. get: function () {
  69315. return this._buttonY;
  69316. },
  69317. set: function (value) {
  69318. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  69319. },
  69320. enumerable: true,
  69321. configurable: true
  69322. });
  69323. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  69324. get: function () {
  69325. return this._buttonStart;
  69326. },
  69327. set: function (value) {
  69328. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  69329. },
  69330. enumerable: true,
  69331. configurable: true
  69332. });
  69333. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  69334. get: function () {
  69335. return this._buttonBack;
  69336. },
  69337. set: function (value) {
  69338. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  69339. },
  69340. enumerable: true,
  69341. configurable: true
  69342. });
  69343. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  69344. get: function () {
  69345. return this._buttonLB;
  69346. },
  69347. set: function (value) {
  69348. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  69349. },
  69350. enumerable: true,
  69351. configurable: true
  69352. });
  69353. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  69354. get: function () {
  69355. return this._buttonRB;
  69356. },
  69357. set: function (value) {
  69358. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  69359. },
  69360. enumerable: true,
  69361. configurable: true
  69362. });
  69363. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  69364. get: function () {
  69365. return this._buttonLeftStick;
  69366. },
  69367. set: function (value) {
  69368. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  69369. },
  69370. enumerable: true,
  69371. configurable: true
  69372. });
  69373. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  69374. get: function () {
  69375. return this._buttonRightStick;
  69376. },
  69377. set: function (value) {
  69378. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  69379. },
  69380. enumerable: true,
  69381. configurable: true
  69382. });
  69383. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  69384. get: function () {
  69385. return this._dPadUp;
  69386. },
  69387. set: function (value) {
  69388. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  69389. },
  69390. enumerable: true,
  69391. configurable: true
  69392. });
  69393. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  69394. get: function () {
  69395. return this._dPadDown;
  69396. },
  69397. set: function (value) {
  69398. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  69399. },
  69400. enumerable: true,
  69401. configurable: true
  69402. });
  69403. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  69404. get: function () {
  69405. return this._dPadLeft;
  69406. },
  69407. set: function (value) {
  69408. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  69409. },
  69410. enumerable: true,
  69411. configurable: true
  69412. });
  69413. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  69414. get: function () {
  69415. return this._dPadRight;
  69416. },
  69417. set: function (value) {
  69418. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  69419. },
  69420. enumerable: true,
  69421. configurable: true
  69422. });
  69423. Xbox360Pad.prototype.update = function () {
  69424. _super.prototype.update.call(this);
  69425. if (this._isXboxOnePad) {
  69426. this.buttonA = this.browserGamepad.buttons[0].value;
  69427. this.buttonB = this.browserGamepad.buttons[1].value;
  69428. this.buttonX = this.browserGamepad.buttons[2].value;
  69429. this.buttonY = this.browserGamepad.buttons[3].value;
  69430. this.buttonLB = this.browserGamepad.buttons[4].value;
  69431. this.buttonRB = this.browserGamepad.buttons[5].value;
  69432. this.leftTrigger = this.browserGamepad.axes[2];
  69433. this.rightTrigger = this.browserGamepad.axes[5];
  69434. this.buttonBack = this.browserGamepad.buttons[9].value;
  69435. this.buttonStart = this.browserGamepad.buttons[8].value;
  69436. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  69437. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  69438. this.dPadUp = this.browserGamepad.buttons[11].value;
  69439. this.dPadDown = this.browserGamepad.buttons[12].value;
  69440. this.dPadLeft = this.browserGamepad.buttons[13].value;
  69441. this.dPadRight = this.browserGamepad.buttons[14].value;
  69442. }
  69443. else {
  69444. this.buttonA = this.browserGamepad.buttons[0].value;
  69445. this.buttonB = this.browserGamepad.buttons[1].value;
  69446. this.buttonX = this.browserGamepad.buttons[2].value;
  69447. this.buttonY = this.browserGamepad.buttons[3].value;
  69448. this.buttonLB = this.browserGamepad.buttons[4].value;
  69449. this.buttonRB = this.browserGamepad.buttons[5].value;
  69450. this.leftTrigger = this.browserGamepad.buttons[6].value;
  69451. this.rightTrigger = this.browserGamepad.buttons[7].value;
  69452. this.buttonBack = this.browserGamepad.buttons[8].value;
  69453. this.buttonStart = this.browserGamepad.buttons[9].value;
  69454. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  69455. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  69456. this.dPadUp = this.browserGamepad.buttons[12].value;
  69457. this.dPadDown = this.browserGamepad.buttons[13].value;
  69458. this.dPadLeft = this.browserGamepad.buttons[14].value;
  69459. this.dPadRight = this.browserGamepad.buttons[15].value;
  69460. }
  69461. };
  69462. Xbox360Pad.prototype.dispose = function () {
  69463. _super.prototype.dispose.call(this);
  69464. this.onButtonDownObservable.clear();
  69465. this.onButtonUpObservable.clear();
  69466. this.onPadDownObservable.clear();
  69467. this.onPadUpObservable.clear();
  69468. };
  69469. return Xbox360Pad;
  69470. }(BABYLON.Gamepad));
  69471. BABYLON.Xbox360Pad = Xbox360Pad;
  69472. })(BABYLON || (BABYLON = {}));
  69473. //# sourceMappingURL=babylon.xboxGamepad.js.map
  69474. "use strict";
  69475. var BABYLON;
  69476. (function (BABYLON) {
  69477. /**
  69478. * Defines the types of pose enabled controllers that are supported
  69479. */
  69480. var PoseEnabledControllerType;
  69481. (function (PoseEnabledControllerType) {
  69482. /**
  69483. * HTC Vive
  69484. */
  69485. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  69486. /**
  69487. * Oculus Rift
  69488. */
  69489. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  69490. /**
  69491. * Windows mixed reality
  69492. */
  69493. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  69494. /**
  69495. * Samsung gear VR
  69496. */
  69497. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  69498. /**
  69499. * Google Daydream
  69500. */
  69501. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  69502. /**
  69503. * Generic
  69504. */
  69505. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  69506. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  69507. /**
  69508. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69509. */
  69510. var PoseEnabledControllerHelper = /** @class */ (function () {
  69511. function PoseEnabledControllerHelper() {
  69512. }
  69513. /**
  69514. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69515. * @param vrGamepad the gamepad to initialized
  69516. * @returns a vr controller of the type the gamepad identified as
  69517. */
  69518. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  69519. // Oculus Touch
  69520. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  69521. return new BABYLON.OculusTouchController(vrGamepad);
  69522. }
  69523. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  69524. return new BABYLON.WindowsMotionController(vrGamepad);
  69525. }
  69526. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  69527. return new BABYLON.ViveController(vrGamepad);
  69528. }
  69529. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  69530. return new BABYLON.GearVRController(vrGamepad);
  69531. }
  69532. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  69533. return new BABYLON.DaydreamController(vrGamepad);
  69534. }
  69535. else {
  69536. return new BABYLON.GenericController(vrGamepad);
  69537. }
  69538. };
  69539. return PoseEnabledControllerHelper;
  69540. }());
  69541. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  69542. /**
  69543. * Defines the PoseEnabledController object that contains state of a vr capable controller
  69544. */
  69545. var PoseEnabledController = /** @class */ (function (_super) {
  69546. __extends(PoseEnabledController, _super);
  69547. /**
  69548. * Creates a new PoseEnabledController from a gamepad
  69549. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  69550. */
  69551. function PoseEnabledController(browserGamepad) {
  69552. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  69553. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  69554. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  69555. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  69556. /**
  69557. * The device position in babylon space
  69558. */
  69559. _this.devicePosition = BABYLON.Vector3.Zero();
  69560. /**
  69561. * The device rotation in babylon space
  69562. */
  69563. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69564. /**
  69565. * The scale factor of the device in babylon space
  69566. */
  69567. _this.deviceScaleFactor = 1;
  69568. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  69569. /**
  69570. * Internal, matrix used to convert room space to babylon space
  69571. */
  69572. _this._deviceToWorld = BABYLON.Matrix.Identity();
  69573. /**
  69574. * Node to be used when casting a ray from the controller
  69575. */
  69576. _this._pointingPoseNode = null;
  69577. _this._workingMatrix = BABYLON.Matrix.Identity();
  69578. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  69579. _this.controllerType = PoseEnabledControllerType.GENERIC;
  69580. _this.position = BABYLON.Vector3.Zero();
  69581. _this.rotationQuaternion = new BABYLON.Quaternion();
  69582. _this._calculatedPosition = BABYLON.Vector3.Zero();
  69583. _this._calculatedRotation = new BABYLON.Quaternion();
  69584. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  69585. return _this;
  69586. }
  69587. /**
  69588. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  69589. */
  69590. PoseEnabledController.prototype.update = function () {
  69591. _super.prototype.update.call(this);
  69592. var pose = this.browserGamepad.pose;
  69593. this.updateFromDevice(pose);
  69594. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  69595. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  69596. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  69597. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  69598. if (this._mesh) {
  69599. this._mesh.position.copyFrom(this.devicePosition);
  69600. if (this._mesh.rotationQuaternion) {
  69601. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69602. }
  69603. }
  69604. };
  69605. /**
  69606. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  69607. * @param poseData raw pose fromthe device
  69608. */
  69609. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  69610. if (poseData) {
  69611. this.rawPose = poseData;
  69612. if (poseData.position) {
  69613. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  69614. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  69615. this._deviceRoomPosition.z *= -1;
  69616. }
  69617. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  69618. this._calculatedPosition.addInPlace(this.position);
  69619. }
  69620. var pose = this.rawPose;
  69621. if (poseData.orientation && pose.orientation) {
  69622. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  69623. if (this._mesh) {
  69624. if (this._mesh.getScene().useRightHandedSystem) {
  69625. this._deviceRoomRotationQuaternion.z *= -1;
  69626. this._deviceRoomRotationQuaternion.w *= -1;
  69627. }
  69628. else {
  69629. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  69630. }
  69631. }
  69632. // if the camera is set, rotate to the camera's rotation
  69633. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  69634. }
  69635. }
  69636. };
  69637. /**
  69638. * Attaches a mesh to the controller
  69639. * @param mesh the mesh to be attached
  69640. */
  69641. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  69642. if (this._mesh) {
  69643. this._mesh.parent = null;
  69644. }
  69645. this._mesh = mesh;
  69646. if (this._poseControlledCamera) {
  69647. this._mesh.parent = this._poseControlledCamera;
  69648. }
  69649. if (!this._mesh.rotationQuaternion) {
  69650. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  69651. }
  69652. };
  69653. /**
  69654. * Attaches the controllers mesh to a camera
  69655. * @param camera the camera the mesh should be attached to
  69656. */
  69657. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  69658. this._poseControlledCamera = camera;
  69659. if (this._mesh) {
  69660. this._mesh.parent = this._poseControlledCamera;
  69661. }
  69662. };
  69663. /**
  69664. * Disposes of the controller
  69665. */
  69666. PoseEnabledController.prototype.dispose = function () {
  69667. if (this._mesh) {
  69668. this._mesh.dispose();
  69669. }
  69670. this._mesh = null;
  69671. _super.prototype.dispose.call(this);
  69672. };
  69673. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  69674. /**
  69675. * The mesh that is attached to the controller
  69676. */
  69677. get: function () {
  69678. return this._mesh;
  69679. },
  69680. enumerable: true,
  69681. configurable: true
  69682. });
  69683. /**
  69684. * Gets the ray of the controller in the direction the controller is pointing
  69685. * @param length the length the resulting ray should be
  69686. * @returns a ray in the direction the controller is pointing
  69687. */
  69688. PoseEnabledController.prototype.getForwardRay = function (length) {
  69689. if (length === void 0) { length = 100; }
  69690. if (!this.mesh) {
  69691. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  69692. }
  69693. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  69694. var origin = m.getTranslation();
  69695. var forward = new BABYLON.Vector3(0, 0, -1);
  69696. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69697. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69698. return new BABYLON.Ray(origin, direction, length);
  69699. };
  69700. /**
  69701. * Name of the child mesh that can be used to cast a ray from the controller
  69702. */
  69703. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  69704. return PoseEnabledController;
  69705. }(BABYLON.Gamepad));
  69706. BABYLON.PoseEnabledController = PoseEnabledController;
  69707. })(BABYLON || (BABYLON = {}));
  69708. //# sourceMappingURL=babylon.poseEnabledController.js.map
  69709. "use strict";
  69710. var BABYLON;
  69711. (function (BABYLON) {
  69712. /**
  69713. * Defines the WebVRController object that represents controllers tracked in 3D space
  69714. */
  69715. var WebVRController = /** @class */ (function (_super) {
  69716. __extends(WebVRController, _super);
  69717. /**
  69718. * Creates a new WebVRController from a gamepad
  69719. * @param vrGamepad the gamepad that the WebVRController should be created from
  69720. */
  69721. function WebVRController(vrGamepad) {
  69722. var _this = _super.call(this, vrGamepad) || this;
  69723. // Observables
  69724. /**
  69725. * Fired when the trigger state has changed
  69726. */
  69727. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  69728. /**
  69729. * Fired when the main button state has changed
  69730. */
  69731. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  69732. /**
  69733. * Fired when the secondary button state has changed
  69734. */
  69735. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  69736. /**
  69737. * Fired when the pad state has changed
  69738. */
  69739. _this.onPadStateChangedObservable = new BABYLON.Observable();
  69740. /**
  69741. * Fired when controllers stick values have changed
  69742. */
  69743. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  69744. /**
  69745. * X and Y axis corrisponding to the controllers joystick
  69746. */
  69747. _this.pad = { x: 0, y: 0 };
  69748. // avoid GC, store state in a tmp object
  69749. _this._changes = {
  69750. pressChanged: false,
  69751. touchChanged: false,
  69752. valueChanged: false,
  69753. changed: false
  69754. };
  69755. _this._buttons = new Array(vrGamepad.buttons.length);
  69756. _this.hand = vrGamepad.hand;
  69757. return _this;
  69758. }
  69759. /**
  69760. * Fired when a controller button's state has changed
  69761. * @param callback the callback containing the button that was modified
  69762. */
  69763. WebVRController.prototype.onButtonStateChange = function (callback) {
  69764. this._onButtonStateChange = callback;
  69765. };
  69766. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  69767. /**
  69768. * The default controller model for the controller
  69769. */
  69770. get: function () {
  69771. return this._defaultModel;
  69772. },
  69773. enumerable: true,
  69774. configurable: true
  69775. });
  69776. /**
  69777. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  69778. */
  69779. WebVRController.prototype.update = function () {
  69780. _super.prototype.update.call(this);
  69781. for (var index = 0; index < this._buttons.length; index++) {
  69782. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  69783. }
  69784. ;
  69785. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  69786. this.pad.x = this.leftStick.x;
  69787. this.pad.y = this.leftStick.y;
  69788. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  69789. }
  69790. };
  69791. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  69792. if (!newState) {
  69793. newState = {
  69794. pressed: false,
  69795. touched: false,
  69796. value: 0
  69797. };
  69798. }
  69799. if (!currentState) {
  69800. this._buttons[buttonIndex] = {
  69801. pressed: newState.pressed,
  69802. touched: newState.touched,
  69803. value: newState.value
  69804. };
  69805. return;
  69806. }
  69807. this._checkChanges(newState, currentState);
  69808. if (this._changes.changed) {
  69809. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  69810. this._handleButtonChange(buttonIndex, newState, this._changes);
  69811. }
  69812. this._buttons[buttonIndex].pressed = newState.pressed;
  69813. this._buttons[buttonIndex].touched = newState.touched;
  69814. // oculus triggers are never 0, thou not touched.
  69815. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  69816. };
  69817. WebVRController.prototype._checkChanges = function (newState, currentState) {
  69818. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  69819. this._changes.touchChanged = newState.touched !== currentState.touched;
  69820. this._changes.valueChanged = newState.value !== currentState.value;
  69821. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  69822. return this._changes;
  69823. };
  69824. /**
  69825. * Disposes of th webVRCOntroller
  69826. */
  69827. WebVRController.prototype.dispose = function () {
  69828. _super.prototype.dispose.call(this);
  69829. this.onTriggerStateChangedObservable.clear();
  69830. this.onMainButtonStateChangedObservable.clear();
  69831. this.onSecondaryButtonStateChangedObservable.clear();
  69832. this.onPadStateChangedObservable.clear();
  69833. this.onPadValuesChangedObservable.clear();
  69834. };
  69835. return WebVRController;
  69836. }(BABYLON.PoseEnabledController));
  69837. BABYLON.WebVRController = WebVRController;
  69838. })(BABYLON || (BABYLON = {}));
  69839. //# sourceMappingURL=babylon.webVRController.js.map
  69840. "use strict";
  69841. var BABYLON;
  69842. (function (BABYLON) {
  69843. /**
  69844. * Oculus Touch Controller
  69845. */
  69846. var OculusTouchController = /** @class */ (function (_super) {
  69847. __extends(OculusTouchController, _super);
  69848. /**
  69849. * Creates a new OculusTouchController from a gamepad
  69850. * @param vrGamepad the gamepad that the controller should be created from
  69851. */
  69852. function OculusTouchController(vrGamepad) {
  69853. var _this = _super.call(this, vrGamepad) || this;
  69854. /**
  69855. * Fired when the secondary trigger on this controller is modified
  69856. */
  69857. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  69858. /**
  69859. * Fired when the thumb rest on this controller is modified
  69860. */
  69861. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  69862. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  69863. return _this;
  69864. }
  69865. /**
  69866. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69867. * @param scene scene in which to add meshes
  69868. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69869. */
  69870. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69871. var _this = this;
  69872. var meshName;
  69873. // Hand
  69874. if (this.hand === 'left') {
  69875. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  69876. }
  69877. else {
  69878. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  69879. }
  69880. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  69881. /*
  69882. Parent Mesh name: oculus_touch_left
  69883. - body
  69884. - trigger
  69885. - thumbstick
  69886. - grip
  69887. - button_y
  69888. - button_x
  69889. - button_enter
  69890. */
  69891. _this._defaultModel = newMeshes[1];
  69892. _this.attachToMesh(_this._defaultModel);
  69893. if (meshLoaded) {
  69894. meshLoaded(_this._defaultModel);
  69895. }
  69896. });
  69897. };
  69898. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  69899. /**
  69900. * Fired when the A button on this controller is modified
  69901. */
  69902. get: function () {
  69903. if (this.hand === 'right') {
  69904. return this.onMainButtonStateChangedObservable;
  69905. }
  69906. else {
  69907. throw new Error('No A button on left hand');
  69908. }
  69909. },
  69910. enumerable: true,
  69911. configurable: true
  69912. });
  69913. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  69914. /**
  69915. * Fired when the B button on this controller is modified
  69916. */
  69917. get: function () {
  69918. if (this.hand === 'right') {
  69919. return this.onSecondaryButtonStateChangedObservable;
  69920. }
  69921. else {
  69922. throw new Error('No B button on left hand');
  69923. }
  69924. },
  69925. enumerable: true,
  69926. configurable: true
  69927. });
  69928. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  69929. /**
  69930. * Fired when the X button on this controller is modified
  69931. */
  69932. get: function () {
  69933. if (this.hand === 'left') {
  69934. return this.onMainButtonStateChangedObservable;
  69935. }
  69936. else {
  69937. throw new Error('No X button on right hand');
  69938. }
  69939. },
  69940. enumerable: true,
  69941. configurable: true
  69942. });
  69943. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  69944. /**
  69945. * Fired when the Y button on this controller is modified
  69946. */
  69947. get: function () {
  69948. if (this.hand === 'left') {
  69949. return this.onSecondaryButtonStateChangedObservable;
  69950. }
  69951. else {
  69952. throw new Error('No Y button on right hand');
  69953. }
  69954. },
  69955. enumerable: true,
  69956. configurable: true
  69957. });
  69958. /**
  69959. * Called once for each button that changed state since the last frame
  69960. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  69961. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  69962. * 2) secondary trigger (same)
  69963. * 3) A (right) X (left), touch, pressed = value
  69964. * 4) B / Y
  69965. * 5) thumb rest
  69966. * @param buttonIdx Which button index changed
  69967. * @param state New state of the button
  69968. * @param changes Which properties on the state changed since last frame
  69969. */
  69970. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69971. var notifyObject = state; //{ state: state, changes: changes };
  69972. var triggerDirection = this.hand === 'right' ? -1 : 1;
  69973. switch (buttonIdx) {
  69974. case 0:
  69975. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69976. return;
  69977. case 1:// index trigger
  69978. if (this._defaultModel) {
  69979. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  69980. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  69981. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  69982. }
  69983. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69984. return;
  69985. case 2:// secondary trigger
  69986. if (this._defaultModel) {
  69987. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  69988. }
  69989. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  69990. return;
  69991. case 3:
  69992. if (this._defaultModel) {
  69993. if (notifyObject.pressed) {
  69994. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  69995. }
  69996. else {
  69997. (this._defaultModel.getChildren()[1]).position.y = 0;
  69998. }
  69999. }
  70000. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70001. return;
  70002. case 4:
  70003. if (this._defaultModel) {
  70004. if (notifyObject.pressed) {
  70005. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70006. }
  70007. else {
  70008. (this._defaultModel.getChildren()[2]).position.y = 0;
  70009. }
  70010. }
  70011. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70012. return;
  70013. case 5:
  70014. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  70015. return;
  70016. }
  70017. };
  70018. /**
  70019. * Base Url for the controller model.
  70020. */
  70021. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  70022. /**
  70023. * File name for the left controller model.
  70024. */
  70025. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  70026. /**
  70027. * File name for the right controller model.
  70028. */
  70029. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  70030. return OculusTouchController;
  70031. }(BABYLON.WebVRController));
  70032. BABYLON.OculusTouchController = OculusTouchController;
  70033. })(BABYLON || (BABYLON = {}));
  70034. //# sourceMappingURL=babylon.oculusTouchController.js.map
  70035. "use strict";
  70036. var BABYLON;
  70037. (function (BABYLON) {
  70038. /**
  70039. * Vive Controller
  70040. */
  70041. var ViveController = /** @class */ (function (_super) {
  70042. __extends(ViveController, _super);
  70043. /**
  70044. * Creates a new ViveController from a gamepad
  70045. * @param vrGamepad the gamepad that the controller should be created from
  70046. */
  70047. function ViveController(vrGamepad) {
  70048. var _this = _super.call(this, vrGamepad) || this;
  70049. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  70050. _this._invertLeftStickY = true;
  70051. return _this;
  70052. }
  70053. /**
  70054. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70055. * @param scene scene in which to add meshes
  70056. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70057. */
  70058. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70059. var _this = this;
  70060. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  70061. /*
  70062. Parent Mesh name: ViveWand
  70063. - body
  70064. - r_gripper
  70065. - l_gripper
  70066. - menu_button
  70067. - system_button
  70068. - trackpad
  70069. - trigger
  70070. - LED
  70071. */
  70072. _this._defaultModel = newMeshes[1];
  70073. _this.attachToMesh(_this._defaultModel);
  70074. if (meshLoaded) {
  70075. meshLoaded(_this._defaultModel);
  70076. }
  70077. });
  70078. };
  70079. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  70080. /**
  70081. * Fired when the left button on this controller is modified
  70082. */
  70083. get: function () {
  70084. return this.onMainButtonStateChangedObservable;
  70085. },
  70086. enumerable: true,
  70087. configurable: true
  70088. });
  70089. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  70090. /**
  70091. * Fired when the right button on this controller is modified
  70092. */
  70093. get: function () {
  70094. return this.onMainButtonStateChangedObservable;
  70095. },
  70096. enumerable: true,
  70097. configurable: true
  70098. });
  70099. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  70100. /**
  70101. * Fired when the menu button on this controller is modified
  70102. */
  70103. get: function () {
  70104. return this.onSecondaryButtonStateChangedObservable;
  70105. },
  70106. enumerable: true,
  70107. configurable: true
  70108. });
  70109. /**
  70110. * Called once for each button that changed state since the last frame
  70111. * Vive mapping:
  70112. * 0: touchpad
  70113. * 1: trigger
  70114. * 2: left AND right buttons
  70115. * 3: menu button
  70116. * @param buttonIdx Which button index changed
  70117. * @param state New state of the button
  70118. * @param changes Which properties on the state changed since last frame
  70119. */
  70120. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70121. var notifyObject = state; //{ state: state, changes: changes };
  70122. switch (buttonIdx) {
  70123. case 0:
  70124. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70125. return;
  70126. case 1:// index trigger
  70127. if (this._defaultModel) {
  70128. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  70129. }
  70130. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70131. return;
  70132. case 2:// left AND right button
  70133. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70134. return;
  70135. case 3:
  70136. if (this._defaultModel) {
  70137. if (notifyObject.pressed) {
  70138. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70139. }
  70140. else {
  70141. (this._defaultModel.getChildren()[2]).position.y = 0;
  70142. }
  70143. }
  70144. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70145. return;
  70146. }
  70147. };
  70148. /**
  70149. * Base Url for the controller model.
  70150. */
  70151. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  70152. /**
  70153. * File name for the controller model.
  70154. */
  70155. ViveController.MODEL_FILENAME = 'wand.babylon';
  70156. return ViveController;
  70157. }(BABYLON.WebVRController));
  70158. BABYLON.ViveController = ViveController;
  70159. })(BABYLON || (BABYLON = {}));
  70160. //# sourceMappingURL=babylon.viveController.js.map
  70161. "use strict";
  70162. var BABYLON;
  70163. (function (BABYLON) {
  70164. /**
  70165. * Generic Controller
  70166. */
  70167. var GenericController = /** @class */ (function (_super) {
  70168. __extends(GenericController, _super);
  70169. /**
  70170. * Creates a new GenericController from a gamepad
  70171. * @param vrGamepad the gamepad that the controller should be created from
  70172. */
  70173. function GenericController(vrGamepad) {
  70174. return _super.call(this, vrGamepad) || this;
  70175. }
  70176. /**
  70177. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70178. * @param scene scene in which to add meshes
  70179. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70180. */
  70181. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70182. var _this = this;
  70183. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  70184. _this._defaultModel = newMeshes[1];
  70185. _this.attachToMesh(_this._defaultModel);
  70186. if (meshLoaded) {
  70187. meshLoaded(_this._defaultModel);
  70188. }
  70189. });
  70190. };
  70191. /**
  70192. * Called once for each button that changed state since the last frame
  70193. * @param buttonIdx Which button index changed
  70194. * @param state New state of the button
  70195. * @param changes Which properties on the state changed since last frame
  70196. */
  70197. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70198. console.log("Button id: " + buttonIdx + "state: ");
  70199. console.dir(state);
  70200. };
  70201. /**
  70202. * Base Url for the controller model.
  70203. */
  70204. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70205. /**
  70206. * File name for the controller model.
  70207. */
  70208. GenericController.MODEL_FILENAME = 'generic.babylon';
  70209. return GenericController;
  70210. }(BABYLON.WebVRController));
  70211. BABYLON.GenericController = GenericController;
  70212. })(BABYLON || (BABYLON = {}));
  70213. //# sourceMappingURL=babylon.genericController.js.map
  70214. "use strict";
  70215. var BABYLON;
  70216. (function (BABYLON) {
  70217. /**
  70218. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  70219. */
  70220. var LoadedMeshInfo = /** @class */ (function () {
  70221. function LoadedMeshInfo() {
  70222. /**
  70223. * Map of the button meshes contained in the controller
  70224. */
  70225. this.buttonMeshes = {};
  70226. /**
  70227. * Map of the axis meshes contained in the controller
  70228. */
  70229. this.axisMeshes = {};
  70230. }
  70231. return LoadedMeshInfo;
  70232. }());
  70233. /**
  70234. * Defines the WindowsMotionController object that the state of the windows motion controller
  70235. */
  70236. var WindowsMotionController = /** @class */ (function (_super) {
  70237. __extends(WindowsMotionController, _super);
  70238. /**
  70239. * Creates a new WindowsMotionController from a gamepad
  70240. * @param vrGamepad the gamepad that the controller should be created from
  70241. */
  70242. function WindowsMotionController(vrGamepad) {
  70243. var _this = _super.call(this, vrGamepad) || this;
  70244. _this._mapping = {
  70245. // Semantic button names
  70246. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  70247. // A mapping of the button name to glTF model node name
  70248. // that should be transformed by button value.
  70249. buttonMeshNames: {
  70250. 'trigger': 'SELECT',
  70251. 'menu': 'MENU',
  70252. 'grip': 'GRASP',
  70253. 'thumbstick': 'THUMBSTICK_PRESS',
  70254. 'trackpad': 'TOUCHPAD_PRESS'
  70255. },
  70256. // This mapping is used to translate from the Motion Controller to Babylon semantics
  70257. buttonObservableNames: {
  70258. 'trigger': 'onTriggerStateChangedObservable',
  70259. 'menu': 'onSecondaryButtonStateChangedObservable',
  70260. 'grip': 'onMainButtonStateChangedObservable',
  70261. 'thumbstick': 'onPadStateChangedObservable',
  70262. 'trackpad': 'onTrackpadChangedObservable'
  70263. },
  70264. // A mapping of the axis name to glTF model node name
  70265. // that should be transformed by axis value.
  70266. // This array mirrors the browserGamepad.axes array, such that
  70267. // the mesh corresponding to axis 0 is in this array index 0.
  70268. axisMeshNames: [
  70269. 'THUMBSTICK_X',
  70270. 'THUMBSTICK_Y',
  70271. 'TOUCHPAD_TOUCH_X',
  70272. 'TOUCHPAD_TOUCH_Y'
  70273. ],
  70274. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  70275. };
  70276. /**
  70277. * Fired when the trackpad on this controller is clicked
  70278. */
  70279. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  70280. /**
  70281. * Fired when the trackpad on this controller is modified
  70282. */
  70283. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  70284. /**
  70285. * The current x and y values of this controller's trackpad
  70286. */
  70287. _this.trackpad = { x: 0, y: 0 };
  70288. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  70289. _this._loadedMeshInfo = null;
  70290. return _this;
  70291. }
  70292. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  70293. /**
  70294. * Fired when the trigger on this controller is modified
  70295. */
  70296. get: function () {
  70297. return this.onTriggerStateChangedObservable;
  70298. },
  70299. enumerable: true,
  70300. configurable: true
  70301. });
  70302. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  70303. /**
  70304. * Fired when the menu button on this controller is modified
  70305. */
  70306. get: function () {
  70307. return this.onSecondaryButtonStateChangedObservable;
  70308. },
  70309. enumerable: true,
  70310. configurable: true
  70311. });
  70312. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  70313. /**
  70314. * Fired when the grip button on this controller is modified
  70315. */
  70316. get: function () {
  70317. return this.onMainButtonStateChangedObservable;
  70318. },
  70319. enumerable: true,
  70320. configurable: true
  70321. });
  70322. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  70323. /**
  70324. * Fired when the thumbstick button on this controller is modified
  70325. */
  70326. get: function () {
  70327. return this.onPadStateChangedObservable;
  70328. },
  70329. enumerable: true,
  70330. configurable: true
  70331. });
  70332. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  70333. /**
  70334. * Fired when the touchpad button on this controller is modified
  70335. */
  70336. get: function () {
  70337. return this.onTrackpadChangedObservable;
  70338. },
  70339. enumerable: true,
  70340. configurable: true
  70341. });
  70342. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  70343. /**
  70344. * Fired when the touchpad values on this controller are modified
  70345. */
  70346. get: function () {
  70347. return this.onTrackpadValuesChangedObservable;
  70348. },
  70349. enumerable: true,
  70350. configurable: true
  70351. });
  70352. /**
  70353. * Called once per frame by the engine.
  70354. */
  70355. WindowsMotionController.prototype.update = function () {
  70356. _super.prototype.update.call(this);
  70357. if (this.browserGamepad.axes) {
  70358. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  70359. this.trackpad.x = this.browserGamepad["axes"][2];
  70360. this.trackpad.y = this.browserGamepad["axes"][3];
  70361. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  70362. }
  70363. // Only need to animate axes if there is a loaded mesh
  70364. if (this._loadedMeshInfo) {
  70365. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  70366. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  70367. }
  70368. }
  70369. }
  70370. };
  70371. /**
  70372. * Called once for each button that changed state since the last frame
  70373. * @param buttonIdx Which button index changed
  70374. * @param state New state of the button
  70375. * @param changes Which properties on the state changed since last frame
  70376. */
  70377. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70378. var buttonName = this._mapping.buttons[buttonIdx];
  70379. if (!buttonName) {
  70380. return;
  70381. }
  70382. // Only emit events for buttons that we know how to map from index to name
  70383. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  70384. if (observable) {
  70385. observable.notifyObservers(state);
  70386. }
  70387. this._lerpButtonTransform(buttonName, state.value);
  70388. };
  70389. /**
  70390. * Moves the buttons on the controller mesh based on their current state
  70391. * @param buttonName the name of the button to move
  70392. * @param buttonValue the value of the button which determines the buttons new position
  70393. */
  70394. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  70395. // If there is no loaded mesh, there is nothing to transform.
  70396. if (!this._loadedMeshInfo) {
  70397. return;
  70398. }
  70399. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  70400. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70401. return;
  70402. }
  70403. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  70404. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  70405. };
  70406. /**
  70407. * Moves the axis on the controller mesh based on its current state
  70408. * @param axis the index of the axis
  70409. * @param axisValue the value of the axis which determines the meshes new position
  70410. * @ignore
  70411. */
  70412. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  70413. if (!this._loadedMeshInfo) {
  70414. return;
  70415. }
  70416. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  70417. if (!meshInfo) {
  70418. return;
  70419. }
  70420. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70421. return;
  70422. }
  70423. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  70424. var lerpValue = axisValue * 0.5 + 0.5;
  70425. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  70426. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  70427. };
  70428. /**
  70429. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70430. * @param scene scene in which to add meshes
  70431. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70432. */
  70433. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  70434. var _this = this;
  70435. if (forceDefault === void 0) { forceDefault = false; }
  70436. var path;
  70437. var filename;
  70438. // Checking if GLB loader is present
  70439. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  70440. // Determine the device specific folder based on the ID suffix
  70441. var device = 'default';
  70442. if (this.id && !forceDefault) {
  70443. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  70444. device = ((match && match[0]) || device);
  70445. }
  70446. // Hand
  70447. if (this.hand === 'left') {
  70448. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  70449. }
  70450. else {
  70451. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  70452. }
  70453. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  70454. }
  70455. else {
  70456. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  70457. path = BABYLON.GenericController.MODEL_BASE_URL;
  70458. filename = BABYLON.GenericController.MODEL_FILENAME;
  70459. }
  70460. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  70461. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  70462. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  70463. if (!_this._loadedMeshInfo) {
  70464. return;
  70465. }
  70466. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  70467. _this.attachToMesh(_this._defaultModel);
  70468. if (meshLoaded) {
  70469. meshLoaded(_this._defaultModel);
  70470. }
  70471. }, null, function (scene, message) {
  70472. BABYLON.Tools.Log(message);
  70473. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  70474. if (!forceDefault) {
  70475. _this.initControllerMesh(scene, meshLoaded, true);
  70476. }
  70477. });
  70478. };
  70479. /**
  70480. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  70481. * can be transformed by button presses and axes values, based on this._mapping.
  70482. *
  70483. * @param scene scene in which the meshes exist
  70484. * @param meshes list of meshes that make up the controller model to process
  70485. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  70486. */
  70487. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  70488. var loadedMeshInfo = null;
  70489. // Create a new mesh to contain the glTF hierarchy
  70490. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  70491. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  70492. var childMesh = null;
  70493. for (var i = 0; i < meshes.length; i++) {
  70494. var mesh = meshes[i];
  70495. if (!mesh.parent) {
  70496. // Exclude controller meshes from picking results
  70497. mesh.isPickable = false;
  70498. // Handle root node, attach to the new parentMesh
  70499. childMesh = mesh;
  70500. break;
  70501. }
  70502. }
  70503. if (childMesh) {
  70504. childMesh.setParent(parentMesh);
  70505. // Create our mesh info. Note that this method will always return non-null.
  70506. loadedMeshInfo = this.createMeshInfo(parentMesh);
  70507. }
  70508. else {
  70509. BABYLON.Tools.Warn('Could not find root node in model file.');
  70510. }
  70511. return loadedMeshInfo;
  70512. };
  70513. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  70514. var loadedMeshInfo = new LoadedMeshInfo();
  70515. var i;
  70516. loadedMeshInfo.rootNode = rootNode;
  70517. // Reset the caches
  70518. loadedMeshInfo.buttonMeshes = {};
  70519. loadedMeshInfo.axisMeshes = {};
  70520. // Button Meshes
  70521. for (i = 0; i < this._mapping.buttons.length; i++) {
  70522. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  70523. if (!buttonMeshName) {
  70524. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  70525. continue;
  70526. }
  70527. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  70528. if (!buttonMesh) {
  70529. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  70530. continue;
  70531. }
  70532. var buttonMeshInfo = {
  70533. index: i,
  70534. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  70535. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  70536. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  70537. };
  70538. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  70539. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  70540. }
  70541. else {
  70542. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  70543. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  70544. '(VALUE: ' + !!buttonMeshInfo.value +
  70545. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  70546. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  70547. ')');
  70548. }
  70549. }
  70550. // Axis Meshes
  70551. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  70552. var axisMeshName = this._mapping.axisMeshNames[i];
  70553. if (!axisMeshName) {
  70554. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  70555. continue;
  70556. }
  70557. var axisMesh = getChildByName(rootNode, axisMeshName);
  70558. if (!axisMesh) {
  70559. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  70560. continue;
  70561. }
  70562. var axisMeshInfo = {
  70563. index: i,
  70564. value: getImmediateChildByName(axisMesh, 'VALUE'),
  70565. min: getImmediateChildByName(axisMesh, 'MIN'),
  70566. max: getImmediateChildByName(axisMesh, 'MAX')
  70567. };
  70568. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  70569. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  70570. }
  70571. else {
  70572. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  70573. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  70574. '(VALUE: ' + !!axisMeshInfo.value +
  70575. ', MIN: ' + !!axisMeshInfo.min +
  70576. ', MAX:' + !!axisMeshInfo.max +
  70577. ')');
  70578. }
  70579. }
  70580. // Pointing Ray
  70581. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  70582. if (!loadedMeshInfo.pointingPoseNode) {
  70583. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  70584. }
  70585. return loadedMeshInfo;
  70586. // Look through all children recursively. This will return null if no mesh exists with the given name.
  70587. function getChildByName(node, name) {
  70588. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  70589. }
  70590. // Look through only immediate children. This will return null if no mesh exists with the given name.
  70591. function getImmediateChildByName(node, name) {
  70592. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  70593. }
  70594. };
  70595. /**
  70596. * Gets the ray of the controller in the direction the controller is pointing
  70597. * @param length the length the resulting ray should be
  70598. * @returns a ray in the direction the controller is pointing
  70599. */
  70600. WindowsMotionController.prototype.getForwardRay = function (length) {
  70601. if (length === void 0) { length = 100; }
  70602. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  70603. return _super.prototype.getForwardRay.call(this, length);
  70604. }
  70605. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  70606. var origin = m.getTranslation();
  70607. var forward = new BABYLON.Vector3(0, 0, -1);
  70608. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70609. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70610. return new BABYLON.Ray(origin, direction, length);
  70611. };
  70612. /**
  70613. * Disposes of the controller
  70614. */
  70615. WindowsMotionController.prototype.dispose = function () {
  70616. _super.prototype.dispose.call(this);
  70617. this.onTrackpadChangedObservable.clear();
  70618. };
  70619. /**
  70620. * The base url used to load the left and right controller models
  70621. */
  70622. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  70623. /**
  70624. * The name of the left controller model file
  70625. */
  70626. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  70627. /**
  70628. * The name of the right controller model file
  70629. */
  70630. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  70631. /**
  70632. * The controller name prefix for this controller type
  70633. */
  70634. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  70635. /**
  70636. * The controller id pattern for this controller type
  70637. */
  70638. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  70639. return WindowsMotionController;
  70640. }(BABYLON.WebVRController));
  70641. BABYLON.WindowsMotionController = WindowsMotionController;
  70642. })(BABYLON || (BABYLON = {}));
  70643. //# sourceMappingURL=babylon.windowsMotionController.js.map
  70644. "use strict";
  70645. var BABYLON;
  70646. (function (BABYLON) {
  70647. /**
  70648. * Gear VR Controller
  70649. */
  70650. var GearVRController = /** @class */ (function (_super) {
  70651. __extends(GearVRController, _super);
  70652. /**
  70653. * Creates a new GearVRController from a gamepad
  70654. * @param vrGamepad the gamepad that the controller should be created from
  70655. */
  70656. function GearVRController(vrGamepad) {
  70657. var _this = _super.call(this, vrGamepad) || this;
  70658. _this._buttonIndexToObservableNameMap = [
  70659. 'onTrackpadChangedObservable',
  70660. 'onTriggerStateChangedObservable' // Trigger
  70661. ];
  70662. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  70663. return _this;
  70664. }
  70665. /**
  70666. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70667. * @param scene scene in which to add meshes
  70668. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70669. */
  70670. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70671. var _this = this;
  70672. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  70673. _this._defaultModel = newMeshes[1];
  70674. _this.attachToMesh(_this._defaultModel);
  70675. if (meshLoaded) {
  70676. meshLoaded(_this._defaultModel);
  70677. }
  70678. });
  70679. };
  70680. /**
  70681. * Called once for each button that changed state since the last frame
  70682. * @param buttonIdx Which button index changed
  70683. * @param state New state of the button
  70684. * @param changes Which properties on the state changed since last frame
  70685. */
  70686. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70687. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  70688. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  70689. // Only emit events for buttons that we know how to map from index to observable
  70690. var observable = this[observableName];
  70691. if (observable) {
  70692. observable.notifyObservers(state);
  70693. }
  70694. }
  70695. };
  70696. /**
  70697. * Base Url for the controller model.
  70698. */
  70699. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70700. /**
  70701. * File name for the controller model.
  70702. */
  70703. GearVRController.MODEL_FILENAME = 'generic.babylon';
  70704. /**
  70705. * Gamepad Id prefix used to identify this controller.
  70706. */
  70707. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  70708. return GearVRController;
  70709. }(BABYLON.WebVRController));
  70710. BABYLON.GearVRController = GearVRController;
  70711. })(BABYLON || (BABYLON = {}));
  70712. //# sourceMappingURL=babylon.gearVRController.js.map
  70713. "use strict";
  70714. var BABYLON;
  70715. (function (BABYLON) {
  70716. /**
  70717. * Google Daydream controller
  70718. */
  70719. var DaydreamController = /** @class */ (function (_super) {
  70720. __extends(DaydreamController, _super);
  70721. /**
  70722. * Creates a new DaydreamController from a gamepad
  70723. * @param vrGamepad the gamepad that the controller should be created from
  70724. */
  70725. function DaydreamController(vrGamepad) {
  70726. var _this = _super.call(this, vrGamepad) || this;
  70727. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  70728. return _this;
  70729. }
  70730. /**
  70731. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70732. * @param scene scene in which to add meshes
  70733. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70734. */
  70735. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70736. var _this = this;
  70737. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  70738. _this._defaultModel = newMeshes[1];
  70739. _this.attachToMesh(_this._defaultModel);
  70740. if (meshLoaded) {
  70741. meshLoaded(_this._defaultModel);
  70742. }
  70743. });
  70744. };
  70745. /**
  70746. * Called once for each button that changed state since the last frame
  70747. * @param buttonIdx Which button index changed
  70748. * @param state New state of the button
  70749. * @param changes Which properties on the state changed since last frame
  70750. */
  70751. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70752. // Daydream controller only has 1 GamepadButton (on the trackpad).
  70753. if (buttonIdx === 0) {
  70754. var observable = this.onTriggerStateChangedObservable;
  70755. if (observable) {
  70756. observable.notifyObservers(state);
  70757. }
  70758. }
  70759. else {
  70760. // If the app or home buttons are ever made available
  70761. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  70762. }
  70763. };
  70764. /**
  70765. * Base Url for the controller model.
  70766. */
  70767. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70768. /**
  70769. * File name for the controller model.
  70770. */
  70771. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  70772. /**
  70773. * Gamepad Id prefix used to identify Daydream Controller.
  70774. */
  70775. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  70776. return DaydreamController;
  70777. }(BABYLON.WebVRController));
  70778. BABYLON.DaydreamController = DaydreamController;
  70779. })(BABYLON || (BABYLON = {}));
  70780. //# sourceMappingURL=babylon.daydreamController.js.map
  70781. "use strict";
  70782. var BABYLON;
  70783. (function (BABYLON) {
  70784. var FollowCamera = /** @class */ (function (_super) {
  70785. __extends(FollowCamera, _super);
  70786. function FollowCamera(name, position, scene, lockedTarget) {
  70787. if (lockedTarget === void 0) { lockedTarget = null; }
  70788. var _this = _super.call(this, name, position, scene) || this;
  70789. _this.radius = 12;
  70790. _this.rotationOffset = 0;
  70791. _this.heightOffset = 4;
  70792. _this.cameraAcceleration = 0.05;
  70793. _this.maxCameraSpeed = 20;
  70794. _this.lockedTarget = lockedTarget;
  70795. return _this;
  70796. }
  70797. FollowCamera.prototype.getRadians = function (degrees) {
  70798. return degrees * Math.PI / 180;
  70799. };
  70800. FollowCamera.prototype.follow = function (cameraTarget) {
  70801. if (!cameraTarget)
  70802. return;
  70803. var yRotation;
  70804. if (cameraTarget.rotationQuaternion) {
  70805. var rotMatrix = new BABYLON.Matrix();
  70806. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  70807. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  70808. }
  70809. else {
  70810. yRotation = cameraTarget.rotation.y;
  70811. }
  70812. var radians = this.getRadians(this.rotationOffset) + yRotation;
  70813. var targetPosition = cameraTarget.getAbsolutePosition();
  70814. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  70815. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  70816. var dx = targetX - this.position.x;
  70817. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  70818. var dz = (targetZ) - this.position.z;
  70819. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  70820. var vy = dy * this.cameraAcceleration;
  70821. var vz = dz * this.cameraAcceleration * 2;
  70822. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  70823. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70824. }
  70825. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  70826. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70827. }
  70828. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  70829. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70830. }
  70831. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  70832. this.setTarget(targetPosition);
  70833. };
  70834. FollowCamera.prototype._checkInputs = function () {
  70835. _super.prototype._checkInputs.call(this);
  70836. if (this.lockedTarget) {
  70837. this.follow(this.lockedTarget);
  70838. }
  70839. };
  70840. FollowCamera.prototype.getClassName = function () {
  70841. return "FollowCamera";
  70842. };
  70843. __decorate([
  70844. BABYLON.serialize()
  70845. ], FollowCamera.prototype, "radius", void 0);
  70846. __decorate([
  70847. BABYLON.serialize()
  70848. ], FollowCamera.prototype, "rotationOffset", void 0);
  70849. __decorate([
  70850. BABYLON.serialize()
  70851. ], FollowCamera.prototype, "heightOffset", void 0);
  70852. __decorate([
  70853. BABYLON.serialize()
  70854. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  70855. __decorate([
  70856. BABYLON.serialize()
  70857. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  70858. __decorate([
  70859. BABYLON.serializeAsMeshReference("lockedTargetId")
  70860. ], FollowCamera.prototype, "lockedTarget", void 0);
  70861. return FollowCamera;
  70862. }(BABYLON.TargetCamera));
  70863. BABYLON.FollowCamera = FollowCamera;
  70864. var ArcFollowCamera = /** @class */ (function (_super) {
  70865. __extends(ArcFollowCamera, _super);
  70866. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  70867. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  70868. _this.alpha = alpha;
  70869. _this.beta = beta;
  70870. _this.radius = radius;
  70871. _this.target = target;
  70872. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  70873. _this.follow();
  70874. return _this;
  70875. }
  70876. ArcFollowCamera.prototype.follow = function () {
  70877. if (!this.target) {
  70878. return;
  70879. }
  70880. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  70881. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  70882. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  70883. var targetPosition = this.target.getAbsolutePosition();
  70884. this.position = targetPosition.add(this._cartesianCoordinates);
  70885. this.setTarget(targetPosition);
  70886. };
  70887. ArcFollowCamera.prototype._checkInputs = function () {
  70888. _super.prototype._checkInputs.call(this);
  70889. this.follow();
  70890. };
  70891. ArcFollowCamera.prototype.getClassName = function () {
  70892. return "ArcFollowCamera";
  70893. };
  70894. return ArcFollowCamera;
  70895. }(BABYLON.TargetCamera));
  70896. BABYLON.ArcFollowCamera = ArcFollowCamera;
  70897. })(BABYLON || (BABYLON = {}));
  70898. //# sourceMappingURL=babylon.followCamera.js.map
  70899. "use strict";
  70900. var BABYLON;
  70901. (function (BABYLON) {
  70902. // We're mainly based on the logic defined into the FreeCamera code
  70903. var UniversalCamera = /** @class */ (function (_super) {
  70904. __extends(UniversalCamera, _super);
  70905. //-- end properties for backward compatibility for inputs
  70906. function UniversalCamera(name, position, scene) {
  70907. var _this = _super.call(this, name, position, scene) || this;
  70908. _this.inputs.addGamepad();
  70909. return _this;
  70910. }
  70911. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  70912. //-- Begin properties for backward compatibility for inputs
  70913. get: function () {
  70914. var gamepad = this.inputs.attached["gamepad"];
  70915. if (gamepad)
  70916. return gamepad.gamepadAngularSensibility;
  70917. return 0;
  70918. },
  70919. set: function (value) {
  70920. var gamepad = this.inputs.attached["gamepad"];
  70921. if (gamepad)
  70922. gamepad.gamepadAngularSensibility = value;
  70923. },
  70924. enumerable: true,
  70925. configurable: true
  70926. });
  70927. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  70928. get: function () {
  70929. var gamepad = this.inputs.attached["gamepad"];
  70930. if (gamepad)
  70931. return gamepad.gamepadMoveSensibility;
  70932. return 0;
  70933. },
  70934. set: function (value) {
  70935. var gamepad = this.inputs.attached["gamepad"];
  70936. if (gamepad)
  70937. gamepad.gamepadMoveSensibility = value;
  70938. },
  70939. enumerable: true,
  70940. configurable: true
  70941. });
  70942. UniversalCamera.prototype.getClassName = function () {
  70943. return "UniversalCamera";
  70944. };
  70945. return UniversalCamera;
  70946. }(BABYLON.TouchCamera));
  70947. BABYLON.UniversalCamera = UniversalCamera;
  70948. })(BABYLON || (BABYLON = {}));
  70949. //# sourceMappingURL=babylon.universalCamera.js.map
  70950. "use strict";
  70951. var BABYLON;
  70952. (function (BABYLON) {
  70953. // We're mainly based on the logic defined into the FreeCamera code
  70954. var GamepadCamera = /** @class */ (function (_super) {
  70955. __extends(GamepadCamera, _super);
  70956. //-- end properties for backward compatibility for inputs
  70957. function GamepadCamera(name, position, scene) {
  70958. return _super.call(this, name, position, scene) || this;
  70959. }
  70960. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  70961. //-- Begin properties for backward compatibility for inputs
  70962. get: function () {
  70963. var gamepad = this.inputs.attached["gamepad"];
  70964. if (gamepad)
  70965. return gamepad.gamepadAngularSensibility;
  70966. return 0;
  70967. },
  70968. set: function (value) {
  70969. var gamepad = this.inputs.attached["gamepad"];
  70970. if (gamepad)
  70971. gamepad.gamepadAngularSensibility = value;
  70972. },
  70973. enumerable: true,
  70974. configurable: true
  70975. });
  70976. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  70977. get: function () {
  70978. var gamepad = this.inputs.attached["gamepad"];
  70979. if (gamepad)
  70980. return gamepad.gamepadMoveSensibility;
  70981. return 0;
  70982. },
  70983. set: function (value) {
  70984. var gamepad = this.inputs.attached["gamepad"];
  70985. if (gamepad)
  70986. gamepad.gamepadMoveSensibility = value;
  70987. },
  70988. enumerable: true,
  70989. configurable: true
  70990. });
  70991. GamepadCamera.prototype.getClassName = function () {
  70992. return "GamepadCamera";
  70993. };
  70994. return GamepadCamera;
  70995. }(BABYLON.UniversalCamera));
  70996. BABYLON.GamepadCamera = GamepadCamera;
  70997. })(BABYLON || (BABYLON = {}));
  70998. //# sourceMappingURL=babylon.gamepadCamera.js.map
  70999. "use strict";
  71000. var BABYLON;
  71001. (function (BABYLON) {
  71002. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71003. function PostProcessRenderPipelineManager() {
  71004. this._renderPipelines = {};
  71005. }
  71006. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71007. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71008. };
  71009. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71010. if (unique === void 0) { unique = false; }
  71011. var renderPipeline = this._renderPipelines[renderPipelineName];
  71012. if (!renderPipeline) {
  71013. return;
  71014. }
  71015. renderPipeline._attachCameras(cameras, unique);
  71016. };
  71017. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  71018. var renderPipeline = this._renderPipelines[renderPipelineName];
  71019. if (!renderPipeline) {
  71020. return;
  71021. }
  71022. renderPipeline._detachCameras(cameras);
  71023. };
  71024. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71025. var renderPipeline = this._renderPipelines[renderPipelineName];
  71026. if (!renderPipeline) {
  71027. return;
  71028. }
  71029. renderPipeline._enableEffect(renderEffectName, cameras);
  71030. };
  71031. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71032. var renderPipeline = this._renderPipelines[renderPipelineName];
  71033. if (!renderPipeline) {
  71034. return;
  71035. }
  71036. renderPipeline._disableEffect(renderEffectName, cameras);
  71037. };
  71038. PostProcessRenderPipelineManager.prototype.update = function () {
  71039. for (var renderPipelineName in this._renderPipelines) {
  71040. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71041. var pipeline = this._renderPipelines[renderPipelineName];
  71042. if (!pipeline.isSupported) {
  71043. pipeline.dispose();
  71044. delete this._renderPipelines[renderPipelineName];
  71045. }
  71046. else {
  71047. pipeline._update();
  71048. }
  71049. }
  71050. }
  71051. };
  71052. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  71053. for (var renderPipelineName in this._renderPipelines) {
  71054. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71055. var pipeline = this._renderPipelines[renderPipelineName];
  71056. pipeline._rebuild();
  71057. }
  71058. }
  71059. };
  71060. PostProcessRenderPipelineManager.prototype.dispose = function () {
  71061. for (var renderPipelineName in this._renderPipelines) {
  71062. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71063. var pipeline = this._renderPipelines[renderPipelineName];
  71064. pipeline.dispose();
  71065. }
  71066. }
  71067. };
  71068. return PostProcessRenderPipelineManager;
  71069. }());
  71070. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  71071. })(BABYLON || (BABYLON = {}));
  71072. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  71073. "use strict";
  71074. var BABYLON;
  71075. (function (BABYLON) {
  71076. /**
  71077. * This represents a set of one or more post processes in Babylon.
  71078. * A post process can be used to apply a shader to a texture after it is rendered.
  71079. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  71080. */
  71081. var PostProcessRenderEffect = /** @class */ (function () {
  71082. /**
  71083. * Instantiates a post process render effect.
  71084. * A post process can be used to apply a shader to a texture after it is rendered.
  71085. * @param engine The engine the effect is tied to
  71086. * @param name The name of the effect
  71087. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  71088. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  71089. */
  71090. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  71091. this._name = name;
  71092. this._singleInstance = singleInstance || true;
  71093. this._getPostProcesses = getPostProcesses;
  71094. this._cameras = {};
  71095. this._indicesForCamera = {};
  71096. this._postProcesses = {};
  71097. }
  71098. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  71099. /**
  71100. * Checks if all the post processes in the effect are supported.
  71101. */
  71102. get: function () {
  71103. for (var index in this._postProcesses) {
  71104. if (this._postProcesses.hasOwnProperty(index)) {
  71105. var pps = this._postProcesses[index];
  71106. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  71107. if (!pps[ppIndex].isSupported) {
  71108. return false;
  71109. }
  71110. }
  71111. }
  71112. }
  71113. return true;
  71114. },
  71115. enumerable: true,
  71116. configurable: true
  71117. });
  71118. /**
  71119. * Updates the current state of the effect
  71120. */
  71121. PostProcessRenderEffect.prototype._update = function () {
  71122. };
  71123. /**
  71124. * Attaches the effect on cameras
  71125. * @param cameras The camera to attach to.
  71126. */
  71127. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  71128. var _this = this;
  71129. var cameraKey;
  71130. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71131. if (!cams) {
  71132. return;
  71133. }
  71134. for (var i = 0; i < cams.length; i++) {
  71135. var camera = cams[i];
  71136. var cameraName = camera.name;
  71137. if (this._singleInstance) {
  71138. cameraKey = 0;
  71139. }
  71140. else {
  71141. cameraKey = cameraName;
  71142. }
  71143. if (!this._postProcesses[cameraKey]) {
  71144. var postProcess = this._getPostProcesses();
  71145. if (postProcess) {
  71146. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  71147. }
  71148. }
  71149. if (!this._indicesForCamera[cameraName]) {
  71150. this._indicesForCamera[cameraName] = [];
  71151. }
  71152. this._postProcesses[cameraKey].forEach(function (postProcess) {
  71153. var index = camera.attachPostProcess(postProcess);
  71154. _this._indicesForCamera[cameraName].push(index);
  71155. });
  71156. if (!this._cameras[cameraName]) {
  71157. this._cameras[cameraName] = camera;
  71158. }
  71159. }
  71160. };
  71161. /**
  71162. * Detatches the effect on cameras
  71163. * @param cameras The camera to detatch from.
  71164. */
  71165. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  71166. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71167. if (!cams) {
  71168. return;
  71169. }
  71170. for (var i = 0; i < cams.length; i++) {
  71171. var camera = cams[i];
  71172. var cameraName = camera.name;
  71173. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71174. camera.detachPostProcess(postProcess);
  71175. });
  71176. if (this._cameras[cameraName]) {
  71177. //this._indicesForCamera.splice(index, 1);
  71178. this._cameras[cameraName] = null;
  71179. }
  71180. }
  71181. };
  71182. /**
  71183. * Enables the effect on given cameras
  71184. * @param cameras The camera to enable.
  71185. */
  71186. PostProcessRenderEffect.prototype._enable = function (cameras) {
  71187. var _this = this;
  71188. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71189. if (!cams) {
  71190. return;
  71191. }
  71192. for (var i = 0; i < cams.length; i++) {
  71193. var camera = cams[i];
  71194. var cameraName = camera.name;
  71195. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  71196. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  71197. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71198. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  71199. });
  71200. }
  71201. }
  71202. }
  71203. };
  71204. /**
  71205. * Disables the effect on the given cameras
  71206. * @param cameras The camera to disable.
  71207. */
  71208. PostProcessRenderEffect.prototype._disable = function (cameras) {
  71209. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71210. if (!cams) {
  71211. return;
  71212. }
  71213. for (var i = 0; i < cams.length; i++) {
  71214. var camera = cams[i];
  71215. var cameraName = camera.name;
  71216. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71217. camera.detachPostProcess(postProcess);
  71218. });
  71219. }
  71220. };
  71221. /**
  71222. * Gets a list of the post processes contained in the effect.
  71223. * @param camera The camera to get the post processes on.
  71224. * @returns The list of the post processes in the effect.
  71225. */
  71226. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  71227. if (this._singleInstance) {
  71228. return this._postProcesses[0];
  71229. }
  71230. else {
  71231. if (!camera) {
  71232. return null;
  71233. }
  71234. return this._postProcesses[camera.name];
  71235. }
  71236. };
  71237. return PostProcessRenderEffect;
  71238. }());
  71239. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  71240. })(BABYLON || (BABYLON = {}));
  71241. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  71242. "use strict";
  71243. var BABYLON;
  71244. (function (BABYLON) {
  71245. var PostProcessRenderPipeline = /** @class */ (function () {
  71246. function PostProcessRenderPipeline(engine, name) {
  71247. this.engine = engine;
  71248. this._name = name;
  71249. this._renderEffects = {};
  71250. this._renderEffectsForIsolatedPass = new Array();
  71251. this._cameras = [];
  71252. }
  71253. PostProcessRenderPipeline.prototype.getClassName = function () {
  71254. return "PostProcessRenderPipeline";
  71255. };
  71256. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  71257. get: function () {
  71258. for (var renderEffectName in this._renderEffects) {
  71259. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71260. if (!this._renderEffects[renderEffectName].isSupported) {
  71261. return false;
  71262. }
  71263. }
  71264. }
  71265. return true;
  71266. },
  71267. enumerable: true,
  71268. configurable: true
  71269. });
  71270. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  71271. this._renderEffects[renderEffect._name] = renderEffect;
  71272. };
  71273. // private
  71274. PostProcessRenderPipeline.prototype._rebuild = function () {
  71275. };
  71276. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  71277. var renderEffects = this._renderEffects[renderEffectName];
  71278. if (!renderEffects) {
  71279. return;
  71280. }
  71281. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71282. };
  71283. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  71284. var renderEffects = this._renderEffects[renderEffectName];
  71285. if (!renderEffects) {
  71286. return;
  71287. }
  71288. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71289. };
  71290. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  71291. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71292. if (!cams) {
  71293. return;
  71294. }
  71295. var indicesToDelete = [];
  71296. var i;
  71297. for (i = 0; i < cams.length; i++) {
  71298. var camera = cams[i];
  71299. var cameraName = camera.name;
  71300. if (this._cameras.indexOf(camera) === -1) {
  71301. this._cameras[cameraName] = camera;
  71302. }
  71303. else if (unique) {
  71304. indicesToDelete.push(i);
  71305. }
  71306. }
  71307. for (i = 0; i < indicesToDelete.length; i++) {
  71308. cameras.splice(indicesToDelete[i], 1);
  71309. }
  71310. for (var renderEffectName in this._renderEffects) {
  71311. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71312. this._renderEffects[renderEffectName]._attachCameras(cams);
  71313. }
  71314. }
  71315. };
  71316. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  71317. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71318. if (!cams) {
  71319. return;
  71320. }
  71321. for (var renderEffectName in this._renderEffects) {
  71322. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71323. this._renderEffects[renderEffectName]._detachCameras(cams);
  71324. }
  71325. }
  71326. for (var i = 0; i < cams.length; i++) {
  71327. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  71328. }
  71329. };
  71330. PostProcessRenderPipeline.prototype._update = function () {
  71331. for (var renderEffectName in this._renderEffects) {
  71332. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71333. this._renderEffects[renderEffectName]._update();
  71334. }
  71335. }
  71336. for (var i = 0; i < this._cameras.length; i++) {
  71337. var cameraName = this._cameras[i].name;
  71338. if (this._renderEffectsForIsolatedPass[cameraName]) {
  71339. this._renderEffectsForIsolatedPass[cameraName]._update();
  71340. }
  71341. }
  71342. };
  71343. PostProcessRenderPipeline.prototype._reset = function () {
  71344. this._renderEffects = {};
  71345. this._renderEffectsForIsolatedPass = new Array();
  71346. };
  71347. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  71348. // 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)
  71349. var effectKeys = Object.keys(this._renderEffects);
  71350. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  71351. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  71352. if (postProcesses) {
  71353. postProcesses[0].samples = sampleCount;
  71354. return true;
  71355. }
  71356. }
  71357. return false;
  71358. };
  71359. PostProcessRenderPipeline.prototype.dispose = function () {
  71360. // Must be implemented by children
  71361. };
  71362. __decorate([
  71363. BABYLON.serialize()
  71364. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  71365. return PostProcessRenderPipeline;
  71366. }());
  71367. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  71368. })(BABYLON || (BABYLON = {}));
  71369. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  71370. "use strict";
  71371. var BABYLON;
  71372. (function (BABYLON) {
  71373. /**
  71374. * This represents a depth renderer in Babylon.
  71375. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  71376. */
  71377. var DepthRenderer = /** @class */ (function () {
  71378. /**
  71379. * Instantiates a depth renderer
  71380. * @param scene The scene the renderer belongs to
  71381. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  71382. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  71383. */
  71384. function DepthRenderer(scene, type, camera) {
  71385. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71386. if (camera === void 0) { camera = null; }
  71387. var _this = this;
  71388. this._scene = scene;
  71389. this._camera = camera;
  71390. var engine = scene.getEngine();
  71391. // Render target
  71392. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  71393. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71394. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71395. this._depthMap.refreshRate = 1;
  71396. this._depthMap.renderParticles = false;
  71397. this._depthMap.renderList = null;
  71398. // Camera to get depth map from to support multiple concurrent cameras
  71399. this._depthMap.activeCamera = this._camera;
  71400. this._depthMap.ignoreCameraViewport = true;
  71401. this._depthMap.useCameraPostProcesses = false;
  71402. // set default depth value to 1.0 (far away)
  71403. this._depthMap.onClearObservable.add(function (engine) {
  71404. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  71405. });
  71406. // Custom render function
  71407. var renderSubMesh = function (subMesh) {
  71408. var mesh = subMesh.getRenderingMesh();
  71409. var scene = _this._scene;
  71410. var engine = scene.getEngine();
  71411. var material = subMesh.getMaterial();
  71412. if (!material) {
  71413. return;
  71414. }
  71415. // Culling and reverse (right handed system)
  71416. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71417. // Managing instances
  71418. var batch = mesh._getInstancesRenderList(subMesh._id);
  71419. if (batch.mustReturn) {
  71420. return;
  71421. }
  71422. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71423. var camera = _this._camera || scene.activeCamera;
  71424. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  71425. engine.enableEffect(_this._effect);
  71426. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71427. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71428. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  71429. // Alpha test
  71430. if (material && material.needAlphaTesting()) {
  71431. var alphaTexture = material.getAlphaTestTexture();
  71432. if (alphaTexture) {
  71433. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71434. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71435. }
  71436. }
  71437. // Bones
  71438. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71439. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71440. }
  71441. // Draw
  71442. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71443. }
  71444. };
  71445. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71446. var index;
  71447. if (depthOnlySubMeshes.length) {
  71448. engine.setColorWrite(false);
  71449. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71450. renderSubMesh(depthOnlySubMeshes.data[index]);
  71451. }
  71452. engine.setColorWrite(true);
  71453. }
  71454. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71455. renderSubMesh(opaqueSubMeshes.data[index]);
  71456. }
  71457. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71458. renderSubMesh(alphaTestSubMeshes.data[index]);
  71459. }
  71460. };
  71461. }
  71462. /**
  71463. * Creates the depth rendering effect and checks if the effect is ready.
  71464. * @param subMesh The submesh to be used to render the depth map of
  71465. * @param useInstances If multiple world instances should be used
  71466. * @returns if the depth renderer is ready to render the depth map
  71467. */
  71468. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  71469. var material = subMesh.getMaterial();
  71470. if (material.disableDepthWrite) {
  71471. return false;
  71472. }
  71473. var defines = [];
  71474. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71475. var mesh = subMesh.getMesh();
  71476. // Alpha test
  71477. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  71478. defines.push("#define ALPHATEST");
  71479. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71480. attribs.push(BABYLON.VertexBuffer.UVKind);
  71481. defines.push("#define UV1");
  71482. }
  71483. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71484. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71485. defines.push("#define UV2");
  71486. }
  71487. }
  71488. // Bones
  71489. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71490. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71491. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71492. if (mesh.numBoneInfluencers > 4) {
  71493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71495. }
  71496. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71497. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71498. }
  71499. else {
  71500. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71501. }
  71502. // Instances
  71503. if (useInstances) {
  71504. defines.push("#define INSTANCES");
  71505. attribs.push("world0");
  71506. attribs.push("world1");
  71507. attribs.push("world2");
  71508. attribs.push("world3");
  71509. }
  71510. // Get correct effect
  71511. var join = defines.join("\n");
  71512. if (this._cachedDefines !== join) {
  71513. this._cachedDefines = join;
  71514. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  71515. }
  71516. return this._effect.isReady();
  71517. };
  71518. /**
  71519. * Gets the texture which the depth map will be written to.
  71520. * @returns The depth map texture
  71521. */
  71522. DepthRenderer.prototype.getDepthMap = function () {
  71523. return this._depthMap;
  71524. };
  71525. /**
  71526. * Disposes of the depth renderer.
  71527. */
  71528. DepthRenderer.prototype.dispose = function () {
  71529. this._depthMap.dispose();
  71530. };
  71531. return DepthRenderer;
  71532. }());
  71533. BABYLON.DepthRenderer = DepthRenderer;
  71534. })(BABYLON || (BABYLON = {}));
  71535. //# sourceMappingURL=babylon.depthRenderer.js.map
  71536. "use strict";
  71537. var BABYLON;
  71538. (function (BABYLON) {
  71539. var SSAORenderingPipeline = /** @class */ (function (_super) {
  71540. __extends(SSAORenderingPipeline, _super);
  71541. /**
  71542. * @constructor
  71543. * @param {string} name - The rendering pipeline name
  71544. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71545. * @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 }
  71546. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71547. */
  71548. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  71549. var _this = _super.call(this, scene.getEngine(), name) || this;
  71550. // Members
  71551. /**
  71552. * The PassPostProcess id in the pipeline that contains the original scene color
  71553. */
  71554. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71555. /**
  71556. * The SSAO PostProcess id in the pipeline
  71557. */
  71558. _this.SSAORenderEffect = "SSAORenderEffect";
  71559. /**
  71560. * The horizontal blur PostProcess id in the pipeline
  71561. */
  71562. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71563. /**
  71564. * The vertical blur PostProcess id in the pipeline
  71565. */
  71566. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71567. /**
  71568. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71569. */
  71570. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71571. /**
  71572. * The output strength of the SSAO post-process. Default value is 1.0.
  71573. */
  71574. _this.totalStrength = 1.0;
  71575. /**
  71576. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  71577. */
  71578. _this.radius = 0.0001;
  71579. /**
  71580. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  71581. * Must not be equal to fallOff and superior to fallOff.
  71582. * Default value is 0.975
  71583. */
  71584. _this.area = 0.0075;
  71585. /**
  71586. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  71587. * Must not be equal to area and inferior to area.
  71588. * Default value is 0.0
  71589. */
  71590. _this.fallOff = 0.000001;
  71591. /**
  71592. * The base color of the SSAO post-process
  71593. * The final result is "base + ssao" between [0, 1]
  71594. */
  71595. _this.base = 0.5;
  71596. _this._firstUpdate = true;
  71597. _this._scene = scene;
  71598. // Set up assets
  71599. _this._createRandomTexture();
  71600. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71601. var ssaoRatio = ratio.ssaoRatio || ratio;
  71602. var combineRatio = ratio.combineRatio || ratio;
  71603. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71604. _this._createSSAOPostProcess(ssaoRatio);
  71605. _this._createBlurPostProcess(ssaoRatio);
  71606. _this._createSSAOCombinePostProcess(combineRatio);
  71607. // Set up pipeline
  71608. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71609. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71610. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71611. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71612. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71613. // Finish
  71614. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71615. if (cameras)
  71616. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71617. return _this;
  71618. }
  71619. // Public Methods
  71620. /**
  71621. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71622. */
  71623. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71624. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71625. for (var i = 0; i < this._scene.cameras.length; i++) {
  71626. var camera = this._scene.cameras[i];
  71627. this._originalColorPostProcess.dispose(camera);
  71628. this._ssaoPostProcess.dispose(camera);
  71629. this._blurHPostProcess.dispose(camera);
  71630. this._blurVPostProcess.dispose(camera);
  71631. this._ssaoCombinePostProcess.dispose(camera);
  71632. }
  71633. this._randomTexture.dispose();
  71634. if (disableDepthRender)
  71635. this._scene.disableDepthRenderer();
  71636. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71637. _super.prototype.dispose.call(this);
  71638. };
  71639. // Private Methods
  71640. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  71641. var _this = this;
  71642. var size = 16;
  71643. 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);
  71644. 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);
  71645. this._blurHPostProcess.onActivateObservable.add(function () {
  71646. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  71647. _this._blurHPostProcess.kernel = size * dw;
  71648. });
  71649. this._blurVPostProcess.onActivateObservable.add(function () {
  71650. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  71651. _this._blurVPostProcess.kernel = size * dw;
  71652. });
  71653. };
  71654. SSAORenderingPipeline.prototype._rebuild = function () {
  71655. this._firstUpdate = true;
  71656. _super.prototype._rebuild.call(this);
  71657. };
  71658. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71659. var _this = this;
  71660. var numSamples = 16;
  71661. var sampleSphere = [
  71662. 0.5381, 0.1856, -0.4319,
  71663. 0.1379, 0.2486, 0.4430,
  71664. 0.3371, 0.5679, -0.0057,
  71665. -0.6999, -0.0451, -0.0019,
  71666. 0.0689, -0.1598, -0.8547,
  71667. 0.0560, 0.0069, -0.1843,
  71668. -0.0146, 0.1402, 0.0762,
  71669. 0.0100, -0.1924, -0.0344,
  71670. -0.3577, -0.5301, -0.4358,
  71671. -0.3169, 0.1063, 0.0158,
  71672. 0.0103, -0.5869, 0.0046,
  71673. -0.0897, -0.4940, 0.3287,
  71674. 0.7119, -0.0154, -0.0918,
  71675. -0.0533, 0.0596, -0.5411,
  71676. 0.0352, -0.0631, 0.5460,
  71677. -0.4776, 0.2847, -0.0271
  71678. ];
  71679. var samplesFactor = 1.0 / numSamples;
  71680. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  71681. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71682. "area", "fallOff", "base", "range", "viewport"
  71683. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71684. this._ssaoPostProcess.onApply = function (effect) {
  71685. if (_this._firstUpdate) {
  71686. effect.setArray3("sampleSphere", sampleSphere);
  71687. effect.setFloat("samplesFactor", samplesFactor);
  71688. effect.setFloat("randTextureTiles", 4.0);
  71689. }
  71690. effect.setFloat("totalStrength", _this.totalStrength);
  71691. effect.setFloat("radius", _this.radius);
  71692. effect.setFloat("area", _this.area);
  71693. effect.setFloat("fallOff", _this.fallOff);
  71694. effect.setFloat("base", _this.base);
  71695. effect.setTexture("textureSampler", _this._depthTexture);
  71696. effect.setTexture("randomSampler", _this._randomTexture);
  71697. };
  71698. };
  71699. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71700. var _this = this;
  71701. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71702. this._ssaoCombinePostProcess.onApply = function (effect) {
  71703. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71704. };
  71705. };
  71706. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  71707. var size = 512;
  71708. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71709. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71710. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71711. var context = this._randomTexture.getContext();
  71712. var rand = function (min, max) {
  71713. return Math.random() * (max - min) + min;
  71714. };
  71715. var randVector = BABYLON.Vector3.Zero();
  71716. for (var x = 0; x < size; x++) {
  71717. for (var y = 0; y < size; y++) {
  71718. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  71719. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  71720. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  71721. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71722. context.fillRect(x, y, 1, 1);
  71723. }
  71724. }
  71725. this._randomTexture.update(false);
  71726. };
  71727. __decorate([
  71728. BABYLON.serialize()
  71729. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  71730. __decorate([
  71731. BABYLON.serialize()
  71732. ], SSAORenderingPipeline.prototype, "radius", void 0);
  71733. __decorate([
  71734. BABYLON.serialize()
  71735. ], SSAORenderingPipeline.prototype, "area", void 0);
  71736. __decorate([
  71737. BABYLON.serialize()
  71738. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  71739. __decorate([
  71740. BABYLON.serialize()
  71741. ], SSAORenderingPipeline.prototype, "base", void 0);
  71742. return SSAORenderingPipeline;
  71743. }(BABYLON.PostProcessRenderPipeline));
  71744. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  71745. })(BABYLON || (BABYLON = {}));
  71746. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  71747. "use strict";
  71748. var BABYLON;
  71749. (function (BABYLON) {
  71750. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  71751. __extends(SSAO2RenderingPipeline, _super);
  71752. /**
  71753. * @constructor
  71754. * @param {string} name - The rendering pipeline name
  71755. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71756. * @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 }
  71757. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71758. */
  71759. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  71760. var _this = _super.call(this, scene.getEngine(), name) || this;
  71761. // Members
  71762. /**
  71763. * The PassPostProcess id in the pipeline that contains the original scene color
  71764. */
  71765. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71766. /**
  71767. * The SSAO PostProcess id in the pipeline
  71768. */
  71769. _this.SSAORenderEffect = "SSAORenderEffect";
  71770. /**
  71771. * The horizontal blur PostProcess id in the pipeline
  71772. */
  71773. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71774. /**
  71775. * The vertical blur PostProcess id in the pipeline
  71776. */
  71777. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71778. /**
  71779. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71780. */
  71781. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71782. /**
  71783. * The output strength of the SSAO post-process. Default value is 1.0.
  71784. */
  71785. _this.totalStrength = 1.0;
  71786. /**
  71787. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  71788. */
  71789. _this.maxZ = 100.0;
  71790. /**
  71791. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  71792. */
  71793. _this.minZAspect = 0.2;
  71794. /**
  71795. * Number of samples used for the SSAO calculations. Default value is 8
  71796. */
  71797. _this._samples = 8;
  71798. /**
  71799. * Are we using bilateral blur ?
  71800. */
  71801. _this._expensiveBlur = true;
  71802. /**
  71803. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  71804. */
  71805. _this.radius = 2.0;
  71806. /**
  71807. * The base color of the SSAO post-process
  71808. * The final result is "base + ssao" between [0, 1]
  71809. */
  71810. _this.base = 0.1;
  71811. _this._firstUpdate = true;
  71812. _this._scene = scene;
  71813. if (!_this.isSupported) {
  71814. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  71815. return _this;
  71816. }
  71817. var ssaoRatio = ratio.ssaoRatio || ratio;
  71818. var blurRatio = ratio.blurRatio || ratio;
  71819. // Set up assets
  71820. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  71821. _this._createRandomTexture();
  71822. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  71823. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  71824. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71825. _this._createSSAOPostProcess(1.0);
  71826. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  71827. _this._createSSAOCombinePostProcess(blurRatio);
  71828. // Set up pipeline
  71829. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71830. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71831. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71832. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71833. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71834. // Finish
  71835. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71836. if (cameras)
  71837. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71838. return _this;
  71839. }
  71840. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  71841. get: function () {
  71842. return this._samples;
  71843. },
  71844. set: function (n) {
  71845. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  71846. this._samples = n;
  71847. this._sampleSphere = this._generateHemisphere();
  71848. this._firstUpdate = true;
  71849. },
  71850. enumerable: true,
  71851. configurable: true
  71852. });
  71853. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  71854. get: function () {
  71855. return this._expensiveBlur;
  71856. },
  71857. set: function (b) {
  71858. 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"]);
  71859. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  71860. this._expensiveBlur = b;
  71861. this._firstUpdate = true;
  71862. },
  71863. enumerable: true,
  71864. configurable: true
  71865. });
  71866. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  71867. /**
  71868. * Support test.
  71869. */
  71870. get: function () {
  71871. var engine = BABYLON.Engine.LastCreatedEngine;
  71872. if (!engine) {
  71873. return false;
  71874. }
  71875. return engine.getCaps().drawBuffersExtension;
  71876. },
  71877. enumerable: true,
  71878. configurable: true
  71879. });
  71880. // Public Methods
  71881. /**
  71882. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71883. */
  71884. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  71885. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  71886. for (var i = 0; i < this._scene.cameras.length; i++) {
  71887. var camera = this._scene.cameras[i];
  71888. this._originalColorPostProcess.dispose(camera);
  71889. this._ssaoPostProcess.dispose(camera);
  71890. this._blurHPostProcess.dispose(camera);
  71891. this._blurVPostProcess.dispose(camera);
  71892. this._ssaoCombinePostProcess.dispose(camera);
  71893. }
  71894. this._randomTexture.dispose();
  71895. if (disableGeometryBufferRenderer)
  71896. this._scene.disableGeometryBufferRenderer();
  71897. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71898. _super.prototype.dispose.call(this);
  71899. };
  71900. // Private Methods
  71901. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  71902. var _this = this;
  71903. this._samplerOffsets = [];
  71904. var expensive = this.expensiveBlur;
  71905. for (var i = -8; i < 8; i++) {
  71906. this._samplerOffsets.push(i * 2 + 0.5);
  71907. }
  71908. 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");
  71909. this._blurHPostProcess.onApply = function (effect) {
  71910. if (!_this._scene.activeCamera) {
  71911. return;
  71912. }
  71913. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  71914. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71915. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71916. effect.setFloat("radius", _this.radius);
  71917. effect.setTexture("depthSampler", _this._depthTexture);
  71918. if (_this._firstUpdate) {
  71919. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71920. }
  71921. };
  71922. 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");
  71923. this._blurVPostProcess.onApply = function (effect) {
  71924. if (!_this._scene.activeCamera) {
  71925. return;
  71926. }
  71927. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  71928. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71929. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71930. effect.setFloat("radius", _this.radius);
  71931. effect.setTexture("depthSampler", _this._depthTexture);
  71932. if (_this._firstUpdate) {
  71933. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71934. _this._firstUpdate = false;
  71935. }
  71936. };
  71937. };
  71938. SSAO2RenderingPipeline.prototype._rebuild = function () {
  71939. this._firstUpdate = true;
  71940. _super.prototype._rebuild.call(this);
  71941. };
  71942. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  71943. var numSamples = this.samples;
  71944. var result = [];
  71945. var vector, scale;
  71946. var rand = function (min, max) {
  71947. return Math.random() * (max - min) + min;
  71948. };
  71949. var i = 0;
  71950. while (i < numSamples) {
  71951. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  71952. vector.normalize();
  71953. scale = i / numSamples;
  71954. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  71955. vector.scaleInPlace(scale);
  71956. result.push(vector.x, vector.y, vector.z);
  71957. i++;
  71958. }
  71959. return result;
  71960. };
  71961. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71962. var _this = this;
  71963. var numSamples = this.samples;
  71964. this._sampleSphere = this._generateHemisphere();
  71965. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  71966. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71967. "base", "range", "projection", "near", "far", "texelSize",
  71968. "xViewport", "yViewport", "maxZ", "minZAspect"
  71969. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71970. this._ssaoPostProcess.onApply = function (effect) {
  71971. if (_this._firstUpdate) {
  71972. effect.setArray3("sampleSphere", _this._sampleSphere);
  71973. effect.setFloat("randTextureTiles", 4.0);
  71974. }
  71975. if (!_this._scene.activeCamera) {
  71976. return;
  71977. }
  71978. effect.setFloat("samplesFactor", 1 / _this.samples);
  71979. effect.setFloat("totalStrength", _this.totalStrength);
  71980. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  71981. effect.setFloat("radius", _this.radius);
  71982. effect.setFloat("maxZ", _this.maxZ);
  71983. effect.setFloat("minZAspect", _this.minZAspect);
  71984. effect.setFloat("base", _this.base);
  71985. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71986. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71987. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  71988. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  71989. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  71990. effect.setTexture("textureSampler", _this._depthTexture);
  71991. effect.setTexture("normalSampler", _this._normalTexture);
  71992. effect.setTexture("randomSampler", _this._randomTexture);
  71993. };
  71994. };
  71995. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71996. var _this = this;
  71997. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71998. this._ssaoCombinePostProcess.onApply = function (effect) {
  71999. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72000. };
  72001. };
  72002. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72003. var size = 512;
  72004. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72005. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72006. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72007. var context = this._randomTexture.getContext();
  72008. var rand = function (min, max) {
  72009. return Math.random() * (max - min) + min;
  72010. };
  72011. var randVector = BABYLON.Vector3.Zero();
  72012. for (var x = 0; x < size; x++) {
  72013. for (var y = 0; y < size; y++) {
  72014. randVector.x = rand(0.0, 1.0);
  72015. randVector.y = rand(0.0, 1.0);
  72016. randVector.z = 0.0;
  72017. randVector.normalize();
  72018. randVector.scaleInPlace(255);
  72019. randVector.x = Math.floor(randVector.x);
  72020. randVector.y = Math.floor(randVector.y);
  72021. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72022. context.fillRect(x, y, 1, 1);
  72023. }
  72024. }
  72025. this._randomTexture.update(false);
  72026. };
  72027. __decorate([
  72028. BABYLON.serialize()
  72029. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  72030. __decorate([
  72031. BABYLON.serialize()
  72032. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  72033. __decorate([
  72034. BABYLON.serialize()
  72035. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  72036. __decorate([
  72037. BABYLON.serialize("samples")
  72038. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  72039. __decorate([
  72040. BABYLON.serialize("expensiveBlur")
  72041. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  72042. __decorate([
  72043. BABYLON.serialize()
  72044. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  72045. __decorate([
  72046. BABYLON.serialize()
  72047. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  72048. return SSAO2RenderingPipeline;
  72049. }(BABYLON.PostProcessRenderPipeline));
  72050. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  72051. })(BABYLON || (BABYLON = {}));
  72052. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  72053. "use strict";
  72054. // BABYLON.JS Chromatic Aberration GLSL Shader
  72055. // Author: Olivier Guyot
  72056. // Separates very slightly R, G and B colors on the edges of the screen
  72057. // Inspired by Francois Tarlier & Martins Upitis
  72058. var BABYLON;
  72059. (function (BABYLON) {
  72060. var LensRenderingPipeline = /** @class */ (function (_super) {
  72061. __extends(LensRenderingPipeline, _super);
  72062. /**
  72063. * @constructor
  72064. *
  72065. * Effect parameters are as follow:
  72066. * {
  72067. * chromatic_aberration: number; // from 0 to x (1 for realism)
  72068. * edge_blur: number; // from 0 to x (1 for realism)
  72069. * distortion: number; // from 0 to x (1 for realism)
  72070. * grain_amount: number; // from 0 to 1
  72071. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  72072. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  72073. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  72074. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  72075. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  72076. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  72077. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  72078. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  72079. * }
  72080. * Note: if an effect parameter is unset, effect is disabled
  72081. *
  72082. * @param {string} name - The rendering pipeline name
  72083. * @param {object} parameters - An object containing all parameters (see above)
  72084. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72085. * @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)
  72086. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72087. */
  72088. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  72089. if (ratio === void 0) { ratio = 1.0; }
  72090. var _this = _super.call(this, scene.getEngine(), name) || this;
  72091. // Lens effects can be of the following:
  72092. // - chromatic aberration (slight shift of RGB colors)
  72093. // - blur on the edge of the lens
  72094. // - lens distortion
  72095. // - depth-of-field blur & highlights enhancing
  72096. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  72097. // - grain effect (noise or custom texture)
  72098. // Two additional texture samplers are needed:
  72099. // - depth map (for depth-of-field)
  72100. // - grain texture
  72101. /**
  72102. * The chromatic aberration PostProcess id in the pipeline
  72103. */
  72104. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  72105. /**
  72106. * The highlights enhancing PostProcess id in the pipeline
  72107. */
  72108. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  72109. /**
  72110. * The depth-of-field PostProcess id in the pipeline
  72111. */
  72112. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  72113. _this._scene = scene;
  72114. // Fetch texture samplers
  72115. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72116. if (parameters.grain_texture) {
  72117. _this._grainTexture = parameters.grain_texture;
  72118. }
  72119. else {
  72120. _this._createGrainTexture();
  72121. }
  72122. // save parameters
  72123. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  72124. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  72125. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  72126. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  72127. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  72128. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  72129. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  72130. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  72131. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  72132. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  72133. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  72134. // Create effects
  72135. _this._createChromaticAberrationPostProcess(ratio);
  72136. _this._createHighlightsPostProcess(ratio);
  72137. _this._createDepthOfFieldPostProcess(ratio / 4);
  72138. // Set up pipeline
  72139. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  72140. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  72141. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  72142. if (_this._highlightsGain === -1) {
  72143. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  72144. }
  72145. // Finish
  72146. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72147. if (cameras) {
  72148. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72149. }
  72150. return _this;
  72151. }
  72152. // public methods (self explanatory)
  72153. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  72154. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  72155. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  72156. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  72157. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  72158. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  72159. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  72160. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  72161. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  72162. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  72163. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  72164. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  72165. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  72166. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  72167. };
  72168. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  72169. this._highlightsPostProcess.updateEffect();
  72170. };
  72171. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  72172. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  72173. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  72174. this._highlightsGain = amount;
  72175. };
  72176. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  72177. if (this._highlightsGain === -1) {
  72178. this._highlightsGain = 1.0;
  72179. }
  72180. this._highlightsThreshold = amount;
  72181. };
  72182. LensRenderingPipeline.prototype.disableHighlights = function () {
  72183. this._highlightsGain = -1;
  72184. };
  72185. /**
  72186. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  72187. */
  72188. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72189. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72190. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72191. this._chromaticAberrationPostProcess = null;
  72192. this._highlightsPostProcess = null;
  72193. this._depthOfFieldPostProcess = null;
  72194. this._grainTexture.dispose();
  72195. if (disableDepthRender)
  72196. this._scene.disableDepthRenderer();
  72197. };
  72198. // colors shifting and distortion
  72199. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  72200. var _this = this;
  72201. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  72202. [], // samplers
  72203. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72204. this._chromaticAberrationPostProcess.onApply = function (effect) {
  72205. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  72206. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72207. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72208. effect.setFloat('radialIntensity', 1);
  72209. effect.setFloat2('direction', 17, 17);
  72210. effect.setFloat2('centerPosition', 0.5, 0.5);
  72211. };
  72212. };
  72213. // highlights enhancing
  72214. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  72215. var _this = this;
  72216. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  72217. [], // samplers
  72218. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  72219. this._highlightsPostProcess.onApply = function (effect) {
  72220. effect.setFloat('gain', _this._highlightsGain);
  72221. effect.setFloat('threshold', _this._highlightsThreshold);
  72222. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  72223. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72224. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72225. };
  72226. };
  72227. // colors shifting and distortion
  72228. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  72229. var _this = this;
  72230. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  72231. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  72232. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  72233. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72234. this._depthOfFieldPostProcess.onApply = function (effect) {
  72235. effect.setTexture("depthSampler", _this._depthTexture);
  72236. effect.setTexture("grainSampler", _this._grainTexture);
  72237. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  72238. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  72239. effect.setFloat('grain_amount', _this._grainAmount);
  72240. effect.setBool('blur_noise', _this._blurNoise);
  72241. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72242. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72243. effect.setFloat('distortion', _this._distortion);
  72244. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  72245. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  72246. effect.setFloat('aperture', _this._dofAperture);
  72247. effect.setFloat('darken', _this._dofDarken);
  72248. effect.setFloat('edge_blur', _this._edgeBlur);
  72249. effect.setBool('highlights', (_this._highlightsGain !== -1));
  72250. if (_this._scene.activeCamera) {
  72251. effect.setFloat('near', _this._scene.activeCamera.minZ);
  72252. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  72253. }
  72254. };
  72255. };
  72256. // creates a black and white random noise texture, 512x512
  72257. LensRenderingPipeline.prototype._createGrainTexture = function () {
  72258. var size = 512;
  72259. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72260. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72261. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72262. var context = this._grainTexture.getContext();
  72263. var rand = function (min, max) {
  72264. return Math.random() * (max - min) + min;
  72265. };
  72266. var value;
  72267. for (var x = 0; x < size; x++) {
  72268. for (var y = 0; y < size; y++) {
  72269. value = Math.floor(rand(0.42, 0.58) * 255);
  72270. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  72271. context.fillRect(x, y, 1, 1);
  72272. }
  72273. }
  72274. this._grainTexture.update(false);
  72275. };
  72276. return LensRenderingPipeline;
  72277. }(BABYLON.PostProcessRenderPipeline));
  72278. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  72279. })(BABYLON || (BABYLON = {}));
  72280. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  72281. "use strict";
  72282. var BABYLON;
  72283. (function (BABYLON) {
  72284. var StandardRenderingPipeline = /** @class */ (function (_super) {
  72285. __extends(StandardRenderingPipeline, _super);
  72286. /**
  72287. * @constructor
  72288. * @param {string} name - The rendering pipeline name
  72289. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72290. * @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)
  72291. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  72292. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72293. */
  72294. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  72295. if (originalPostProcess === void 0) { originalPostProcess = null; }
  72296. var _this = _super.call(this, scene.getEngine(), name) || this;
  72297. _this.downSampleX4PostProcess = null;
  72298. _this.brightPassPostProcess = null;
  72299. _this.blurHPostProcesses = [];
  72300. _this.blurVPostProcesses = [];
  72301. _this.textureAdderPostProcess = null;
  72302. _this.volumetricLightPostProcess = null;
  72303. _this.volumetricLightSmoothXPostProcess = null;
  72304. _this.volumetricLightSmoothYPostProcess = null;
  72305. _this.volumetricLightMergePostProces = null;
  72306. _this.volumetricLightFinalPostProcess = null;
  72307. _this.luminancePostProcess = null;
  72308. _this.luminanceDownSamplePostProcesses = [];
  72309. _this.hdrPostProcess = null;
  72310. _this.textureAdderFinalPostProcess = null;
  72311. _this.lensFlareFinalPostProcess = null;
  72312. _this.hdrFinalPostProcess = null;
  72313. _this.lensFlarePostProcess = null;
  72314. _this.lensFlareComposePostProcess = null;
  72315. _this.motionBlurPostProcess = null;
  72316. _this.depthOfFieldPostProcess = null;
  72317. // Values
  72318. _this.brightThreshold = 1.0;
  72319. _this.blurWidth = 512.0;
  72320. _this.horizontalBlur = false;
  72321. _this.exposure = 1.0;
  72322. _this.lensTexture = null;
  72323. _this.volumetricLightCoefficient = 0.2;
  72324. _this.volumetricLightPower = 4.0;
  72325. _this.volumetricLightBlurScale = 64.0;
  72326. _this.sourceLight = null;
  72327. _this.hdrMinimumLuminance = 1.0;
  72328. _this.hdrDecreaseRate = 0.5;
  72329. _this.hdrIncreaseRate = 0.5;
  72330. _this.lensColorTexture = null;
  72331. _this.lensFlareStrength = 20.0;
  72332. _this.lensFlareGhostDispersal = 1.4;
  72333. _this.lensFlareHaloWidth = 0.7;
  72334. _this.lensFlareDistortionStrength = 16.0;
  72335. _this.lensStarTexture = null;
  72336. _this.lensFlareDirtTexture = null;
  72337. _this.depthOfFieldDistance = 10.0;
  72338. _this.depthOfFieldBlurWidth = 64.0;
  72339. _this.motionStrength = 1.0;
  72340. // IAnimatable
  72341. _this.animations = [];
  72342. _this._currentDepthOfFieldSource = null;
  72343. _this._hdrCurrentLuminance = 1.0;
  72344. // Getters and setters
  72345. _this._bloomEnabled = true;
  72346. _this._depthOfFieldEnabled = false;
  72347. _this._vlsEnabled = false;
  72348. _this._lensFlareEnabled = false;
  72349. _this._hdrEnabled = false;
  72350. _this._motionBlurEnabled = false;
  72351. _this._motionBlurSamples = 64.0;
  72352. _this._volumetricLightStepsCount = 50.0;
  72353. _this._cameras = cameras || [];
  72354. // Initialize
  72355. _this._scene = scene;
  72356. _this._basePostProcess = originalPostProcess;
  72357. _this._ratio = ratio;
  72358. // Misc
  72359. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72360. // Finish
  72361. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72362. _this._buildPipeline();
  72363. return _this;
  72364. }
  72365. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  72366. get: function () {
  72367. return this._bloomEnabled;
  72368. },
  72369. set: function (enabled) {
  72370. if (this._bloomEnabled === enabled) {
  72371. return;
  72372. }
  72373. this._bloomEnabled = enabled;
  72374. this._buildPipeline();
  72375. },
  72376. enumerable: true,
  72377. configurable: true
  72378. });
  72379. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  72380. get: function () {
  72381. return this._depthOfFieldEnabled;
  72382. },
  72383. set: function (enabled) {
  72384. if (this._depthOfFieldEnabled === enabled) {
  72385. return;
  72386. }
  72387. this._depthOfFieldEnabled = enabled;
  72388. this._buildPipeline();
  72389. },
  72390. enumerable: true,
  72391. configurable: true
  72392. });
  72393. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  72394. get: function () {
  72395. return this._lensFlareEnabled;
  72396. },
  72397. set: function (enabled) {
  72398. if (this._lensFlareEnabled === enabled) {
  72399. return;
  72400. }
  72401. this._lensFlareEnabled = enabled;
  72402. this._buildPipeline();
  72403. },
  72404. enumerable: true,
  72405. configurable: true
  72406. });
  72407. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  72408. get: function () {
  72409. return this._hdrEnabled;
  72410. },
  72411. set: function (enabled) {
  72412. if (this._hdrEnabled === enabled) {
  72413. return;
  72414. }
  72415. this._hdrEnabled = enabled;
  72416. this._buildPipeline();
  72417. },
  72418. enumerable: true,
  72419. configurable: true
  72420. });
  72421. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  72422. get: function () {
  72423. return this._vlsEnabled;
  72424. },
  72425. set: function (enabled) {
  72426. if (this._vlsEnabled === enabled) {
  72427. return;
  72428. }
  72429. if (enabled) {
  72430. var geometry = this._scene.enableGeometryBufferRenderer();
  72431. if (!geometry) {
  72432. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  72433. return;
  72434. }
  72435. }
  72436. this._vlsEnabled = enabled;
  72437. this._buildPipeline();
  72438. },
  72439. enumerable: true,
  72440. configurable: true
  72441. });
  72442. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  72443. get: function () {
  72444. return this._motionBlurEnabled;
  72445. },
  72446. set: function (enabled) {
  72447. if (this._motionBlurEnabled === enabled) {
  72448. return;
  72449. }
  72450. this._motionBlurEnabled = enabled;
  72451. this._buildPipeline();
  72452. },
  72453. enumerable: true,
  72454. configurable: true
  72455. });
  72456. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  72457. get: function () {
  72458. return this._volumetricLightStepsCount;
  72459. },
  72460. set: function (count) {
  72461. if (this.volumetricLightPostProcess) {
  72462. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  72463. }
  72464. this._volumetricLightStepsCount = count;
  72465. },
  72466. enumerable: true,
  72467. configurable: true
  72468. });
  72469. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  72470. get: function () {
  72471. return this._motionBlurSamples;
  72472. },
  72473. set: function (samples) {
  72474. if (this.motionBlurPostProcess) {
  72475. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  72476. }
  72477. this._motionBlurSamples = samples;
  72478. },
  72479. enumerable: true,
  72480. configurable: true
  72481. });
  72482. StandardRenderingPipeline.prototype._buildPipeline = function () {
  72483. var _this = this;
  72484. var ratio = this._ratio;
  72485. var scene = this._scene;
  72486. this._disposePostProcesses();
  72487. this._reset();
  72488. // Create pass post-process
  72489. if (!this._basePostProcess) {
  72490. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  72491. this.originalPostProcess.onApply = function (effect) {
  72492. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  72493. };
  72494. }
  72495. else {
  72496. this.originalPostProcess = this._basePostProcess;
  72497. }
  72498. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  72499. this._currentDepthOfFieldSource = this.originalPostProcess;
  72500. if (this._vlsEnabled) {
  72501. // Create volumetric light
  72502. this._createVolumetricLightPostProcess(scene, ratio);
  72503. // Create volumetric light final post-process
  72504. 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);
  72505. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  72506. }
  72507. if (this._bloomEnabled) {
  72508. // Create down sample X4 post-process
  72509. this._createDownSampleX4PostProcess(scene, ratio / 2);
  72510. // Create bright pass post-process
  72511. this._createBrightPassPostProcess(scene, ratio / 2);
  72512. // Create gaussian blur post-processes (down sampling blurs)
  72513. this._createBlurPostProcesses(scene, ratio / 4, 1);
  72514. // Create texture adder post-process
  72515. this._createTextureAdderPostProcess(scene, ratio);
  72516. // Create depth-of-field source post-process
  72517. 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);
  72518. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  72519. }
  72520. if (this._lensFlareEnabled) {
  72521. // Create lens flare post-process
  72522. this._createLensFlarePostProcess(scene, ratio);
  72523. // Create depth-of-field source post-process post lens-flare and disable it now
  72524. 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);
  72525. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  72526. }
  72527. if (this._hdrEnabled) {
  72528. // Create luminance
  72529. this._createLuminancePostProcesses(scene, this._floatTextureType);
  72530. // Create HDR
  72531. this._createHdrPostProcess(scene, ratio);
  72532. // Create depth-of-field source post-process post hdr and disable it now
  72533. 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);
  72534. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  72535. }
  72536. if (this._depthOfFieldEnabled) {
  72537. // Create gaussian blur used by depth-of-field
  72538. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  72539. // Create depth-of-field post-process
  72540. this._createDepthOfFieldPostProcess(scene, ratio);
  72541. }
  72542. if (this._motionBlurEnabled) {
  72543. // Create motion blur post-process
  72544. this._createMotionBlurPostProcess(scene, ratio);
  72545. }
  72546. if (this._cameras !== null) {
  72547. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  72548. }
  72549. };
  72550. // Down Sample X4 Post-Processs
  72551. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  72552. var _this = this;
  72553. var downSampleX4Offsets = new Array(32);
  72554. 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);
  72555. this.downSampleX4PostProcess.onApply = function (effect) {
  72556. var id = 0;
  72557. var width = _this.downSampleX4PostProcess.width;
  72558. var height = _this.downSampleX4PostProcess.height;
  72559. for (var i = -2; i < 2; i++) {
  72560. for (var j = -2; j < 2; j++) {
  72561. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  72562. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  72563. id += 2;
  72564. }
  72565. }
  72566. effect.setArray2("dsOffsets", downSampleX4Offsets);
  72567. };
  72568. // Add to pipeline
  72569. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  72570. };
  72571. // Brightpass Post-Process
  72572. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  72573. var _this = this;
  72574. var brightOffsets = new Array(8);
  72575. 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);
  72576. this.brightPassPostProcess.onApply = function (effect) {
  72577. var sU = (1.0 / _this.brightPassPostProcess.width);
  72578. var sV = (1.0 / _this.brightPassPostProcess.height);
  72579. brightOffsets[0] = -0.5 * sU;
  72580. brightOffsets[1] = 0.5 * sV;
  72581. brightOffsets[2] = 0.5 * sU;
  72582. brightOffsets[3] = 0.5 * sV;
  72583. brightOffsets[4] = -0.5 * sU;
  72584. brightOffsets[5] = -0.5 * sV;
  72585. brightOffsets[6] = 0.5 * sU;
  72586. brightOffsets[7] = -0.5 * sV;
  72587. effect.setArray2("dsOffsets", brightOffsets);
  72588. effect.setFloat("brightThreshold", _this.brightThreshold);
  72589. };
  72590. // Add to pipeline
  72591. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  72592. };
  72593. // Create blur H&V post-processes
  72594. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  72595. var _this = this;
  72596. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  72597. var engine = scene.getEngine();
  72598. 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);
  72599. 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);
  72600. blurX.onActivateObservable.add(function () {
  72601. var dw = blurX.width / engine.getRenderWidth();
  72602. blurX.kernel = _this[blurWidthKey] * dw;
  72603. });
  72604. blurY.onActivateObservable.add(function () {
  72605. var dw = blurY.height / engine.getRenderHeight();
  72606. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  72607. });
  72608. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  72609. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  72610. this.blurHPostProcesses.push(blurX);
  72611. this.blurVPostProcesses.push(blurY);
  72612. };
  72613. // Create texture adder post-process
  72614. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  72615. var _this = this;
  72616. 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);
  72617. this.textureAdderPostProcess.onApply = function (effect) {
  72618. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  72619. effect.setTexture("lensSampler", _this.lensTexture);
  72620. effect.setFloat("exposure", _this.exposure);
  72621. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  72622. };
  72623. // Add to pipeline
  72624. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  72625. };
  72626. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  72627. var _this = this;
  72628. var geometryRenderer = scene.enableGeometryBufferRenderer();
  72629. geometryRenderer.enablePosition = true;
  72630. var geometry = geometryRenderer.getGBuffer();
  72631. // Base post-process
  72632. 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));
  72633. var depthValues = BABYLON.Vector2.Zero();
  72634. this.volumetricLightPostProcess.onApply = function (effect) {
  72635. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  72636. var generator = _this.sourceLight.getShadowGenerator();
  72637. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  72638. effect.setTexture("positionSampler", geometry.textures[2]);
  72639. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  72640. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  72641. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  72642. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  72643. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  72644. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  72645. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  72646. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  72647. effect.setVector2("depthValues", depthValues);
  72648. }
  72649. };
  72650. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  72651. // Smooth
  72652. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  72653. // Merge
  72654. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  72655. this.volumetricLightMergePostProces.onApply = function (effect) {
  72656. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  72657. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  72658. };
  72659. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  72660. };
  72661. // Create luminance
  72662. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  72663. var _this = this;
  72664. // Create luminance
  72665. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  72666. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  72667. var offsets = [];
  72668. this.luminancePostProcess.onApply = function (effect) {
  72669. var sU = (1.0 / _this.luminancePostProcess.width);
  72670. var sV = (1.0 / _this.luminancePostProcess.height);
  72671. offsets[0] = -0.5 * sU;
  72672. offsets[1] = 0.5 * sV;
  72673. offsets[2] = 0.5 * sU;
  72674. offsets[3] = 0.5 * sV;
  72675. offsets[4] = -0.5 * sU;
  72676. offsets[5] = -0.5 * sV;
  72677. offsets[6] = 0.5 * sU;
  72678. offsets[7] = -0.5 * sV;
  72679. effect.setArray2("lumOffsets", offsets);
  72680. };
  72681. // Add to pipeline
  72682. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  72683. // Create down sample luminance
  72684. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  72685. var size = Math.pow(3, i);
  72686. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  72687. if (i === 0) {
  72688. defines += "#define FINAL_DOWN_SAMPLER";
  72689. }
  72690. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  72691. this.luminanceDownSamplePostProcesses.push(postProcess);
  72692. }
  72693. // Create callbacks and add effects
  72694. var lastLuminance = this.luminancePostProcess;
  72695. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  72696. var downSampleOffsets = new Array(18);
  72697. pp.onApply = function (effect) {
  72698. if (!lastLuminance) {
  72699. return;
  72700. }
  72701. var id = 0;
  72702. for (var x = -1; x < 2; x++) {
  72703. for (var y = -1; y < 2; y++) {
  72704. downSampleOffsets[id] = x / lastLuminance.width;
  72705. downSampleOffsets[id + 1] = y / lastLuminance.height;
  72706. id += 2;
  72707. }
  72708. }
  72709. effect.setArray2("dsOffsets", downSampleOffsets);
  72710. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  72711. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72712. lastLuminance = _this.luminancePostProcess;
  72713. }
  72714. else {
  72715. lastLuminance = pp;
  72716. }
  72717. };
  72718. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72719. pp.onAfterRender = function (effect) {
  72720. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  72721. 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);
  72722. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  72723. };
  72724. }
  72725. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  72726. });
  72727. };
  72728. // Create HDR post-process
  72729. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  72730. var _this = this;
  72731. 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);
  72732. var outputLiminance = 1;
  72733. var time = 0;
  72734. var lastTime = 0;
  72735. this.hdrPostProcess.onApply = function (effect) {
  72736. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  72737. time += scene.getEngine().getDeltaTime();
  72738. if (outputLiminance < 0) {
  72739. outputLiminance = _this._hdrCurrentLuminance;
  72740. }
  72741. else {
  72742. var dt = (lastTime - time) / 1000.0;
  72743. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  72744. outputLiminance += _this.hdrDecreaseRate * dt;
  72745. }
  72746. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  72747. outputLiminance -= _this.hdrIncreaseRate * dt;
  72748. }
  72749. else {
  72750. outputLiminance = _this._hdrCurrentLuminance;
  72751. }
  72752. }
  72753. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  72754. effect.setFloat("averageLuminance", outputLiminance);
  72755. lastTime = time;
  72756. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  72757. };
  72758. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  72759. };
  72760. // Create lens flare post-process
  72761. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  72762. var _this = this;
  72763. 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);
  72764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  72765. this._createBlurPostProcesses(scene, ratio / 4, 2);
  72766. 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);
  72767. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  72768. var resolution = new BABYLON.Vector2(0, 0);
  72769. // Lens flare
  72770. this.lensFlarePostProcess.onApply = function (effect) {
  72771. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  72772. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  72773. effect.setFloat("strength", _this.lensFlareStrength);
  72774. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  72775. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  72776. // Shift
  72777. resolution.x = _this.lensFlarePostProcess.width;
  72778. resolution.y = _this.lensFlarePostProcess.height;
  72779. effect.setVector2("resolution", resolution);
  72780. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  72781. };
  72782. // Compose
  72783. 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);
  72784. 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);
  72785. this.lensFlareComposePostProcess.onApply = function (effect) {
  72786. if (!_this._scene.activeCamera) {
  72787. return;
  72788. }
  72789. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72790. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  72791. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  72792. // Lens start rotation matrix
  72793. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  72794. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  72795. 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));
  72796. camRot *= 4.0;
  72797. 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);
  72798. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  72799. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  72800. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  72801. };
  72802. };
  72803. // Create depth-of-field post-process
  72804. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  72805. var _this = this;
  72806. 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);
  72807. this.depthOfFieldPostProcess.onApply = function (effect) {
  72808. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72809. effect.setTexture("depthSampler", _this._getDepthTexture());
  72810. effect.setFloat("distance", _this.depthOfFieldDistance);
  72811. };
  72812. // Add to pipeline
  72813. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  72814. };
  72815. // Create motion blur post-process
  72816. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  72817. var _this = this;
  72818. 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);
  72819. var motionScale = 0;
  72820. var prevViewProjection = BABYLON.Matrix.Identity();
  72821. var invViewProjection = BABYLON.Matrix.Identity();
  72822. var viewProjection = BABYLON.Matrix.Identity();
  72823. var screenSize = BABYLON.Vector2.Zero();
  72824. this.motionBlurPostProcess.onApply = function (effect) {
  72825. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  72826. viewProjection.invertToRef(invViewProjection);
  72827. effect.setMatrix("inverseViewProjection", invViewProjection);
  72828. effect.setMatrix("prevViewProjection", prevViewProjection);
  72829. prevViewProjection = viewProjection;
  72830. screenSize.x = _this.motionBlurPostProcess.width;
  72831. screenSize.y = _this.motionBlurPostProcess.height;
  72832. effect.setVector2("screenSize", screenSize);
  72833. motionScale = scene.getEngine().getFps() / 60.0;
  72834. effect.setFloat("motionScale", motionScale);
  72835. effect.setFloat("motionStrength", _this.motionStrength);
  72836. effect.setTexture("depthSampler", _this._getDepthTexture());
  72837. };
  72838. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  72839. };
  72840. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  72841. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  72842. var renderer = this._scene.enableGeometryBufferRenderer();
  72843. return renderer.getGBuffer().textures[0];
  72844. }
  72845. return this._scene.enableDepthRenderer().getDepthMap();
  72846. };
  72847. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  72848. for (var i = 0; i < this._cameras.length; i++) {
  72849. var camera = this._cameras[i];
  72850. if (this.originalPostProcess) {
  72851. this.originalPostProcess.dispose(camera);
  72852. }
  72853. if (this.downSampleX4PostProcess) {
  72854. this.downSampleX4PostProcess.dispose(camera);
  72855. }
  72856. if (this.brightPassPostProcess) {
  72857. this.brightPassPostProcess.dispose(camera);
  72858. }
  72859. if (this.textureAdderPostProcess) {
  72860. this.textureAdderPostProcess.dispose(camera);
  72861. }
  72862. if (this.textureAdderFinalPostProcess) {
  72863. this.textureAdderFinalPostProcess.dispose(camera);
  72864. }
  72865. if (this.volumetricLightPostProcess) {
  72866. this.volumetricLightPostProcess.dispose(camera);
  72867. }
  72868. if (this.volumetricLightSmoothXPostProcess) {
  72869. this.volumetricLightSmoothXPostProcess.dispose(camera);
  72870. }
  72871. if (this.volumetricLightSmoothYPostProcess) {
  72872. this.volumetricLightSmoothYPostProcess.dispose(camera);
  72873. }
  72874. if (this.volumetricLightMergePostProces) {
  72875. this.volumetricLightMergePostProces.dispose(camera);
  72876. }
  72877. if (this.volumetricLightFinalPostProcess) {
  72878. this.volumetricLightFinalPostProcess.dispose(camera);
  72879. }
  72880. if (this.lensFlarePostProcess) {
  72881. this.lensFlarePostProcess.dispose(camera);
  72882. }
  72883. if (this.lensFlareComposePostProcess) {
  72884. this.lensFlareComposePostProcess.dispose(camera);
  72885. }
  72886. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  72887. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  72888. }
  72889. if (this.luminancePostProcess) {
  72890. this.luminancePostProcess.dispose(camera);
  72891. }
  72892. if (this.hdrPostProcess) {
  72893. this.hdrPostProcess.dispose(camera);
  72894. }
  72895. if (this.hdrFinalPostProcess) {
  72896. this.hdrFinalPostProcess.dispose(camera);
  72897. }
  72898. if (this.depthOfFieldPostProcess) {
  72899. this.depthOfFieldPostProcess.dispose(camera);
  72900. }
  72901. if (this.motionBlurPostProcess) {
  72902. this.motionBlurPostProcess.dispose(camera);
  72903. }
  72904. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  72905. this.blurHPostProcesses[j].dispose(camera);
  72906. }
  72907. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  72908. this.blurVPostProcesses[j].dispose(camera);
  72909. }
  72910. }
  72911. this.originalPostProcess = null;
  72912. this.downSampleX4PostProcess = null;
  72913. this.brightPassPostProcess = null;
  72914. this.textureAdderPostProcess = null;
  72915. this.textureAdderFinalPostProcess = null;
  72916. this.volumetricLightPostProcess = null;
  72917. this.volumetricLightSmoothXPostProcess = null;
  72918. this.volumetricLightSmoothYPostProcess = null;
  72919. this.volumetricLightMergePostProces = null;
  72920. this.volumetricLightFinalPostProcess = null;
  72921. this.lensFlarePostProcess = null;
  72922. this.lensFlareComposePostProcess = null;
  72923. this.luminancePostProcess = null;
  72924. this.hdrPostProcess = null;
  72925. this.hdrFinalPostProcess = null;
  72926. this.depthOfFieldPostProcess = null;
  72927. this.motionBlurPostProcess = null;
  72928. this.luminanceDownSamplePostProcesses = [];
  72929. this.blurHPostProcesses = [];
  72930. this.blurVPostProcesses = [];
  72931. };
  72932. // Dispose
  72933. StandardRenderingPipeline.prototype.dispose = function () {
  72934. this._disposePostProcesses();
  72935. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  72936. _super.prototype.dispose.call(this);
  72937. };
  72938. // Serialize rendering pipeline
  72939. StandardRenderingPipeline.prototype.serialize = function () {
  72940. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72941. serializationObject.customType = "StandardRenderingPipeline";
  72942. return serializationObject;
  72943. };
  72944. /**
  72945. * Static members
  72946. */
  72947. // Parse serialized pipeline
  72948. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  72949. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  72950. };
  72951. // Luminance steps
  72952. StandardRenderingPipeline.LuminanceSteps = 6;
  72953. __decorate([
  72954. BABYLON.serialize()
  72955. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  72956. __decorate([
  72957. BABYLON.serialize()
  72958. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  72959. __decorate([
  72960. BABYLON.serialize()
  72961. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  72962. __decorate([
  72963. BABYLON.serialize()
  72964. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  72965. __decorate([
  72966. BABYLON.serializeAsTexture("lensTexture")
  72967. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  72968. __decorate([
  72969. BABYLON.serialize()
  72970. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  72971. __decorate([
  72972. BABYLON.serialize()
  72973. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  72974. __decorate([
  72975. BABYLON.serialize()
  72976. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  72977. __decorate([
  72978. BABYLON.serialize()
  72979. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  72980. __decorate([
  72981. BABYLON.serialize()
  72982. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  72983. __decorate([
  72984. BABYLON.serialize()
  72985. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  72986. __decorate([
  72987. BABYLON.serializeAsTexture("lensColorTexture")
  72988. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  72989. __decorate([
  72990. BABYLON.serialize()
  72991. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  72992. __decorate([
  72993. BABYLON.serialize()
  72994. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  72995. __decorate([
  72996. BABYLON.serialize()
  72997. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  72998. __decorate([
  72999. BABYLON.serialize()
  73000. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  73001. __decorate([
  73002. BABYLON.serializeAsTexture("lensStarTexture")
  73003. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  73004. __decorate([
  73005. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  73006. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  73007. __decorate([
  73008. BABYLON.serialize()
  73009. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  73010. __decorate([
  73011. BABYLON.serialize()
  73012. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  73013. __decorate([
  73014. BABYLON.serialize()
  73015. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  73016. __decorate([
  73017. BABYLON.serialize()
  73018. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  73019. __decorate([
  73020. BABYLON.serialize()
  73021. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  73022. __decorate([
  73023. BABYLON.serialize()
  73024. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  73025. __decorate([
  73026. BABYLON.serialize()
  73027. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  73028. __decorate([
  73029. BABYLON.serialize()
  73030. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  73031. __decorate([
  73032. BABYLON.serialize()
  73033. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  73034. __decorate([
  73035. BABYLON.serialize()
  73036. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  73037. __decorate([
  73038. BABYLON.serialize()
  73039. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  73040. __decorate([
  73041. BABYLON.serialize()
  73042. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  73043. return StandardRenderingPipeline;
  73044. }(BABYLON.PostProcessRenderPipeline));
  73045. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  73046. })(BABYLON || (BABYLON = {}));
  73047. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  73048. "use strict";
  73049. var BABYLON;
  73050. (function (BABYLON) {
  73051. var FxaaPostProcess = /** @class */ (function (_super) {
  73052. __extends(FxaaPostProcess, _super);
  73053. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73054. if (camera === void 0) { camera = null; }
  73055. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73056. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  73057. _this.onApplyObservable.add(function (effect) {
  73058. var texelSize = _this.texelSize;
  73059. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  73060. });
  73061. return _this;
  73062. }
  73063. return FxaaPostProcess;
  73064. }(BABYLON.PostProcess));
  73065. BABYLON.FxaaPostProcess = FxaaPostProcess;
  73066. })(BABYLON || (BABYLON = {}));
  73067. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  73068. "use strict";
  73069. var BABYLON;
  73070. (function (BABYLON) {
  73071. /**
  73072. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  73073. */
  73074. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  73075. __extends(ChromaticAberrationPostProcess, _super);
  73076. /**
  73077. * Creates a new instance ChromaticAberrationPostProcess
  73078. * @param name The name of the effect.
  73079. * @param screenWidth The width of the screen to apply the effect on.
  73080. * @param screenHeight The height of the screen to apply the effect on.
  73081. * @param options The required width/height ratio to downsize to before computing the render pass.
  73082. * @param camera The camera to apply the render pass to.
  73083. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73084. * @param engine The engine which the post process will be applied. (default: current engine)
  73085. * @param reusable If the post process can be reused on the same frame. (default: false)
  73086. * @param textureType Type of textures used when performing the post process. (default: 0)
  73087. * @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)
  73088. */
  73089. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73090. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73091. if (blockCompilation === void 0) { blockCompilation = false; }
  73092. 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;
  73093. /**
  73094. * The amount of seperation of rgb channels (default: 30)
  73095. */
  73096. _this.aberrationAmount = 30;
  73097. /**
  73098. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  73099. */
  73100. _this.radialIntensity = 0;
  73101. /**
  73102. * 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))
  73103. */
  73104. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  73105. /**
  73106. * 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))
  73107. */
  73108. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  73109. _this.onApplyObservable.add(function (effect) {
  73110. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  73111. effect.setFloat('screen_width', screenWidth);
  73112. effect.setFloat('screen_height', screenHeight);
  73113. effect.setFloat('radialIntensity', _this.radialIntensity);
  73114. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  73115. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  73116. });
  73117. return _this;
  73118. }
  73119. return ChromaticAberrationPostProcess;
  73120. }(BABYLON.PostProcess));
  73121. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  73122. })(BABYLON || (BABYLON = {}));
  73123. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  73124. "use strict";
  73125. var BABYLON;
  73126. (function (BABYLON) {
  73127. /**
  73128. * The GrainPostProcess adds noise to the image at mid luminance levels
  73129. */
  73130. var GrainPostProcess = /** @class */ (function (_super) {
  73131. __extends(GrainPostProcess, _super);
  73132. /**
  73133. * Creates a new instance of @see GrainPostProcess
  73134. * @param name The name of the effect.
  73135. * @param options The required width/height ratio to downsize to before computing the render pass.
  73136. * @param camera The camera to apply the render pass to.
  73137. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73138. * @param engine The engine which the post process will be applied. (default: current engine)
  73139. * @param reusable If the post process can be reused on the same frame. (default: false)
  73140. * @param textureType Type of textures used when performing the post process. (default: 0)
  73141. * @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)
  73142. */
  73143. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73144. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73145. if (blockCompilation === void 0) { blockCompilation = false; }
  73146. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73147. /**
  73148. * The intensity of the grain added (default: 30)
  73149. */
  73150. _this.intensity = 30;
  73151. /**
  73152. * If the grain should be randomized on every frame
  73153. */
  73154. _this.animated = false;
  73155. _this.onApplyObservable.add(function (effect) {
  73156. effect.setFloat('intensity', _this.intensity);
  73157. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  73158. });
  73159. return _this;
  73160. }
  73161. return GrainPostProcess;
  73162. }(BABYLON.PostProcess));
  73163. BABYLON.GrainPostProcess = GrainPostProcess;
  73164. })(BABYLON || (BABYLON = {}));
  73165. //# sourceMappingURL=babylon.grainPostProcess.js.map
  73166. "use strict";
  73167. var BABYLON;
  73168. (function (BABYLON) {
  73169. /**
  73170. * The SharpenPostProcess applies a sharpen kernel to every pixel
  73171. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  73172. */
  73173. var SharpenPostProcess = /** @class */ (function (_super) {
  73174. __extends(SharpenPostProcess, _super);
  73175. /**
  73176. * Creates a new instance ConvolutionPostProcess
  73177. * @param name The name of the effect.
  73178. * @param options The required width/height ratio to downsize to before computing the render pass.
  73179. * @param camera The camera to apply the render pass to.
  73180. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73181. * @param engine The engine which the post process will be applied. (default: current engine)
  73182. * @param reusable If the post process can be reused on the same frame. (default: false)
  73183. * @param textureType Type of textures used when performing the post process. (default: 0)
  73184. * @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)
  73185. */
  73186. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73187. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73188. if (blockCompilation === void 0) { blockCompilation = false; }
  73189. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73190. /**
  73191. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  73192. */
  73193. _this.colorAmount = 1.0;
  73194. /**
  73195. * How much sharpness should be applied (default: 0.3)
  73196. */
  73197. _this.edgeAmount = 0.3;
  73198. _this.onApply = function (effect) {
  73199. effect.setFloat2("screenSize", _this.width, _this.height);
  73200. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  73201. };
  73202. return _this;
  73203. }
  73204. return SharpenPostProcess;
  73205. }(BABYLON.PostProcess));
  73206. BABYLON.SharpenPostProcess = SharpenPostProcess;
  73207. })(BABYLON || (BABYLON = {}));
  73208. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  73209. "use strict";
  73210. var BABYLON;
  73211. (function (BABYLON) {
  73212. /**
  73213. * The Blur Post Process which blurs an image based on a kernel and direction.
  73214. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  73215. */
  73216. var BlurPostProcess = /** @class */ (function (_super) {
  73217. __extends(BlurPostProcess, _super);
  73218. /**
  73219. * Creates a new instance BlurPostProcess
  73220. * @param name The name of the effect.
  73221. * @param direction The direction in which to blur the image.
  73222. * @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.
  73223. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73224. * @param camera The camera to apply the render pass to.
  73225. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73226. * @param engine The engine which the post process will be applied. (default: current engine)
  73227. * @param reusable If the post process can be reused on the same frame. (default: false)
  73228. * @param textureType Type of textures used when performing the post process. (default: 0)
  73229. * @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)
  73230. */
  73231. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  73232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73233. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73234. if (defines === void 0) { defines = ""; }
  73235. if (blockCompilation === void 0) { blockCompilation = false; }
  73236. 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;
  73237. _this.direction = direction;
  73238. _this.blockCompilation = blockCompilation;
  73239. _this._packedFloat = false;
  73240. _this._staticDefines = "";
  73241. _this._staticDefines = defines;
  73242. _this.onApplyObservable.add(function (effect) {
  73243. if (_this._outputTexture) {
  73244. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  73245. }
  73246. else {
  73247. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  73248. }
  73249. });
  73250. _this.kernel = kernel;
  73251. return _this;
  73252. }
  73253. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  73254. /**
  73255. * Gets the length in pixels of the blur sample region
  73256. */
  73257. get: function () {
  73258. return this._idealKernel;
  73259. },
  73260. /**
  73261. * Sets the length in pixels of the blur sample region
  73262. */
  73263. set: function (v) {
  73264. if (this._idealKernel === v) {
  73265. return;
  73266. }
  73267. v = Math.max(v, 1);
  73268. this._idealKernel = v;
  73269. this._kernel = this._nearestBestKernel(v);
  73270. if (!this.blockCompilation) {
  73271. this._updateParameters();
  73272. }
  73273. },
  73274. enumerable: true,
  73275. configurable: true
  73276. });
  73277. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  73278. /**
  73279. * Gets wether or not the blur is unpacking/repacking floats
  73280. */
  73281. get: function () {
  73282. return this._packedFloat;
  73283. },
  73284. /**
  73285. * Sets wether or not the blur needs to unpack/repack floats
  73286. */
  73287. set: function (v) {
  73288. if (this._packedFloat === v) {
  73289. return;
  73290. }
  73291. this._packedFloat = v;
  73292. if (!this.blockCompilation) {
  73293. this._updateParameters();
  73294. }
  73295. },
  73296. enumerable: true,
  73297. configurable: true
  73298. });
  73299. /**
  73300. * Updates the effect with the current post process compile time values and recompiles the shader.
  73301. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73302. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73303. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73304. * @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
  73305. * @param onCompiled Called when the shader has been compiled.
  73306. * @param onError Called if there is an error when compiling a shader.
  73307. */
  73308. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73309. if (defines === void 0) { defines = null; }
  73310. if (uniforms === void 0) { uniforms = null; }
  73311. if (samplers === void 0) { samplers = null; }
  73312. this._updateParameters(onCompiled, onError);
  73313. };
  73314. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  73315. // Generate sampling offsets and weights
  73316. var N = this._kernel;
  73317. var centerIndex = (N - 1) / 2;
  73318. // Generate Gaussian sampling weights over kernel
  73319. var offsets = [];
  73320. var weights = [];
  73321. var totalWeight = 0;
  73322. for (var i = 0; i < N; i++) {
  73323. var u = i / (N - 1);
  73324. var w = this._gaussianWeight(u * 2.0 - 1);
  73325. offsets[i] = (i - centerIndex);
  73326. weights[i] = w;
  73327. totalWeight += w;
  73328. }
  73329. // Normalize weights
  73330. for (var i = 0; i < weights.length; i++) {
  73331. weights[i] /= totalWeight;
  73332. }
  73333. // Optimize: combine samples to take advantage of hardware linear sampling
  73334. // Walk from left to center, combining pairs (symmetrically)
  73335. var linearSamplingWeights = [];
  73336. var linearSamplingOffsets = [];
  73337. var linearSamplingMap = [];
  73338. for (var i = 0; i <= centerIndex; i += 2) {
  73339. var j = Math.min(i + 1, Math.floor(centerIndex));
  73340. var singleCenterSample = i === j;
  73341. if (singleCenterSample) {
  73342. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73343. }
  73344. else {
  73345. var sharedCell = j === centerIndex;
  73346. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  73347. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  73348. if (offsetLinear === 0) {
  73349. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73350. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  73351. }
  73352. else {
  73353. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  73354. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  73355. }
  73356. }
  73357. }
  73358. for (var i = 0; i < linearSamplingMap.length; i++) {
  73359. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  73360. linearSamplingWeights[i] = linearSamplingMap[i].w;
  73361. }
  73362. // Replace with optimized
  73363. offsets = linearSamplingOffsets;
  73364. weights = linearSamplingWeights;
  73365. // Generate shaders
  73366. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  73367. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  73368. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  73369. var defines = "";
  73370. defines += this._staticDefines;
  73371. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  73372. if (this._staticDefines.indexOf("DOF") != -1) {
  73373. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  73374. varyingCount--;
  73375. }
  73376. for (var i = 0; i < varyingCount; i++) {
  73377. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  73378. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  73379. }
  73380. var depCount = 0;
  73381. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  73382. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  73383. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  73384. depCount++;
  73385. }
  73386. if (this.packedFloat) {
  73387. defines += "#define PACKEDFLOAT 1";
  73388. }
  73389. this.blockCompilation = false;
  73390. _super.prototype.updateEffect.call(this, defines, null, null, {
  73391. varyingCount: varyingCount,
  73392. depCount: depCount
  73393. }, onCompiled, onError);
  73394. };
  73395. /**
  73396. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  73397. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  73398. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  73399. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  73400. * The gaps between physical kernels are compensated for in the weighting of the samples
  73401. * @param idealKernel Ideal blur kernel.
  73402. * @return Nearest best kernel.
  73403. */
  73404. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  73405. var v = Math.round(idealKernel);
  73406. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  73407. var k = _a[_i];
  73408. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  73409. return Math.max(k, 3);
  73410. }
  73411. }
  73412. return Math.max(v, 3);
  73413. };
  73414. /**
  73415. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  73416. * @param x The point on the Gaussian distribution to sample.
  73417. * @return the value of the Gaussian function at x.
  73418. */
  73419. BlurPostProcess.prototype._gaussianWeight = function (x) {
  73420. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  73421. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  73422. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  73423. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  73424. // truncated at around 1.3% of peak strength.
  73425. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  73426. var sigma = (1 / 3);
  73427. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  73428. var exponent = -((x * x) / (2.0 * sigma * sigma));
  73429. var weight = (1.0 / denominator) * Math.exp(exponent);
  73430. return weight;
  73431. };
  73432. /**
  73433. * Generates a string that can be used as a floating point number in GLSL.
  73434. * @param x Value to print.
  73435. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  73436. * @return GLSL float string.
  73437. */
  73438. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  73439. if (decimalFigures === void 0) { decimalFigures = 8; }
  73440. return x.toFixed(decimalFigures).replace(/0+$/, '');
  73441. };
  73442. return BlurPostProcess;
  73443. }(BABYLON.PostProcess));
  73444. BABYLON.BlurPostProcess = BlurPostProcess;
  73445. })(BABYLON || (BABYLON = {}));
  73446. //# sourceMappingURL=babylon.blurPostProcess.js.map
  73447. "use strict";
  73448. var BABYLON;
  73449. (function (BABYLON) {
  73450. /**
  73451. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  73452. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  73453. * based on samples that have a large difference in distance than the center pixel.
  73454. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73455. */
  73456. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  73457. __extends(DepthOfFieldBlurPostProcess, _super);
  73458. /**
  73459. * Creates a new instance CircleOfConfusionPostProcess
  73460. * @param name The name of the effect.
  73461. * @param scene The scene the effect belongs to.
  73462. * @param direction The direction the blur should be applied.
  73463. * @param kernel The size of the kernel used to blur.
  73464. * @param options The required width/height ratio to downsize to before computing the render pass.
  73465. * @param camera The camera to apply the render pass to.
  73466. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  73467. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  73468. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73469. * @param engine The engine which the post process will be applied. (default: current engine)
  73470. * @param reusable If the post process can be reused on the same frame. (default: false)
  73471. * @param textureType Type of textures used when performing the post process. (default: 0)
  73472. * @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)
  73473. */
  73474. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  73475. if (imageToBlur === void 0) { imageToBlur = null; }
  73476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73477. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73478. if (blockCompilation === void 0) { blockCompilation = false; }
  73479. 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;
  73480. _this.direction = direction;
  73481. _this.onApplyObservable.add(function (effect) {
  73482. if (imageToBlur != null) {
  73483. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  73484. }
  73485. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73486. if (scene.activeCamera) {
  73487. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73488. }
  73489. });
  73490. return _this;
  73491. }
  73492. return DepthOfFieldBlurPostProcess;
  73493. }(BABYLON.BlurPostProcess));
  73494. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  73495. })(BABYLON || (BABYLON = {}));
  73496. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  73497. "use strict";
  73498. var BABYLON;
  73499. (function (BABYLON) {
  73500. /**
  73501. * Options to be set when merging outputs from the default pipeline.
  73502. */
  73503. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  73504. function DepthOfFieldMergePostProcessOptions() {
  73505. }
  73506. return DepthOfFieldMergePostProcessOptions;
  73507. }());
  73508. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  73509. /**
  73510. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73511. */
  73512. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  73513. __extends(DepthOfFieldMergePostProcess, _super);
  73514. /**
  73515. * Creates a new instance of DepthOfFieldMergePostProcess
  73516. * @param name The name of the effect.
  73517. * @param originalFromInput Post process which's input will be used for the merge.
  73518. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  73519. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  73520. * @param options The required width/height ratio to downsize to before computing the render pass.
  73521. * @param camera The camera to apply the render pass to.
  73522. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73523. * @param engine The engine which the post process will be applied. (default: current engine)
  73524. * @param reusable If the post process can be reused on the same frame. (default: false)
  73525. * @param textureType Type of textures used when performing the post process. (default: 0)
  73526. * @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)
  73527. */
  73528. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73529. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73530. if (blockCompilation === void 0) { blockCompilation = false; }
  73531. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73532. _this.blurSteps = blurSteps;
  73533. _this.onApplyObservable.add(function (effect) {
  73534. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73535. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73536. blurSteps.forEach(function (step, index) {
  73537. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  73538. });
  73539. });
  73540. if (!blockCompilation) {
  73541. _this.updateEffect();
  73542. }
  73543. return _this;
  73544. }
  73545. /**
  73546. * Updates the effect with the current post process compile time values and recompiles the shader.
  73547. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73548. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73549. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73550. * @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
  73551. * @param onCompiled Called when the shader has been compiled.
  73552. * @param onError Called if there is an error when compiling a shader.
  73553. */
  73554. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73555. if (defines === void 0) { defines = null; }
  73556. if (uniforms === void 0) { uniforms = null; }
  73557. if (samplers === void 0) { samplers = null; }
  73558. if (!defines) {
  73559. defines = "";
  73560. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  73561. }
  73562. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  73563. };
  73564. return DepthOfFieldMergePostProcess;
  73565. }(BABYLON.PostProcess));
  73566. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  73567. })(BABYLON || (BABYLON = {}));
  73568. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  73569. "use strict";
  73570. var BABYLON;
  73571. (function (BABYLON) {
  73572. /**
  73573. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  73574. */
  73575. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  73576. __extends(CircleOfConfusionPostProcess, _super);
  73577. /**
  73578. * Creates a new instance CircleOfConfusionPostProcess
  73579. * @param name The name of the effect.
  73580. * @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.
  73581. * @param options The required width/height ratio to downsize to before computing the render pass.
  73582. * @param camera The camera to apply the render pass to.
  73583. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73584. * @param engine The engine which the post process will be applied. (default: current engine)
  73585. * @param reusable If the post process can be reused on the same frame. (default: false)
  73586. * @param textureType Type of textures used when performing the post process. (default: 0)
  73587. * @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)
  73588. */
  73589. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73590. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73591. if (blockCompilation === void 0) { blockCompilation = false; }
  73592. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73593. /**
  73594. * 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.
  73595. */
  73596. _this.lensSize = 50;
  73597. /**
  73598. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73599. */
  73600. _this.fStop = 1.4;
  73601. /**
  73602. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73603. */
  73604. _this.focusDistance = 2000;
  73605. /**
  73606. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  73607. */
  73608. _this.focalLength = 50;
  73609. _this._depthTexture = null;
  73610. _this._depthTexture = depthTexture;
  73611. _this.onApplyObservable.add(function (effect) {
  73612. if (!_this._depthTexture) {
  73613. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  73614. return;
  73615. }
  73616. effect.setTexture("depthSampler", _this._depthTexture);
  73617. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  73618. var aperture = _this.lensSize / _this.fStop;
  73619. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  73620. effect.setFloat('focusDistance', _this.focusDistance);
  73621. effect.setFloat('cocPrecalculation', cocPrecalculation);
  73622. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  73623. });
  73624. return _this;
  73625. }
  73626. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  73627. /**
  73628. * 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.
  73629. */
  73630. set: function (value) {
  73631. this._depthTexture = value;
  73632. },
  73633. enumerable: true,
  73634. configurable: true
  73635. });
  73636. return CircleOfConfusionPostProcess;
  73637. }(BABYLON.PostProcess));
  73638. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  73639. })(BABYLON || (BABYLON = {}));
  73640. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  73641. "use strict";
  73642. var BABYLON;
  73643. (function (BABYLON) {
  73644. /**
  73645. * Specifies the level of max blur that should be applied when using the depth of field effect
  73646. */
  73647. var DepthOfFieldEffectBlurLevel;
  73648. (function (DepthOfFieldEffectBlurLevel) {
  73649. /**
  73650. * Subtle blur
  73651. */
  73652. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  73653. /**
  73654. * Medium blur
  73655. */
  73656. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  73657. /**
  73658. * Large blur
  73659. */
  73660. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  73661. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  73662. ;
  73663. /**
  73664. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  73665. */
  73666. var DepthOfFieldEffect = /** @class */ (function (_super) {
  73667. __extends(DepthOfFieldEffect, _super);
  73668. /**
  73669. * Creates a new instance DepthOfFieldEffect
  73670. * @param scene The scene the effect belongs to.
  73671. * @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.
  73672. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73673. * @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)
  73674. */
  73675. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  73676. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  73677. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73678. if (blockCompilation === void 0) { blockCompilation = false; }
  73679. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  73680. return _this._effects;
  73681. }, true) || this;
  73682. /**
  73683. * Internal post processes in depth of field effect
  73684. */
  73685. _this._effects = [];
  73686. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  73687. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73688. // 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)
  73689. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  73690. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73691. _this._depthOfFieldBlurY = [];
  73692. _this._depthOfFieldBlurX = [];
  73693. var blurCount = 1;
  73694. var kernelSize = 15;
  73695. switch (blurLevel) {
  73696. case DepthOfFieldEffectBlurLevel.High: {
  73697. blurCount = 3;
  73698. kernelSize = 51;
  73699. break;
  73700. }
  73701. case DepthOfFieldEffectBlurLevel.Medium: {
  73702. blurCount = 2;
  73703. kernelSize = 31;
  73704. break;
  73705. }
  73706. default: {
  73707. kernelSize = 15;
  73708. blurCount = 1;
  73709. break;
  73710. }
  73711. }
  73712. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  73713. var ratio = 1.0;
  73714. for (var i = 0; i < blurCount; i++) {
  73715. 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);
  73716. blurY.autoClear = false;
  73717. ratio = 0.75 / Math.pow(2, i);
  73718. 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);
  73719. blurX.autoClear = false;
  73720. _this._depthOfFieldBlurY.push(blurY);
  73721. _this._depthOfFieldBlurX.push(blurX);
  73722. }
  73723. // Set all post processes on the effect.
  73724. _this._effects = [_this._circleOfConfusion];
  73725. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  73726. _this._effects.push(_this._depthOfFieldBlurY[i]);
  73727. _this._effects.push(_this._depthOfFieldBlurX[i]);
  73728. }
  73729. // Merge blurred images with original image based on circleOfConfusion
  73730. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73731. _this._dofMerge.autoClear = false;
  73732. _this._effects.push(_this._dofMerge);
  73733. return _this;
  73734. }
  73735. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  73736. get: function () {
  73737. return this._circleOfConfusion.focalLength;
  73738. },
  73739. /**
  73740. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  73741. */
  73742. set: function (value) {
  73743. this._circleOfConfusion.focalLength = value;
  73744. },
  73745. enumerable: true,
  73746. configurable: true
  73747. });
  73748. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  73749. get: function () {
  73750. return this._circleOfConfusion.fStop;
  73751. },
  73752. /**
  73753. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73754. */
  73755. set: function (value) {
  73756. this._circleOfConfusion.fStop = value;
  73757. },
  73758. enumerable: true,
  73759. configurable: true
  73760. });
  73761. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  73762. get: function () {
  73763. return this._circleOfConfusion.focusDistance;
  73764. },
  73765. /**
  73766. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73767. */
  73768. set: function (value) {
  73769. this._circleOfConfusion.focusDistance = value;
  73770. },
  73771. enumerable: true,
  73772. configurable: true
  73773. });
  73774. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  73775. get: function () {
  73776. return this._circleOfConfusion.lensSize;
  73777. },
  73778. /**
  73779. * 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.
  73780. */
  73781. set: function (value) {
  73782. this._circleOfConfusion.lensSize = value;
  73783. },
  73784. enumerable: true,
  73785. configurable: true
  73786. });
  73787. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  73788. /**
  73789. * 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.
  73790. */
  73791. set: function (value) {
  73792. this._circleOfConfusion.depthTexture = value;
  73793. },
  73794. enumerable: true,
  73795. configurable: true
  73796. });
  73797. /**
  73798. * Disposes each of the internal effects for a given camera.
  73799. * @param camera The camera to dispose the effect on.
  73800. */
  73801. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  73802. for (var effect in this._effects) {
  73803. this._effects[effect].dispose(camera);
  73804. }
  73805. };
  73806. /**
  73807. * Internal
  73808. */
  73809. DepthOfFieldEffect.prototype._updateEffects = function () {
  73810. for (var effect in this._effects) {
  73811. this._effects[effect].updateEffect();
  73812. }
  73813. };
  73814. /**
  73815. * Internal
  73816. * @returns if all the contained post processes are ready.
  73817. */
  73818. DepthOfFieldEffect.prototype._isReady = function () {
  73819. for (var effect in this._effects) {
  73820. if (!this._effects[effect].isReady()) {
  73821. return false;
  73822. }
  73823. }
  73824. return true;
  73825. };
  73826. return DepthOfFieldEffect;
  73827. }(BABYLON.PostProcessRenderEffect));
  73828. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  73829. })(BABYLON || (BABYLON = {}));
  73830. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  73831. "use strict";
  73832. var BABYLON;
  73833. (function (BABYLON) {
  73834. /**
  73835. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73836. */
  73837. var BloomMergePostProcess = /** @class */ (function (_super) {
  73838. __extends(BloomMergePostProcess, _super);
  73839. /**
  73840. * Creates a new instance of @see BloomMergePostProcess
  73841. * @param name The name of the effect.
  73842. * @param originalFromInput Post process which's input will be used for the merge.
  73843. * @param blurred Blurred highlights post process which's output will be used.
  73844. * @param weight Weight of the bloom to be added to the original input.
  73845. * @param options The required width/height ratio to downsize to before computing the render pass.
  73846. * @param camera The camera to apply the render pass to.
  73847. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73848. * @param engine The engine which the post process will be applied. (default: current engine)
  73849. * @param reusable If the post process can be reused on the same frame. (default: false)
  73850. * @param textureType Type of textures used when performing the post process. (default: 0)
  73851. * @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)
  73852. */
  73853. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73854. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73855. if (blockCompilation === void 0) { blockCompilation = false; }
  73856. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73857. _this.weight = weight;
  73858. _this.onApplyObservable.add(function (effect) {
  73859. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73860. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  73861. effect.setFloat("bloomWeight", _this.weight);
  73862. });
  73863. if (!blockCompilation) {
  73864. _this.updateEffect();
  73865. }
  73866. return _this;
  73867. }
  73868. return BloomMergePostProcess;
  73869. }(BABYLON.PostProcess));
  73870. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  73871. })(BABYLON || (BABYLON = {}));
  73872. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  73873. "use strict";
  73874. var BABYLON;
  73875. (function (BABYLON) {
  73876. /**
  73877. * 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.
  73878. */
  73879. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  73880. __extends(ExtractHighlightsPostProcess, _super);
  73881. function ExtractHighlightsPostProcess(name, 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, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73885. /**
  73886. * The luminance threshold, pixels below this value will be set to black.
  73887. */
  73888. _this.threshold = 0.9;
  73889. /**
  73890. * Internal
  73891. */
  73892. _this._exposure = 1;
  73893. /**
  73894. * Post process which has the input texture to be used when performing highlight extraction
  73895. */
  73896. _this._inputPostProcess = null;
  73897. _this.onApplyObservable.add(function (effect) {
  73898. if (_this._inputPostProcess) {
  73899. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  73900. }
  73901. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  73902. effect.setFloat('exposure', _this._exposure);
  73903. });
  73904. return _this;
  73905. }
  73906. return ExtractHighlightsPostProcess;
  73907. }(BABYLON.PostProcess));
  73908. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  73909. })(BABYLON || (BABYLON = {}));
  73910. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  73911. "use strict";
  73912. var BABYLON;
  73913. (function (BABYLON) {
  73914. /**
  73915. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  73916. */
  73917. var BloomEffect = /** @class */ (function (_super) {
  73918. __extends(BloomEffect, _super);
  73919. /**
  73920. * Creates a new instance of @see BloomEffect
  73921. * @param scene The scene the effect belongs to.
  73922. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  73923. * @param bloomKernel The size of the kernel to be used when applying the blur.
  73924. * @param bloomWeight The the strength of bloom.
  73925. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73926. * @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)
  73927. */
  73928. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  73929. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73930. if (blockCompilation === void 0) { blockCompilation = false; }
  73931. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  73932. return _this._effects;
  73933. }, true) || this;
  73934. _this.bloomScale = bloomScale;
  73935. /**
  73936. * Internal
  73937. */
  73938. _this._effects = [];
  73939. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73940. _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);
  73941. _this._blurX.alwaysForcePOT = true;
  73942. _this._blurX.autoClear = false;
  73943. _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);
  73944. _this._blurY.alwaysForcePOT = true;
  73945. _this._blurY.autoClear = false;
  73946. _this.kernel = bloomKernel;
  73947. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  73948. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73949. _this._merge.autoClear = false;
  73950. _this._effects.push(_this._merge);
  73951. return _this;
  73952. }
  73953. Object.defineProperty(BloomEffect.prototype, "threshold", {
  73954. /**
  73955. * The luminance threshold to find bright areas of the image to bloom.
  73956. */
  73957. get: function () {
  73958. return this._downscale.threshold;
  73959. },
  73960. set: function (value) {
  73961. this._downscale.threshold = value;
  73962. },
  73963. enumerable: true,
  73964. configurable: true
  73965. });
  73966. Object.defineProperty(BloomEffect.prototype, "weight", {
  73967. /**
  73968. * The strength of the bloom.
  73969. */
  73970. get: function () {
  73971. return this._merge.weight;
  73972. },
  73973. set: function (value) {
  73974. this._merge.weight = value;
  73975. },
  73976. enumerable: true,
  73977. configurable: true
  73978. });
  73979. Object.defineProperty(BloomEffect.prototype, "kernel", {
  73980. /**
  73981. * Specifies the size of the bloom blur kernel, relative to the final output size
  73982. */
  73983. get: function () {
  73984. return this._blurX.kernel / this.bloomScale;
  73985. },
  73986. set: function (value) {
  73987. this._blurX.kernel = value * this.bloomScale;
  73988. this._blurY.kernel = value * this.bloomScale;
  73989. },
  73990. enumerable: true,
  73991. configurable: true
  73992. });
  73993. /**
  73994. * Disposes each of the internal effects for a given camera.
  73995. * @param camera The camera to dispose the effect on.
  73996. */
  73997. BloomEffect.prototype.disposeEffects = function (camera) {
  73998. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  73999. this._effects[effectIndex].dispose(camera);
  74000. }
  74001. };
  74002. /**
  74003. * Internal
  74004. */
  74005. BloomEffect.prototype._updateEffects = function () {
  74006. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74007. this._effects[effectIndex].updateEffect();
  74008. }
  74009. };
  74010. /**
  74011. * Internal
  74012. * @returns if all the contained post processes are ready.
  74013. */
  74014. BloomEffect.prototype._isReady = function () {
  74015. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74016. if (!this._effects[effectIndex].isReady()) {
  74017. return false;
  74018. }
  74019. }
  74020. return true;
  74021. };
  74022. return BloomEffect;
  74023. }(BABYLON.PostProcessRenderEffect));
  74024. BABYLON.BloomEffect = BloomEffect;
  74025. })(BABYLON || (BABYLON = {}));
  74026. //# sourceMappingURL=babylon.bloomEffect.js.map
  74027. "use strict";
  74028. var BABYLON;
  74029. (function (BABYLON) {
  74030. /**
  74031. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  74032. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  74033. */
  74034. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  74035. __extends(DefaultRenderingPipeline, _super);
  74036. /**
  74037. * @constructor
  74038. * @param {string} name - The rendering pipeline name
  74039. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74040. * @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)
  74041. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74042. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  74043. */
  74044. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  74045. if (automaticBuild === void 0) { automaticBuild = true; }
  74046. var _this = _super.call(this, scene.getEngine(), name) || this;
  74047. _this._originalCameras = [];
  74048. /**
  74049. * ID of the sharpen post process,
  74050. */
  74051. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  74052. /**
  74053. * ID of the image processing post process;
  74054. */
  74055. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  74056. /**
  74057. * ID of the Fast Approximate Anti-Aliasing post process;
  74058. */
  74059. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  74060. /**
  74061. * ID of the chromatic aberration post process,
  74062. */
  74063. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  74064. /**
  74065. * ID of the grain post process
  74066. */
  74067. _this.GrainPostProcessId = "GrainPostProcessEffect";
  74068. /**
  74069. * Animations which can be used to tweak settings over a period of time
  74070. */
  74071. _this.animations = [];
  74072. _this._imageProcessingConfigurationObserver = null;
  74073. // Values
  74074. _this._sharpenEnabled = false;
  74075. _this._bloomEnabled = false;
  74076. _this._depthOfFieldEnabled = false;
  74077. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  74078. _this._fxaaEnabled = false;
  74079. _this._imageProcessingEnabled = true;
  74080. _this._bloomScale = 0.5;
  74081. _this._chromaticAberrationEnabled = false;
  74082. _this._grainEnabled = false;
  74083. _this._buildAllowed = true;
  74084. _this._resizeObserver = null;
  74085. _this._hardwareScaleLevel = 1.0;
  74086. _this._bloomKernel = 64;
  74087. /**
  74088. * Specifies the weight of the bloom in the final rendering
  74089. */
  74090. _this._bloomWeight = 0.15;
  74091. /**
  74092. * Specifies the luma threshold for the area that will be blurred by the bloom
  74093. */
  74094. _this._bloomThreshold = 0.9;
  74095. _this._samples = 1;
  74096. _this._hasCleared = false;
  74097. _this._prevPostProcess = null;
  74098. _this._prevPrevPostProcess = null;
  74099. _this._cameras = cameras || [];
  74100. _this._originalCameras = _this._cameras.slice();
  74101. _this._buildAllowed = automaticBuild;
  74102. // Initialize
  74103. _this._scene = scene;
  74104. var caps = _this._scene.getEngine().getCaps();
  74105. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  74106. // Misc
  74107. if (_this._hdr) {
  74108. if (caps.textureHalfFloatRender) {
  74109. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74110. }
  74111. else if (caps.textureFloatRender) {
  74112. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74113. }
  74114. }
  74115. else {
  74116. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74117. }
  74118. // Attach
  74119. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74120. var engine = _this._scene.getEngine();
  74121. // Create post processes before hand so they can be modified before enabled.
  74122. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  74123. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74124. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  74125. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  74126. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  74127. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74128. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  74129. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74130. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  74131. _this._resizeObserver = engine.onResizeObservable.add(function () {
  74132. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  74133. _this.bloomKernel = _this.bloomKernel;
  74134. });
  74135. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74136. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  74137. });
  74138. _this._buildPipeline();
  74139. return _this;
  74140. }
  74141. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  74142. get: function () {
  74143. return this._sharpenEnabled;
  74144. },
  74145. /**
  74146. * Enable or disable the sharpen process from the pipeline
  74147. */
  74148. set: function (enabled) {
  74149. if (this._sharpenEnabled === enabled) {
  74150. return;
  74151. }
  74152. this._sharpenEnabled = enabled;
  74153. this._buildPipeline();
  74154. },
  74155. enumerable: true,
  74156. configurable: true
  74157. });
  74158. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  74159. /**
  74160. * Specifies the size of the bloom blur kernel, relative to the final output size
  74161. */
  74162. get: function () {
  74163. return this._bloomKernel;
  74164. },
  74165. set: function (value) {
  74166. this._bloomKernel = value;
  74167. this.bloom.kernel = value / this._hardwareScaleLevel;
  74168. },
  74169. enumerable: true,
  74170. configurable: true
  74171. });
  74172. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  74173. get: function () {
  74174. return this._bloomWeight;
  74175. },
  74176. /**
  74177. * The strength of the bloom.
  74178. */
  74179. set: function (value) {
  74180. if (this._bloomWeight === value) {
  74181. return;
  74182. }
  74183. this.bloom.weight = value;
  74184. this._bloomWeight = value;
  74185. },
  74186. enumerable: true,
  74187. configurable: true
  74188. });
  74189. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  74190. get: function () {
  74191. return this._bloomThreshold;
  74192. },
  74193. /**
  74194. * The strength of the bloom.
  74195. */
  74196. set: function (value) {
  74197. if (this._bloomThreshold === value) {
  74198. return;
  74199. }
  74200. this.bloom.threshold = value;
  74201. this._bloomThreshold = value;
  74202. },
  74203. enumerable: true,
  74204. configurable: true
  74205. });
  74206. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  74207. get: function () {
  74208. return this._bloomScale;
  74209. },
  74210. /**
  74211. * The scale of the bloom, lower value will provide better performance.
  74212. */
  74213. set: function (value) {
  74214. if (this._bloomScale === value) {
  74215. return;
  74216. }
  74217. this._bloomScale = value;
  74218. // recreate bloom and dispose old as this setting is not dynamic
  74219. this._rebuildBloom();
  74220. this._buildPipeline();
  74221. },
  74222. enumerable: true,
  74223. configurable: true
  74224. });
  74225. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  74226. get: function () {
  74227. return this._bloomEnabled;
  74228. },
  74229. /**
  74230. * Enable or disable the bloom from the pipeline
  74231. */
  74232. set: function (enabled) {
  74233. if (this._bloomEnabled === enabled) {
  74234. return;
  74235. }
  74236. this._bloomEnabled = enabled;
  74237. this._buildPipeline();
  74238. },
  74239. enumerable: true,
  74240. configurable: true
  74241. });
  74242. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  74243. // recreate bloom and dispose old as this setting is not dynamic
  74244. var oldBloom = this.bloom;
  74245. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  74246. this.bloom.threshold = oldBloom.threshold;
  74247. for (var i = 0; i < this._cameras.length; i++) {
  74248. oldBloom.disposeEffects(this._cameras[i]);
  74249. }
  74250. };
  74251. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  74252. /**
  74253. * If the depth of field is enabled.
  74254. */
  74255. get: function () {
  74256. return this._depthOfFieldEnabled;
  74257. },
  74258. set: function (enabled) {
  74259. if (this._depthOfFieldEnabled === enabled) {
  74260. return;
  74261. }
  74262. this._depthOfFieldEnabled = enabled;
  74263. this._buildPipeline();
  74264. },
  74265. enumerable: true,
  74266. configurable: true
  74267. });
  74268. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  74269. /**
  74270. * Blur level of the depth of field effect. (Higher blur will effect performance)
  74271. */
  74272. get: function () {
  74273. return this._depthOfFieldBlurLevel;
  74274. },
  74275. set: function (value) {
  74276. if (this._depthOfFieldBlurLevel === value) {
  74277. return;
  74278. }
  74279. this._depthOfFieldBlurLevel = value;
  74280. // recreate dof and dispose old as this setting is not dynamic
  74281. var oldDof = this.depthOfField;
  74282. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  74283. this.depthOfField.focalLength = oldDof.focalLength;
  74284. this.depthOfField.focusDistance = oldDof.focusDistance;
  74285. this.depthOfField.fStop = oldDof.fStop;
  74286. this.depthOfField.lensSize = oldDof.lensSize;
  74287. for (var i = 0; i < this._cameras.length; i++) {
  74288. oldDof.disposeEffects(this._cameras[i]);
  74289. }
  74290. this._buildPipeline();
  74291. },
  74292. enumerable: true,
  74293. configurable: true
  74294. });
  74295. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  74296. get: function () {
  74297. return this._fxaaEnabled;
  74298. },
  74299. /**
  74300. * If the anti aliasing is enabled.
  74301. */
  74302. set: function (enabled) {
  74303. if (this._fxaaEnabled === enabled) {
  74304. return;
  74305. }
  74306. this._fxaaEnabled = enabled;
  74307. this._buildPipeline();
  74308. },
  74309. enumerable: true,
  74310. configurable: true
  74311. });
  74312. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  74313. get: function () {
  74314. return this._samples;
  74315. },
  74316. /**
  74317. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  74318. */
  74319. set: function (sampleCount) {
  74320. if (this._samples === sampleCount) {
  74321. return;
  74322. }
  74323. this._samples = sampleCount;
  74324. this._buildPipeline();
  74325. },
  74326. enumerable: true,
  74327. configurable: true
  74328. });
  74329. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  74330. get: function () {
  74331. return this._imageProcessingEnabled;
  74332. },
  74333. /**
  74334. * If image processing is enabled.
  74335. */
  74336. set: function (enabled) {
  74337. if (this._imageProcessingEnabled === enabled) {
  74338. return;
  74339. }
  74340. this._imageProcessingEnabled = enabled;
  74341. this._buildPipeline();
  74342. },
  74343. enumerable: true,
  74344. configurable: true
  74345. });
  74346. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  74347. get: function () {
  74348. return this._chromaticAberrationEnabled;
  74349. },
  74350. /**
  74351. * Enable or disable the chromaticAberration process from the pipeline
  74352. */
  74353. set: function (enabled) {
  74354. if (this._chromaticAberrationEnabled === enabled) {
  74355. return;
  74356. }
  74357. this._chromaticAberrationEnabled = enabled;
  74358. this._buildPipeline();
  74359. },
  74360. enumerable: true,
  74361. configurable: true
  74362. });
  74363. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  74364. get: function () {
  74365. return this._grainEnabled;
  74366. },
  74367. /**
  74368. * Enable or disable the grain process from the pipeline
  74369. */
  74370. set: function (enabled) {
  74371. if (this._grainEnabled === enabled) {
  74372. return;
  74373. }
  74374. this._grainEnabled = enabled;
  74375. this._buildPipeline();
  74376. },
  74377. enumerable: true,
  74378. configurable: true
  74379. });
  74380. /**
  74381. * Force the compilation of the entire pipeline.
  74382. */
  74383. DefaultRenderingPipeline.prototype.prepare = function () {
  74384. var previousState = this._buildAllowed;
  74385. this._buildAllowed = true;
  74386. this._buildPipeline();
  74387. this._buildAllowed = previousState;
  74388. };
  74389. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  74390. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  74391. if (this._hasCleared) {
  74392. postProcess.autoClear = false;
  74393. }
  74394. else {
  74395. postProcess.autoClear = true;
  74396. this._scene.autoClear = false;
  74397. this._hasCleared = true;
  74398. }
  74399. if (!skipTextureSharing) {
  74400. if (this._prevPrevPostProcess) {
  74401. postProcess.shareOutputWith(this._prevPrevPostProcess);
  74402. }
  74403. else {
  74404. postProcess.useOwnOutput();
  74405. }
  74406. if (this._prevPostProcess) {
  74407. this._prevPrevPostProcess = this._prevPostProcess;
  74408. }
  74409. this._prevPostProcess = postProcess;
  74410. }
  74411. };
  74412. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  74413. var _this = this;
  74414. if (!this._buildAllowed) {
  74415. return;
  74416. }
  74417. this._scene.autoClear = true;
  74418. var engine = this._scene.getEngine();
  74419. this._disposePostProcesses();
  74420. if (this._cameras !== null) {
  74421. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74422. // get back cameras to be used to reattach pipeline
  74423. this._cameras = this._originalCameras.slice();
  74424. }
  74425. this._reset();
  74426. this._prevPostProcess = null;
  74427. this._prevPrevPostProcess = null;
  74428. this._hasCleared = false;
  74429. if (this.depthOfFieldEnabled) {
  74430. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  74431. this.depthOfField.depthTexture = depthTexture;
  74432. if (!this.depthOfField._isReady()) {
  74433. this.depthOfField._updateEffects();
  74434. }
  74435. this.addEffect(this.depthOfField);
  74436. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  74437. }
  74438. if (this.bloomEnabled) {
  74439. if (!this.bloom._isReady()) {
  74440. this.bloom._updateEffects();
  74441. }
  74442. this.addEffect(this.bloom);
  74443. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  74444. }
  74445. if (this._imageProcessingEnabled) {
  74446. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74447. if (this._hdr) {
  74448. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  74449. this._setAutoClearAndTextureSharing(this.imageProcessing);
  74450. }
  74451. else {
  74452. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  74453. }
  74454. }
  74455. if (this.sharpenEnabled) {
  74456. if (!this.sharpen.isReady()) {
  74457. this.sharpen.updateEffect();
  74458. }
  74459. this.addEffect(this._sharpenEffect);
  74460. this._setAutoClearAndTextureSharing(this.sharpen);
  74461. }
  74462. if (this.grainEnabled) {
  74463. if (!this.grain.isReady()) {
  74464. this.grain.updateEffect();
  74465. }
  74466. this.addEffect(this._grainEffect);
  74467. this._setAutoClearAndTextureSharing(this.grain);
  74468. }
  74469. if (this.chromaticAberrationEnabled) {
  74470. if (!this.chromaticAberration.isReady()) {
  74471. this.chromaticAberration.updateEffect();
  74472. }
  74473. this.addEffect(this._chromaticAberrationEffect);
  74474. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  74475. }
  74476. if (this.fxaaEnabled) {
  74477. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74478. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  74479. this._setAutoClearAndTextureSharing(this.fxaa, true);
  74480. }
  74481. if (this._cameras !== null) {
  74482. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74483. }
  74484. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  74485. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  74486. }
  74487. };
  74488. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  74489. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  74490. for (var i = 0; i < this._cameras.length; i++) {
  74491. var camera = this._cameras[i];
  74492. if (this.imageProcessing) {
  74493. this.imageProcessing.dispose(camera);
  74494. }
  74495. if (this.fxaa) {
  74496. this.fxaa.dispose(camera);
  74497. }
  74498. // These are created in the constructor and should not be disposed on every pipeline change
  74499. if (disposeNonRecreated) {
  74500. if (this.sharpen) {
  74501. this.sharpen.dispose(camera);
  74502. }
  74503. if (this.depthOfField) {
  74504. this.depthOfField.disposeEffects(camera);
  74505. }
  74506. if (this.bloom) {
  74507. this.bloom.disposeEffects(camera);
  74508. }
  74509. if (this.chromaticAberration) {
  74510. this.chromaticAberration.dispose(camera);
  74511. }
  74512. if (this.grain) {
  74513. this.grain.dispose(camera);
  74514. }
  74515. }
  74516. }
  74517. this.imageProcessing = null;
  74518. this.fxaa = null;
  74519. if (disposeNonRecreated) {
  74520. this.sharpen = null;
  74521. this._sharpenEffect = null;
  74522. this.depthOfField = null;
  74523. this.bloom = null;
  74524. this.chromaticAberration = null;
  74525. this._chromaticAberrationEffect = null;
  74526. this.grain = null;
  74527. this._grainEffect = null;
  74528. }
  74529. };
  74530. /**
  74531. * Dispose of the pipeline and stop all post processes
  74532. */
  74533. DefaultRenderingPipeline.prototype.dispose = function () {
  74534. this._disposePostProcesses(true);
  74535. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74536. this._scene.autoClear = true;
  74537. if (this._resizeObserver) {
  74538. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  74539. this._resizeObserver = null;
  74540. }
  74541. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  74542. _super.prototype.dispose.call(this);
  74543. };
  74544. /**
  74545. * Serialize the rendering pipeline (Used when exporting)
  74546. * @returns the serialized object
  74547. */
  74548. DefaultRenderingPipeline.prototype.serialize = function () {
  74549. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74550. serializationObject.customType = "DefaultRenderingPipeline";
  74551. return serializationObject;
  74552. };
  74553. /**
  74554. * Parse the serialized pipeline
  74555. * @param source Source pipeline.
  74556. * @param scene The scene to load the pipeline to.
  74557. * @param rootUrl The URL of the serialized pipeline.
  74558. * @returns An instantiated pipeline from the serialized object.
  74559. */
  74560. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74561. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  74562. };
  74563. __decorate([
  74564. BABYLON.serialize()
  74565. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  74566. __decorate([
  74567. BABYLON.serialize()
  74568. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  74569. __decorate([
  74570. BABYLON.serialize()
  74571. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  74572. __decorate([
  74573. BABYLON.serialize()
  74574. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  74575. __decorate([
  74576. BABYLON.serialize()
  74577. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  74578. __decorate([
  74579. BABYLON.serialize()
  74580. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  74581. __decorate([
  74582. BABYLON.serialize()
  74583. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  74584. __decorate([
  74585. BABYLON.serialize()
  74586. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  74587. __decorate([
  74588. BABYLON.serialize()
  74589. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  74590. __decorate([
  74591. BABYLON.serialize()
  74592. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  74593. __decorate([
  74594. BABYLON.serialize()
  74595. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  74596. __decorate([
  74597. BABYLON.serialize()
  74598. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  74599. __decorate([
  74600. BABYLON.serialize()
  74601. ], DefaultRenderingPipeline.prototype, "samples", null);
  74602. __decorate([
  74603. BABYLON.serialize()
  74604. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  74605. __decorate([
  74606. BABYLON.serialize()
  74607. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  74608. __decorate([
  74609. BABYLON.serialize()
  74610. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  74611. return DefaultRenderingPipeline;
  74612. }(BABYLON.PostProcessRenderPipeline));
  74613. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  74614. })(BABYLON || (BABYLON = {}));
  74615. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  74616. "use strict";
  74617. var BABYLON;
  74618. (function (BABYLON) {
  74619. /**
  74620. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  74621. */
  74622. var GeometryBufferRenderer = /** @class */ (function () {
  74623. /**
  74624. * Creates a new G Buffer for the scene
  74625. * @param scene The scene the buffer belongs to
  74626. * @param ratio How big is the buffer related to the main canvas.
  74627. */
  74628. function GeometryBufferRenderer(scene, ratio) {
  74629. if (ratio === void 0) { ratio = 1; }
  74630. this._enablePosition = false;
  74631. this._scene = scene;
  74632. this._ratio = ratio;
  74633. // Render target
  74634. this._createRenderTargets();
  74635. }
  74636. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  74637. /**
  74638. * Set the render list (meshes to be rendered) used in the G buffer.
  74639. */
  74640. set: function (meshes) {
  74641. this._multiRenderTarget.renderList = meshes;
  74642. },
  74643. enumerable: true,
  74644. configurable: true
  74645. });
  74646. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  74647. /**
  74648. * Gets wether or not G buffer are supported by the running hardware.
  74649. * This requires draw buffer supports
  74650. */
  74651. get: function () {
  74652. return this._multiRenderTarget.isSupported;
  74653. },
  74654. enumerable: true,
  74655. configurable: true
  74656. });
  74657. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  74658. /**
  74659. * Gets wether or not position are enabled for the G buffer.
  74660. */
  74661. get: function () {
  74662. return this._enablePosition;
  74663. },
  74664. /**
  74665. * Sets wether or not position are enabled for the G buffer.
  74666. */
  74667. set: function (enable) {
  74668. this._enablePosition = enable;
  74669. this.dispose();
  74670. this._createRenderTargets();
  74671. },
  74672. enumerable: true,
  74673. configurable: true
  74674. });
  74675. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  74676. /**
  74677. * Gets the scene associated with the buffer.
  74678. */
  74679. get: function () {
  74680. return this._scene;
  74681. },
  74682. enumerable: true,
  74683. configurable: true
  74684. });
  74685. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  74686. /**
  74687. * Gets the ratio used by the buffer during its creation.
  74688. * How big is the buffer related to the main canvas.
  74689. */
  74690. get: function () {
  74691. return this._ratio;
  74692. },
  74693. enumerable: true,
  74694. configurable: true
  74695. });
  74696. /**
  74697. * Checks wether everything is ready to render a submesh to the G buffer.
  74698. * @param subMesh the submesh to check readiness for
  74699. * @param useInstances is the mesh drawn using instance or not
  74700. * @returns true if ready otherwise false
  74701. */
  74702. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  74703. var material = subMesh.getMaterial();
  74704. if (material && material.disableDepthWrite) {
  74705. return false;
  74706. }
  74707. var defines = [];
  74708. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74709. var mesh = subMesh.getMesh();
  74710. // Alpha test
  74711. if (material && material.needAlphaTesting()) {
  74712. defines.push("#define ALPHATEST");
  74713. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74714. attribs.push(BABYLON.VertexBuffer.UVKind);
  74715. defines.push("#define UV1");
  74716. }
  74717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74718. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74719. defines.push("#define UV2");
  74720. }
  74721. }
  74722. // Buffers
  74723. if (this._enablePosition) {
  74724. defines.push("#define POSITION");
  74725. }
  74726. // Bones
  74727. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74728. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74729. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74730. if (mesh.numBoneInfluencers > 4) {
  74731. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74732. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74733. }
  74734. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74735. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74736. }
  74737. else {
  74738. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74739. }
  74740. // Instances
  74741. if (useInstances) {
  74742. defines.push("#define INSTANCES");
  74743. attribs.push("world0");
  74744. attribs.push("world1");
  74745. attribs.push("world2");
  74746. attribs.push("world3");
  74747. }
  74748. // Get correct effect
  74749. var join = defines.join("\n");
  74750. if (this._cachedDefines !== join) {
  74751. this._cachedDefines = join;
  74752. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  74753. }
  74754. return this._effect.isReady();
  74755. };
  74756. /**
  74757. * Gets the current underlying G Buffer.
  74758. * @returns the buffer
  74759. */
  74760. GeometryBufferRenderer.prototype.getGBuffer = function () {
  74761. return this._multiRenderTarget;
  74762. };
  74763. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  74764. /**
  74765. * Gets the number of samples used to render the buffer (anti aliasing).
  74766. */
  74767. get: function () {
  74768. return this._multiRenderTarget.samples;
  74769. },
  74770. /**
  74771. * Sets the number of samples used to render the buffer (anti aliasing).
  74772. */
  74773. set: function (value) {
  74774. this._multiRenderTarget.samples = value;
  74775. },
  74776. enumerable: true,
  74777. configurable: true
  74778. });
  74779. /**
  74780. * Disposes the renderer and frees up associated resources.
  74781. */
  74782. GeometryBufferRenderer.prototype.dispose = function () {
  74783. this.getGBuffer().dispose();
  74784. };
  74785. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  74786. var _this = this;
  74787. var engine = this._scene.getEngine();
  74788. var count = this._enablePosition ? 3 : 2;
  74789. 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 });
  74790. if (!this.isSupported) {
  74791. return;
  74792. }
  74793. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74794. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74795. this._multiRenderTarget.refreshRate = 1;
  74796. this._multiRenderTarget.renderParticles = false;
  74797. this._multiRenderTarget.renderList = null;
  74798. // set default depth value to 1.0 (far away)
  74799. this._multiRenderTarget.onClearObservable.add(function (engine) {
  74800. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  74801. });
  74802. // Custom render function
  74803. var renderSubMesh = function (subMesh) {
  74804. var mesh = subMesh.getRenderingMesh();
  74805. var scene = _this._scene;
  74806. var engine = scene.getEngine();
  74807. var material = subMesh.getMaterial();
  74808. if (!material) {
  74809. return;
  74810. }
  74811. // Culling
  74812. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74813. // Managing instances
  74814. var batch = mesh._getInstancesRenderList(subMesh._id);
  74815. if (batch.mustReturn) {
  74816. return;
  74817. }
  74818. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74819. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  74820. engine.enableEffect(_this._effect);
  74821. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74822. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74823. _this._effect.setMatrix("view", scene.getViewMatrix());
  74824. // Alpha test
  74825. if (material && material.needAlphaTesting()) {
  74826. var alphaTexture = material.getAlphaTestTexture();
  74827. if (alphaTexture) {
  74828. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74829. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74830. }
  74831. }
  74832. // Bones
  74833. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74834. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74835. }
  74836. // Draw
  74837. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74838. }
  74839. };
  74840. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74841. var index;
  74842. if (depthOnlySubMeshes.length) {
  74843. engine.setColorWrite(false);
  74844. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74845. renderSubMesh(depthOnlySubMeshes.data[index]);
  74846. }
  74847. engine.setColorWrite(true);
  74848. }
  74849. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74850. renderSubMesh(opaqueSubMeshes.data[index]);
  74851. }
  74852. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74853. renderSubMesh(alphaTestSubMeshes.data[index]);
  74854. }
  74855. };
  74856. };
  74857. return GeometryBufferRenderer;
  74858. }());
  74859. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  74860. })(BABYLON || (BABYLON = {}));
  74861. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  74862. "use strict";
  74863. var BABYLON;
  74864. (function (BABYLON) {
  74865. var RefractionPostProcess = /** @class */ (function (_super) {
  74866. __extends(RefractionPostProcess, _super);
  74867. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  74868. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  74869. _this.color = color;
  74870. _this.depth = depth;
  74871. _this.colorLevel = colorLevel;
  74872. _this._ownRefractionTexture = true;
  74873. _this.onActivateObservable.add(function (cam) {
  74874. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  74875. });
  74876. _this.onApplyObservable.add(function (effect) {
  74877. effect.setColor3("baseColor", _this.color);
  74878. effect.setFloat("depth", _this.depth);
  74879. effect.setFloat("colorLevel", _this.colorLevel);
  74880. effect.setTexture("refractionSampler", _this._refTexture);
  74881. });
  74882. return _this;
  74883. }
  74884. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  74885. /**
  74886. * Gets or sets the refraction texture
  74887. * Please note that you are responsible for disposing the texture if you set it manually
  74888. */
  74889. get: function () {
  74890. return this._refTexture;
  74891. },
  74892. set: function (value) {
  74893. if (this._refTexture && this._ownRefractionTexture) {
  74894. this._refTexture.dispose();
  74895. }
  74896. this._refTexture = value;
  74897. this._ownRefractionTexture = false;
  74898. },
  74899. enumerable: true,
  74900. configurable: true
  74901. });
  74902. // Methods
  74903. RefractionPostProcess.prototype.dispose = function (camera) {
  74904. if (this._refTexture && this._ownRefractionTexture) {
  74905. this._refTexture.dispose();
  74906. this._refTexture = null;
  74907. }
  74908. _super.prototype.dispose.call(this, camera);
  74909. };
  74910. return RefractionPostProcess;
  74911. }(BABYLON.PostProcess));
  74912. BABYLON.RefractionPostProcess = RefractionPostProcess;
  74913. })(BABYLON || (BABYLON = {}));
  74914. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  74915. "use strict";
  74916. var BABYLON;
  74917. (function (BABYLON) {
  74918. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  74919. __extends(BlackAndWhitePostProcess, _super);
  74920. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  74921. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  74922. _this.degree = 1;
  74923. _this.onApplyObservable.add(function (effect) {
  74924. effect.setFloat("degree", _this.degree);
  74925. });
  74926. return _this;
  74927. }
  74928. return BlackAndWhitePostProcess;
  74929. }(BABYLON.PostProcess));
  74930. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  74931. })(BABYLON || (BABYLON = {}));
  74932. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  74933. "use strict";
  74934. var BABYLON;
  74935. (function (BABYLON) {
  74936. /**
  74937. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  74938. * input texture to perform effects such as edge detection or sharpening
  74939. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74940. */
  74941. var ConvolutionPostProcess = /** @class */ (function (_super) {
  74942. __extends(ConvolutionPostProcess, _super);
  74943. /**
  74944. * Creates a new instance ConvolutionPostProcess
  74945. * @param name The name of the effect.
  74946. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  74947. * @param options The required width/height ratio to downsize to before computing the render pass.
  74948. * @param camera The camera to apply the render pass to.
  74949. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74950. * @param engine The engine which the post process will be applied. (default: current engine)
  74951. * @param reusable If the post process can be reused on the same frame. (default: false)
  74952. * @param textureType Type of textures used when performing the post process. (default: 0)
  74953. */
  74954. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  74955. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74956. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  74957. _this.kernel = kernel;
  74958. _this.onApply = function (effect) {
  74959. effect.setFloat2("screenSize", _this.width, _this.height);
  74960. effect.setArray("kernel", _this.kernel);
  74961. };
  74962. return _this;
  74963. }
  74964. // Statics
  74965. /**
  74966. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74967. */
  74968. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  74969. /**
  74970. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74971. */
  74972. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  74973. /**
  74974. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74975. */
  74976. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  74977. /**
  74978. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74979. */
  74980. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  74981. /**
  74982. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74983. */
  74984. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  74985. /**
  74986. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74987. */
  74988. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  74989. return ConvolutionPostProcess;
  74990. }(BABYLON.PostProcess));
  74991. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  74992. })(BABYLON || (BABYLON = {}));
  74993. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  74994. "use strict";
  74995. var BABYLON;
  74996. (function (BABYLON) {
  74997. var FilterPostProcess = /** @class */ (function (_super) {
  74998. __extends(FilterPostProcess, _super);
  74999. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  75000. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  75001. _this.kernelMatrix = kernelMatrix;
  75002. _this.onApply = function (effect) {
  75003. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  75004. };
  75005. return _this;
  75006. }
  75007. return FilterPostProcess;
  75008. }(BABYLON.PostProcess));
  75009. BABYLON.FilterPostProcess = FilterPostProcess;
  75010. })(BABYLON || (BABYLON = {}));
  75011. //# sourceMappingURL=babylon.filterPostProcess.js.map
  75012. "use strict";
  75013. var BABYLON;
  75014. (function (BABYLON) {
  75015. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  75016. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  75017. __extends(VolumetricLightScatteringPostProcess, _super);
  75018. /**
  75019. * @constructor
  75020. * @param {string} name - The post-process name
  75021. * @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)
  75022. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  75023. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  75024. * @param {number} samples - The post-process quality, default 100
  75025. * @param {number} samplingMode - The post-process filtering mode
  75026. * @param {BABYLON.Engine} engine - The babylon engine
  75027. * @param {boolean} reusable - If the post-process is reusable
  75028. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  75029. */
  75030. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  75031. if (samples === void 0) { samples = 100; }
  75032. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75033. 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;
  75034. _this._screenCoordinates = BABYLON.Vector2.Zero();
  75035. /**
  75036. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  75037. */
  75038. _this.customMeshPosition = BABYLON.Vector3.Zero();
  75039. /**
  75040. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  75041. */
  75042. _this.useCustomMeshPosition = false;
  75043. /**
  75044. * If the post-process should inverse the light scattering direction
  75045. */
  75046. _this.invert = true;
  75047. /**
  75048. * Array containing the excluded meshes not rendered in the internal pass
  75049. */
  75050. _this.excludedMeshes = new Array();
  75051. /**
  75052. * Controls the overall intensity of the post-process
  75053. */
  75054. _this.exposure = 0.3;
  75055. /**
  75056. * Dissipates each sample's contribution in range [0, 1]
  75057. */
  75058. _this.decay = 0.96815;
  75059. /**
  75060. * Controls the overall intensity of each sample
  75061. */
  75062. _this.weight = 0.58767;
  75063. /**
  75064. * Controls the density of each sample
  75065. */
  75066. _this.density = 0.926;
  75067. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  75068. engine = scene.getEngine();
  75069. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  75070. // Configure mesh
  75071. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  75072. // Configure
  75073. _this._createPass(scene, ratio.passRatio || ratio);
  75074. _this.onActivate = function (camera) {
  75075. if (!_this.isSupported) {
  75076. _this.dispose(camera);
  75077. }
  75078. _this.onActivate = null;
  75079. };
  75080. _this.onApplyObservable.add(function (effect) {
  75081. _this._updateMeshScreenCoordinates(scene);
  75082. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  75083. effect.setFloat("exposure", _this.exposure);
  75084. effect.setFloat("decay", _this.decay);
  75085. effect.setFloat("weight", _this.weight);
  75086. effect.setFloat("density", _this.density);
  75087. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  75088. });
  75089. return _this;
  75090. }
  75091. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  75092. get: function () {
  75093. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75094. return false;
  75095. },
  75096. set: function (useDiffuseColor) {
  75097. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75098. },
  75099. enumerable: true,
  75100. configurable: true
  75101. });
  75102. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  75103. return "VolumetricLightScatteringPostProcess";
  75104. };
  75105. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  75106. var mesh = subMesh.getMesh();
  75107. // Render this.mesh as default
  75108. if (mesh === this.mesh && mesh.material) {
  75109. return mesh.material.isReady(mesh);
  75110. }
  75111. var defines = [];
  75112. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75113. var material = subMesh.getMaterial();
  75114. // Alpha test
  75115. if (material) {
  75116. if (material.needAlphaTesting()) {
  75117. defines.push("#define ALPHATEST");
  75118. }
  75119. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75120. attribs.push(BABYLON.VertexBuffer.UVKind);
  75121. defines.push("#define UV1");
  75122. }
  75123. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75124. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75125. defines.push("#define UV2");
  75126. }
  75127. }
  75128. // Bones
  75129. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75130. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75131. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75132. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75133. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75134. }
  75135. else {
  75136. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75137. }
  75138. // Instances
  75139. if (useInstances) {
  75140. defines.push("#define INSTANCES");
  75141. attribs.push("world0");
  75142. attribs.push("world1");
  75143. attribs.push("world2");
  75144. attribs.push("world3");
  75145. }
  75146. // Get correct effect
  75147. var join = defines.join("\n");
  75148. if (this._cachedDefines !== join) {
  75149. this._cachedDefines = join;
  75150. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  75151. }
  75152. return this._volumetricLightScatteringPass.isReady();
  75153. };
  75154. /**
  75155. * Sets the new light position for light scattering effect
  75156. * @param {BABYLON.Vector3} The new custom light position
  75157. */
  75158. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  75159. this.customMeshPosition = position;
  75160. };
  75161. /**
  75162. * Returns the light position for light scattering effect
  75163. * @return {BABYLON.Vector3} The custom light position
  75164. */
  75165. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  75166. return this.customMeshPosition;
  75167. };
  75168. /**
  75169. * Disposes the internal assets and detaches the post-process from the camera
  75170. */
  75171. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  75172. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  75173. if (rttIndex !== -1) {
  75174. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  75175. }
  75176. this._volumetricLightScatteringRTT.dispose();
  75177. _super.prototype.dispose.call(this, camera);
  75178. };
  75179. /**
  75180. * Returns the render target texture used by the post-process
  75181. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  75182. */
  75183. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  75184. return this._volumetricLightScatteringRTT;
  75185. };
  75186. // Private methods
  75187. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  75188. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  75189. return true;
  75190. }
  75191. return false;
  75192. };
  75193. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  75194. var _this = this;
  75195. var engine = scene.getEngine();
  75196. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75197. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75198. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75199. this._volumetricLightScatteringRTT.renderList = null;
  75200. this._volumetricLightScatteringRTT.renderParticles = false;
  75201. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  75202. var camera = this.getCamera();
  75203. if (camera) {
  75204. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75205. }
  75206. else {
  75207. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75208. }
  75209. // Custom render function for submeshes
  75210. var renderSubMesh = function (subMesh) {
  75211. var mesh = subMesh.getRenderingMesh();
  75212. if (_this._meshExcluded(mesh)) {
  75213. return;
  75214. }
  75215. var material = subMesh.getMaterial();
  75216. if (!material) {
  75217. return;
  75218. }
  75219. var scene = mesh.getScene();
  75220. var engine = scene.getEngine();
  75221. // Culling
  75222. engine.setState(material.backFaceCulling);
  75223. // Managing instances
  75224. var batch = mesh._getInstancesRenderList(subMesh._id);
  75225. if (batch.mustReturn) {
  75226. return;
  75227. }
  75228. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75229. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  75230. var effect = _this._volumetricLightScatteringPass;
  75231. if (mesh === _this.mesh) {
  75232. if (subMesh.effect) {
  75233. effect = subMesh.effect;
  75234. }
  75235. else {
  75236. effect = material.getEffect();
  75237. }
  75238. }
  75239. engine.enableEffect(effect);
  75240. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  75241. if (mesh === _this.mesh) {
  75242. material.bind(mesh.getWorldMatrix(), mesh);
  75243. }
  75244. else {
  75245. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  75246. // Alpha test
  75247. if (material && material.needAlphaTesting()) {
  75248. var alphaTexture = material.getAlphaTestTexture();
  75249. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  75250. if (alphaTexture) {
  75251. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75252. }
  75253. }
  75254. // Bones
  75255. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75256. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75257. }
  75258. }
  75259. // Draw
  75260. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  75261. }
  75262. };
  75263. // Render target texture callbacks
  75264. var savedSceneClearColor;
  75265. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  75266. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  75267. savedSceneClearColor = scene.clearColor;
  75268. scene.clearColor = sceneClearColor;
  75269. });
  75270. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  75271. scene.clearColor = savedSceneClearColor;
  75272. });
  75273. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75274. var engine = scene.getEngine();
  75275. var index;
  75276. if (depthOnlySubMeshes.length) {
  75277. engine.setColorWrite(false);
  75278. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75279. renderSubMesh(depthOnlySubMeshes.data[index]);
  75280. }
  75281. engine.setColorWrite(true);
  75282. }
  75283. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75284. renderSubMesh(opaqueSubMeshes.data[index]);
  75285. }
  75286. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75287. renderSubMesh(alphaTestSubMeshes.data[index]);
  75288. }
  75289. if (transparentSubMeshes.length) {
  75290. // Sort sub meshes
  75291. for (index = 0; index < transparentSubMeshes.length; index++) {
  75292. var submesh = transparentSubMeshes.data[index];
  75293. var boundingInfo = submesh.getBoundingInfo();
  75294. if (boundingInfo && scene.activeCamera) {
  75295. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  75296. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  75297. }
  75298. }
  75299. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  75300. sortedArray.sort(function (a, b) {
  75301. // Alpha index first
  75302. if (a._alphaIndex > b._alphaIndex) {
  75303. return 1;
  75304. }
  75305. if (a._alphaIndex < b._alphaIndex) {
  75306. return -1;
  75307. }
  75308. // Then distance to camera
  75309. if (a._distanceToCamera < b._distanceToCamera) {
  75310. return 1;
  75311. }
  75312. if (a._distanceToCamera > b._distanceToCamera) {
  75313. return -1;
  75314. }
  75315. return 0;
  75316. });
  75317. // Render sub meshes
  75318. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  75319. for (index = 0; index < sortedArray.length; index++) {
  75320. renderSubMesh(sortedArray[index]);
  75321. }
  75322. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75323. }
  75324. };
  75325. };
  75326. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  75327. var transform = scene.getTransformMatrix();
  75328. var meshPosition;
  75329. if (this.useCustomMeshPosition) {
  75330. meshPosition = this.customMeshPosition;
  75331. }
  75332. else if (this.attachedNode) {
  75333. meshPosition = this.attachedNode.position;
  75334. }
  75335. else {
  75336. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  75337. }
  75338. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  75339. this._screenCoordinates.x = pos.x / this._viewPort.width;
  75340. this._screenCoordinates.y = pos.y / this._viewPort.height;
  75341. if (this.invert)
  75342. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  75343. };
  75344. // Static methods
  75345. /**
  75346. * Creates a default mesh for the Volumeric Light Scattering post-process
  75347. * @param {string} The mesh name
  75348. * @param {BABYLON.Scene} The scene where to create the mesh
  75349. * @return {BABYLON.Mesh} the default mesh
  75350. */
  75351. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  75352. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  75353. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  75354. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  75355. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  75356. mesh.material = material;
  75357. return mesh;
  75358. };
  75359. __decorate([
  75360. BABYLON.serializeAsVector3()
  75361. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  75362. __decorate([
  75363. BABYLON.serialize()
  75364. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  75365. __decorate([
  75366. BABYLON.serialize()
  75367. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  75368. __decorate([
  75369. BABYLON.serializeAsMeshReference()
  75370. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  75371. __decorate([
  75372. BABYLON.serialize()
  75373. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  75374. __decorate([
  75375. BABYLON.serialize()
  75376. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  75377. __decorate([
  75378. BABYLON.serialize()
  75379. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  75380. __decorate([
  75381. BABYLON.serialize()
  75382. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  75383. __decorate([
  75384. BABYLON.serialize()
  75385. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  75386. return VolumetricLightScatteringPostProcess;
  75387. }(BABYLON.PostProcess));
  75388. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  75389. })(BABYLON || (BABYLON = {}));
  75390. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  75391. "use strict";
  75392. //
  75393. // This post-process allows the modification of rendered colors by using
  75394. // a 'look-up table' (LUT). This effect is also called Color Grading.
  75395. //
  75396. // The object needs to be provided an url to a texture containing the color
  75397. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  75398. // Use an image editing software to tweak the LUT to match your needs.
  75399. //
  75400. // For an example of a color LUT, see here:
  75401. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  75402. // For explanations on color grading, see here:
  75403. // http://udn.epicgames.com/Three/ColorGrading.html
  75404. //
  75405. var BABYLON;
  75406. (function (BABYLON) {
  75407. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  75408. __extends(ColorCorrectionPostProcess, _super);
  75409. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  75410. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  75411. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75412. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  75413. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75414. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75415. _this.onApply = function (effect) {
  75416. effect.setTexture("colorTable", _this._colorTableTexture);
  75417. };
  75418. return _this;
  75419. }
  75420. return ColorCorrectionPostProcess;
  75421. }(BABYLON.PostProcess));
  75422. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  75423. })(BABYLON || (BABYLON = {}));
  75424. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  75425. "use strict";
  75426. var BABYLON;
  75427. (function (BABYLON) {
  75428. var TonemappingOperator;
  75429. (function (TonemappingOperator) {
  75430. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  75431. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  75432. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  75433. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  75434. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  75435. ;
  75436. var TonemapPostProcess = /** @class */ (function (_super) {
  75437. __extends(TonemapPostProcess, _super);
  75438. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  75439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75440. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75441. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  75442. _this._operator = _operator;
  75443. _this.exposureAdjustment = exposureAdjustment;
  75444. var defines = "#define ";
  75445. if (_this._operator === TonemappingOperator.Hable)
  75446. defines += "HABLE_TONEMAPPING";
  75447. else if (_this._operator === TonemappingOperator.Reinhard)
  75448. defines += "REINHARD_TONEMAPPING";
  75449. else if (_this._operator === TonemappingOperator.HejiDawson)
  75450. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  75451. else if (_this._operator === TonemappingOperator.Photographic)
  75452. defines += "PHOTOGRAPHIC_TONEMAPPING";
  75453. //sadly a second call to create the effect.
  75454. _this.updateEffect(defines);
  75455. _this.onApply = function (effect) {
  75456. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  75457. };
  75458. return _this;
  75459. }
  75460. return TonemapPostProcess;
  75461. }(BABYLON.PostProcess));
  75462. BABYLON.TonemapPostProcess = TonemapPostProcess;
  75463. })(BABYLON || (BABYLON = {}));
  75464. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  75465. "use strict";
  75466. var BABYLON;
  75467. (function (BABYLON) {
  75468. var DisplayPassPostProcess = /** @class */ (function (_super) {
  75469. __extends(DisplayPassPostProcess, _super);
  75470. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  75471. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  75472. }
  75473. return DisplayPassPostProcess;
  75474. }(BABYLON.PostProcess));
  75475. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  75476. })(BABYLON || (BABYLON = {}));
  75477. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  75478. "use strict";
  75479. var BABYLON;
  75480. (function (BABYLON) {
  75481. var HighlightsPostProcess = /** @class */ (function (_super) {
  75482. __extends(HighlightsPostProcess, _super);
  75483. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75484. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75485. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75486. }
  75487. return HighlightsPostProcess;
  75488. }(BABYLON.PostProcess));
  75489. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  75490. })(BABYLON || (BABYLON = {}));
  75491. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  75492. "use strict";
  75493. var BABYLON;
  75494. (function (BABYLON) {
  75495. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  75496. __extends(ImageProcessingPostProcess, _super);
  75497. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  75498. if (camera === void 0) { camera = null; }
  75499. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75500. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  75501. _this._fromLinearSpace = true;
  75502. /**
  75503. * Defines cache preventing GC.
  75504. */
  75505. _this._defines = {
  75506. IMAGEPROCESSING: false,
  75507. VIGNETTE: false,
  75508. VIGNETTEBLENDMODEMULTIPLY: false,
  75509. VIGNETTEBLENDMODEOPAQUE: false,
  75510. TONEMAPPING: false,
  75511. CONTRAST: false,
  75512. COLORCURVES: false,
  75513. COLORGRADING: false,
  75514. COLORGRADING3D: false,
  75515. FROMLINEARSPACE: false,
  75516. SAMPLER3DGREENDEPTH: false,
  75517. SAMPLER3DBGRMAP: false,
  75518. IMAGEPROCESSINGPOSTPROCESS: false,
  75519. EXPOSURE: false,
  75520. };
  75521. // Setup the configuration as forced by the constructor. This would then not force the
  75522. // scene materials output in linear space and let untouched the default forward pass.
  75523. if (imageProcessingConfiguration) {
  75524. imageProcessingConfiguration.applyByPostProcess = true;
  75525. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  75526. // This will cause the shader to be compiled
  75527. _this.fromLinearSpace = false;
  75528. }
  75529. else {
  75530. _this._attachImageProcessingConfiguration(null, true);
  75531. _this.imageProcessingConfiguration.applyByPostProcess = true;
  75532. }
  75533. _this.onApply = function (effect) {
  75534. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  75535. };
  75536. return _this;
  75537. }
  75538. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  75539. /**
  75540. * Gets the image processing configuration used either in this material.
  75541. */
  75542. get: function () {
  75543. return this._imageProcessingConfiguration;
  75544. },
  75545. /**
  75546. * Sets the Default image processing configuration used either in the this material.
  75547. *
  75548. * If sets to null, the scene one is in use.
  75549. */
  75550. set: function (value) {
  75551. this._attachImageProcessingConfiguration(value);
  75552. },
  75553. enumerable: true,
  75554. configurable: true
  75555. });
  75556. /**
  75557. * Attaches a new image processing configuration to the PBR Material.
  75558. * @param configuration
  75559. */
  75560. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  75561. var _this = this;
  75562. if (doNotBuild === void 0) { doNotBuild = false; }
  75563. if (configuration === this._imageProcessingConfiguration) {
  75564. return;
  75565. }
  75566. // Detaches observer.
  75567. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75568. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75569. }
  75570. // Pick the scene configuration if needed.
  75571. if (!configuration) {
  75572. var scene = null;
  75573. var engine = this.getEngine();
  75574. var camera = this.getCamera();
  75575. if (camera) {
  75576. scene = camera.getScene();
  75577. }
  75578. else if (engine && engine.scenes) {
  75579. var scenes = engine.scenes;
  75580. scene = scenes[scenes.length - 1];
  75581. }
  75582. else {
  75583. scene = BABYLON.Engine.LastCreatedScene;
  75584. }
  75585. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  75586. }
  75587. else {
  75588. this._imageProcessingConfiguration = configuration;
  75589. }
  75590. // Attaches observer.
  75591. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75592. _this._updateParameters();
  75593. });
  75594. // Ensure the effect will be rebuilt.
  75595. if (!doNotBuild) {
  75596. this._updateParameters();
  75597. }
  75598. };
  75599. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  75600. /**
  75601. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75602. */
  75603. get: function () {
  75604. return this.imageProcessingConfiguration.colorCurves;
  75605. },
  75606. /**
  75607. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75608. */
  75609. set: function (value) {
  75610. this.imageProcessingConfiguration.colorCurves = value;
  75611. },
  75612. enumerable: true,
  75613. configurable: true
  75614. });
  75615. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  75616. /**
  75617. * Gets wether the color curves effect is enabled.
  75618. */
  75619. get: function () {
  75620. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75621. },
  75622. /**
  75623. * Sets wether the color curves effect is enabled.
  75624. */
  75625. set: function (value) {
  75626. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75627. },
  75628. enumerable: true,
  75629. configurable: true
  75630. });
  75631. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  75632. /**
  75633. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75634. */
  75635. get: function () {
  75636. return this.imageProcessingConfiguration.colorGradingTexture;
  75637. },
  75638. /**
  75639. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75640. */
  75641. set: function (value) {
  75642. this.imageProcessingConfiguration.colorGradingTexture = value;
  75643. },
  75644. enumerable: true,
  75645. configurable: true
  75646. });
  75647. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  75648. /**
  75649. * Gets wether the color grading effect is enabled.
  75650. */
  75651. get: function () {
  75652. return this.imageProcessingConfiguration.colorGradingEnabled;
  75653. },
  75654. /**
  75655. * Gets wether the color grading effect is enabled.
  75656. */
  75657. set: function (value) {
  75658. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75659. },
  75660. enumerable: true,
  75661. configurable: true
  75662. });
  75663. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  75664. /**
  75665. * Gets exposure used in the effect.
  75666. */
  75667. get: function () {
  75668. return this.imageProcessingConfiguration.exposure;
  75669. },
  75670. /**
  75671. * Sets exposure used in the effect.
  75672. */
  75673. set: function (value) {
  75674. this.imageProcessingConfiguration.exposure = value;
  75675. },
  75676. enumerable: true,
  75677. configurable: true
  75678. });
  75679. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  75680. /**
  75681. * Gets wether tonemapping is enabled or not.
  75682. */
  75683. get: function () {
  75684. return this._imageProcessingConfiguration.toneMappingEnabled;
  75685. },
  75686. /**
  75687. * Sets wether tonemapping is enabled or not
  75688. */
  75689. set: function (value) {
  75690. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75691. },
  75692. enumerable: true,
  75693. configurable: true
  75694. });
  75695. ;
  75696. ;
  75697. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  75698. /**
  75699. * Gets contrast used in the effect.
  75700. */
  75701. get: function () {
  75702. return this.imageProcessingConfiguration.contrast;
  75703. },
  75704. /**
  75705. * Sets contrast used in the effect.
  75706. */
  75707. set: function (value) {
  75708. this.imageProcessingConfiguration.contrast = value;
  75709. },
  75710. enumerable: true,
  75711. configurable: true
  75712. });
  75713. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  75714. /**
  75715. * Gets Vignette stretch size.
  75716. */
  75717. get: function () {
  75718. return this.imageProcessingConfiguration.vignetteStretch;
  75719. },
  75720. /**
  75721. * Sets Vignette stretch size.
  75722. */
  75723. set: function (value) {
  75724. this.imageProcessingConfiguration.vignetteStretch = value;
  75725. },
  75726. enumerable: true,
  75727. configurable: true
  75728. });
  75729. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  75730. /**
  75731. * Gets Vignette centre X Offset.
  75732. */
  75733. get: function () {
  75734. return this.imageProcessingConfiguration.vignetteCentreX;
  75735. },
  75736. /**
  75737. * Sets Vignette centre X Offset.
  75738. */
  75739. set: function (value) {
  75740. this.imageProcessingConfiguration.vignetteCentreX = value;
  75741. },
  75742. enumerable: true,
  75743. configurable: true
  75744. });
  75745. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  75746. /**
  75747. * Gets Vignette centre Y Offset.
  75748. */
  75749. get: function () {
  75750. return this.imageProcessingConfiguration.vignetteCentreY;
  75751. },
  75752. /**
  75753. * Sets Vignette centre Y Offset.
  75754. */
  75755. set: function (value) {
  75756. this.imageProcessingConfiguration.vignetteCentreY = value;
  75757. },
  75758. enumerable: true,
  75759. configurable: true
  75760. });
  75761. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  75762. /**
  75763. * Gets Vignette weight or intensity of the vignette effect.
  75764. */
  75765. get: function () {
  75766. return this.imageProcessingConfiguration.vignetteWeight;
  75767. },
  75768. /**
  75769. * Sets Vignette weight or intensity of the vignette effect.
  75770. */
  75771. set: function (value) {
  75772. this.imageProcessingConfiguration.vignetteWeight = value;
  75773. },
  75774. enumerable: true,
  75775. configurable: true
  75776. });
  75777. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  75778. /**
  75779. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75780. * if vignetteEnabled is set to true.
  75781. */
  75782. get: function () {
  75783. return this.imageProcessingConfiguration.vignetteColor;
  75784. },
  75785. /**
  75786. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75787. * if vignetteEnabled is set to true.
  75788. */
  75789. set: function (value) {
  75790. this.imageProcessingConfiguration.vignetteColor = value;
  75791. },
  75792. enumerable: true,
  75793. configurable: true
  75794. });
  75795. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  75796. /**
  75797. * Gets Camera field of view used by the Vignette effect.
  75798. */
  75799. get: function () {
  75800. return this.imageProcessingConfiguration.vignetteCameraFov;
  75801. },
  75802. /**
  75803. * Sets Camera field of view used by the Vignette effect.
  75804. */
  75805. set: function (value) {
  75806. this.imageProcessingConfiguration.vignetteCameraFov = value;
  75807. },
  75808. enumerable: true,
  75809. configurable: true
  75810. });
  75811. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  75812. /**
  75813. * Gets the vignette blend mode allowing different kind of effect.
  75814. */
  75815. get: function () {
  75816. return this.imageProcessingConfiguration.vignetteBlendMode;
  75817. },
  75818. /**
  75819. * Sets the vignette blend mode allowing different kind of effect.
  75820. */
  75821. set: function (value) {
  75822. this.imageProcessingConfiguration.vignetteBlendMode = value;
  75823. },
  75824. enumerable: true,
  75825. configurable: true
  75826. });
  75827. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  75828. /**
  75829. * Gets wether the vignette effect is enabled.
  75830. */
  75831. get: function () {
  75832. return this.imageProcessingConfiguration.vignetteEnabled;
  75833. },
  75834. /**
  75835. * Sets wether the vignette effect is enabled.
  75836. */
  75837. set: function (value) {
  75838. this.imageProcessingConfiguration.vignetteEnabled = value;
  75839. },
  75840. enumerable: true,
  75841. configurable: true
  75842. });
  75843. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  75844. /**
  75845. * Gets wether the input of the processing is in Gamma or Linear Space.
  75846. */
  75847. get: function () {
  75848. return this._fromLinearSpace;
  75849. },
  75850. /**
  75851. * Sets wether the input of the processing is in Gamma or Linear Space.
  75852. */
  75853. set: function (value) {
  75854. if (this._fromLinearSpace === value) {
  75855. return;
  75856. }
  75857. this._fromLinearSpace = value;
  75858. this._updateParameters();
  75859. },
  75860. enumerable: true,
  75861. configurable: true
  75862. });
  75863. ImageProcessingPostProcess.prototype.getClassName = function () {
  75864. return "ImageProcessingPostProcess";
  75865. };
  75866. ImageProcessingPostProcess.prototype._updateParameters = function () {
  75867. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  75868. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  75869. var defines = "";
  75870. for (var define in this._defines) {
  75871. if (this._defines[define]) {
  75872. defines += "#define " + define + ";\r\n";
  75873. }
  75874. }
  75875. var samplers = ["textureSampler"];
  75876. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  75877. var uniforms = ["scale"];
  75878. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  75879. this.updateEffect(defines, uniforms, samplers);
  75880. };
  75881. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  75882. _super.prototype.dispose.call(this, camera);
  75883. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75884. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75885. }
  75886. this.imageProcessingConfiguration.applyByPostProcess = false;
  75887. };
  75888. __decorate([
  75889. BABYLON.serialize()
  75890. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  75891. return ImageProcessingPostProcess;
  75892. }(BABYLON.PostProcess));
  75893. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  75894. })(BABYLON || (BABYLON = {}));
  75895. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  75896. "use strict";
  75897. var BABYLON;
  75898. (function (BABYLON) {
  75899. var Bone = /** @class */ (function (_super) {
  75900. __extends(Bone, _super);
  75901. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  75902. if (parentBone === void 0) { parentBone = null; }
  75903. if (localMatrix === void 0) { localMatrix = null; }
  75904. if (restPose === void 0) { restPose = null; }
  75905. if (baseMatrix === void 0) { baseMatrix = null; }
  75906. if (index === void 0) { index = null; }
  75907. var _this = _super.call(this, name, skeleton.getScene()) || this;
  75908. _this.name = name;
  75909. _this.children = new Array();
  75910. _this.animations = new Array();
  75911. // Set this value to map this bone to a different index in the transform matrices.
  75912. // Set this value to -1 to exclude the bone from the transform matrices.
  75913. _this._index = null;
  75914. _this._worldTransform = new BABYLON.Matrix();
  75915. _this._absoluteTransform = new BABYLON.Matrix();
  75916. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  75917. _this._scaleMatrix = BABYLON.Matrix.Identity();
  75918. _this._scaleVector = BABYLON.Vector3.One();
  75919. _this._negateScaleChildren = BABYLON.Vector3.One();
  75920. _this._scalingDeterminant = 1;
  75921. _this._skeleton = skeleton;
  75922. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  75923. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  75924. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  75925. _this._index = index;
  75926. skeleton.bones.push(_this);
  75927. _this.setParent(parentBone, false);
  75928. _this._updateDifferenceMatrix();
  75929. return _this;
  75930. }
  75931. Object.defineProperty(Bone.prototype, "_matrix", {
  75932. get: function () {
  75933. return this._localMatrix;
  75934. },
  75935. set: function (val) {
  75936. if (this._localMatrix) {
  75937. this._localMatrix.copyFrom(val);
  75938. }
  75939. else {
  75940. this._localMatrix = val;
  75941. }
  75942. },
  75943. enumerable: true,
  75944. configurable: true
  75945. });
  75946. // Members
  75947. Bone.prototype.getSkeleton = function () {
  75948. return this._skeleton;
  75949. };
  75950. Bone.prototype.getParent = function () {
  75951. return this._parent;
  75952. };
  75953. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  75954. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75955. if (this._parent === parent) {
  75956. return;
  75957. }
  75958. if (this._parent) {
  75959. var index = this._parent.children.indexOf(this);
  75960. if (index !== -1) {
  75961. this._parent.children.splice(index, 1);
  75962. }
  75963. }
  75964. this._parent = parent;
  75965. if (this._parent) {
  75966. this._parent.children.push(this);
  75967. }
  75968. if (updateDifferenceMatrix) {
  75969. this._updateDifferenceMatrix();
  75970. }
  75971. };
  75972. Bone.prototype.getLocalMatrix = function () {
  75973. return this._localMatrix;
  75974. };
  75975. Bone.prototype.getBaseMatrix = function () {
  75976. return this._baseMatrix;
  75977. };
  75978. Bone.prototype.getRestPose = function () {
  75979. return this._restPose;
  75980. };
  75981. Bone.prototype.returnToRest = function () {
  75982. this.updateMatrix(this._restPose.clone());
  75983. };
  75984. Bone.prototype.getWorldMatrix = function () {
  75985. return this._worldTransform;
  75986. };
  75987. Bone.prototype.getInvertedAbsoluteTransform = function () {
  75988. return this._invertedAbsoluteTransform;
  75989. };
  75990. Bone.prototype.getAbsoluteTransform = function () {
  75991. return this._absoluteTransform;
  75992. };
  75993. Object.defineProperty(Bone.prototype, "position", {
  75994. // Properties (matches AbstractMesh properties)
  75995. get: function () {
  75996. return this.getPosition();
  75997. },
  75998. set: function (newPosition) {
  75999. this.setPosition(newPosition);
  76000. },
  76001. enumerable: true,
  76002. configurable: true
  76003. });
  76004. Object.defineProperty(Bone.prototype, "rotation", {
  76005. get: function () {
  76006. return this.getRotation();
  76007. },
  76008. set: function (newRotation) {
  76009. this.setRotation(newRotation);
  76010. },
  76011. enumerable: true,
  76012. configurable: true
  76013. });
  76014. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  76015. get: function () {
  76016. return this.getRotationQuaternion();
  76017. },
  76018. set: function (newRotation) {
  76019. this.setRotationQuaternion(newRotation);
  76020. },
  76021. enumerable: true,
  76022. configurable: true
  76023. });
  76024. Object.defineProperty(Bone.prototype, "scaling", {
  76025. get: function () {
  76026. return this.getScale();
  76027. },
  76028. set: function (newScaling) {
  76029. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  76030. },
  76031. enumerable: true,
  76032. configurable: true
  76033. });
  76034. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  76035. /**
  76036. * Gets the animation properties override
  76037. */
  76038. get: function () {
  76039. return this._skeleton.animationPropertiesOverride;
  76040. },
  76041. enumerable: true,
  76042. configurable: true
  76043. });
  76044. // Methods
  76045. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  76046. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76047. this._baseMatrix = matrix.clone();
  76048. this._localMatrix = matrix.clone();
  76049. this._skeleton._markAsDirty();
  76050. if (updateDifferenceMatrix) {
  76051. this._updateDifferenceMatrix();
  76052. }
  76053. };
  76054. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  76055. if (!rootMatrix) {
  76056. rootMatrix = this._baseMatrix;
  76057. }
  76058. if (this._parent) {
  76059. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76060. }
  76061. else {
  76062. this._absoluteTransform.copyFrom(rootMatrix);
  76063. }
  76064. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  76065. for (var index = 0; index < this.children.length; index++) {
  76066. this.children[index]._updateDifferenceMatrix();
  76067. }
  76068. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  76069. };
  76070. Bone.prototype.markAsDirty = function () {
  76071. this._currentRenderId++;
  76072. this._childRenderId++;
  76073. this._skeleton._markAsDirty();
  76074. };
  76075. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  76076. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76077. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  76078. // all animation may be coming from a library skeleton, so may need to create animation
  76079. if (this.animations.length === 0) {
  76080. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  76081. this.animations[0].setKeys([]);
  76082. }
  76083. // get animation info / verify there is such a range from the source bone
  76084. var sourceRange = source.animations[0].getRange(rangeName);
  76085. if (!sourceRange) {
  76086. return false;
  76087. }
  76088. var from = sourceRange.from;
  76089. var to = sourceRange.to;
  76090. var sourceKeys = source.animations[0].getKeys();
  76091. // rescaling prep
  76092. var sourceBoneLength = source.length;
  76093. var sourceParent = source.getParent();
  76094. var parent = this.getParent();
  76095. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  76096. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  76097. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  76098. var destKeys = this.animations[0].getKeys();
  76099. // loop vars declaration
  76100. var orig;
  76101. var origTranslation;
  76102. var mat;
  76103. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  76104. orig = sourceKeys[key];
  76105. if (orig.frame >= from && orig.frame <= to) {
  76106. if (rescaleAsRequired) {
  76107. mat = orig.value.clone();
  76108. // scale based on parent ratio, when bone has parent
  76109. if (parentScalingReqd) {
  76110. origTranslation = mat.getTranslation();
  76111. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  76112. // scale based on skeleton dimension ratio when root bone, and value is passed
  76113. }
  76114. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  76115. origTranslation = mat.getTranslation();
  76116. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  76117. // use original when root bone, and no data for skelDimensionsRatio
  76118. }
  76119. else {
  76120. mat = orig.value;
  76121. }
  76122. }
  76123. else {
  76124. mat = orig.value;
  76125. }
  76126. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  76127. }
  76128. }
  76129. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  76130. return true;
  76131. };
  76132. /**
  76133. * Translate the bone in local or world space.
  76134. * @param vec The amount to translate the bone.
  76135. * @param space The space that the translation is in.
  76136. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76137. */
  76138. Bone.prototype.translate = function (vec, space, mesh) {
  76139. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76140. var lm = this.getLocalMatrix();
  76141. if (space == BABYLON.Space.LOCAL) {
  76142. lm.m[12] += vec.x;
  76143. lm.m[13] += vec.y;
  76144. lm.m[14] += vec.z;
  76145. }
  76146. else {
  76147. var wm = null;
  76148. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76149. if (mesh) {
  76150. wm = mesh.getWorldMatrix();
  76151. }
  76152. this._skeleton.computeAbsoluteTransforms();
  76153. var tmat = Bone._tmpMats[0];
  76154. var tvec = Bone._tmpVecs[0];
  76155. if (this._parent) {
  76156. if (mesh && wm) {
  76157. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76158. tmat.multiplyToRef(wm, tmat);
  76159. }
  76160. else {
  76161. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76162. }
  76163. }
  76164. tmat.m[12] = 0;
  76165. tmat.m[13] = 0;
  76166. tmat.m[14] = 0;
  76167. tmat.invert();
  76168. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  76169. lm.m[12] += tvec.x;
  76170. lm.m[13] += tvec.y;
  76171. lm.m[14] += tvec.z;
  76172. }
  76173. this.markAsDirty();
  76174. };
  76175. /**
  76176. * Set the postion of the bone in local or world space.
  76177. * @param position The position to set the bone.
  76178. * @param space The space that the position is in.
  76179. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76180. */
  76181. Bone.prototype.setPosition = function (position, space, mesh) {
  76182. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76183. var lm = this.getLocalMatrix();
  76184. if (space == BABYLON.Space.LOCAL) {
  76185. lm.m[12] = position.x;
  76186. lm.m[13] = position.y;
  76187. lm.m[14] = position.z;
  76188. }
  76189. else {
  76190. var wm = null;
  76191. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76192. if (mesh) {
  76193. wm = mesh.getWorldMatrix();
  76194. }
  76195. this._skeleton.computeAbsoluteTransforms();
  76196. var tmat = Bone._tmpMats[0];
  76197. var vec = Bone._tmpVecs[0];
  76198. if (this._parent) {
  76199. if (mesh && wm) {
  76200. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76201. tmat.multiplyToRef(wm, tmat);
  76202. }
  76203. else {
  76204. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76205. }
  76206. }
  76207. tmat.invert();
  76208. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  76209. lm.m[12] = vec.x;
  76210. lm.m[13] = vec.y;
  76211. lm.m[14] = vec.z;
  76212. }
  76213. this.markAsDirty();
  76214. };
  76215. /**
  76216. * Set the absolute postion of the bone (world space).
  76217. * @param position The position to set the bone.
  76218. * @param mesh The mesh that this bone is attached to.
  76219. */
  76220. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  76221. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  76222. };
  76223. /**
  76224. * Set the scale of the bone on the x, y and z axes.
  76225. * @param x The scale of the bone on the x axis.
  76226. * @param x The scale of the bone on the y axis.
  76227. * @param z The scale of the bone on the z axis.
  76228. * @param scaleChildren Set this to true if children of the bone should be scaled.
  76229. */
  76230. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  76231. if (scaleChildren === void 0) { scaleChildren = false; }
  76232. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  76233. if (!scaleChildren) {
  76234. this._negateScaleChildren.x = 1 / x;
  76235. this._negateScaleChildren.y = 1 / y;
  76236. this._negateScaleChildren.z = 1 / z;
  76237. }
  76238. this._syncScaleVector();
  76239. }
  76240. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  76241. };
  76242. /**
  76243. * Scale the bone on the x, y and z axes.
  76244. * @param x The amount to scale the bone on the x axis.
  76245. * @param x The amount to scale the bone on the y axis.
  76246. * @param z The amount to scale the bone on the z axis.
  76247. * @param scaleChildren Set this to true if children of the bone should be scaled.
  76248. */
  76249. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  76250. if (scaleChildren === void 0) { scaleChildren = false; }
  76251. var locMat = this.getLocalMatrix();
  76252. var origLocMat = Bone._tmpMats[0];
  76253. origLocMat.copyFrom(locMat);
  76254. var origLocMatInv = Bone._tmpMats[1];
  76255. origLocMatInv.copyFrom(origLocMat);
  76256. origLocMatInv.invert();
  76257. var scaleMat = Bone._tmpMats[2];
  76258. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  76259. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  76260. this._scaleVector.x *= x;
  76261. this._scaleVector.y *= y;
  76262. this._scaleVector.z *= z;
  76263. locMat.multiplyToRef(origLocMatInv, locMat);
  76264. locMat.multiplyToRef(scaleMat, locMat);
  76265. locMat.multiplyToRef(origLocMat, locMat);
  76266. var parent = this.getParent();
  76267. if (parent) {
  76268. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  76269. }
  76270. else {
  76271. this.getAbsoluteTransform().copyFrom(locMat);
  76272. }
  76273. var len = this.children.length;
  76274. scaleMat.invert();
  76275. for (var i = 0; i < len; i++) {
  76276. var child = this.children[i];
  76277. var cm = child.getLocalMatrix();
  76278. cm.multiplyToRef(scaleMat, cm);
  76279. var lm = child.getLocalMatrix();
  76280. lm.m[12] *= x;
  76281. lm.m[13] *= y;
  76282. lm.m[14] *= z;
  76283. }
  76284. this.computeAbsoluteTransforms();
  76285. if (scaleChildren) {
  76286. for (var i = 0; i < len; i++) {
  76287. this.children[i].scale(x, y, z, scaleChildren);
  76288. }
  76289. }
  76290. this.markAsDirty();
  76291. };
  76292. /**
  76293. * Set the yaw, pitch, and roll of the bone in local or world space.
  76294. * @param yaw The rotation of the bone on the y axis.
  76295. * @param pitch The rotation of the bone on the x axis.
  76296. * @param roll The rotation of the bone on the z axis.
  76297. * @param space The space that the axes of rotation are in.
  76298. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76299. */
  76300. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  76301. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76302. var rotMat = Bone._tmpMats[0];
  76303. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  76304. var rotMatInv = Bone._tmpMats[1];
  76305. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76306. rotMatInv.multiplyToRef(rotMat, rotMat);
  76307. this._rotateWithMatrix(rotMat, space, mesh);
  76308. };
  76309. /**
  76310. * Rotate the bone on an axis in local or world space.
  76311. * @param axis The axis to rotate the bone on.
  76312. * @param amount The amount to rotate the bone.
  76313. * @param space The space that the axis is in.
  76314. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76315. */
  76316. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  76317. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76318. var rmat = Bone._tmpMats[0];
  76319. rmat.m[12] = 0;
  76320. rmat.m[13] = 0;
  76321. rmat.m[14] = 0;
  76322. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  76323. this._rotateWithMatrix(rmat, space, mesh);
  76324. };
  76325. /**
  76326. * Set the rotation of the bone to a particular axis angle in local or world space.
  76327. * @param axis The axis to rotate the bone on.
  76328. * @param angle The angle that the bone should be rotated to.
  76329. * @param space The space that the axis is in.
  76330. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76331. */
  76332. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  76333. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76334. var rotMat = Bone._tmpMats[0];
  76335. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  76336. var rotMatInv = Bone._tmpMats[1];
  76337. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76338. rotMatInv.multiplyToRef(rotMat, rotMat);
  76339. this._rotateWithMatrix(rotMat, space, mesh);
  76340. };
  76341. /**
  76342. * Set the euler rotation of the bone in local of world space.
  76343. * @param rotation The euler rotation that the bone should be set to.
  76344. * @param space The space that the rotation is in.
  76345. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76346. */
  76347. Bone.prototype.setRotation = function (rotation, space, mesh) {
  76348. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76349. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  76350. };
  76351. /**
  76352. * Set the quaternion rotation of the bone in local of world space.
  76353. * @param quat The quaternion rotation that the bone should be set to.
  76354. * @param space The space that the rotation is in.
  76355. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76356. */
  76357. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  76358. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76359. var rotMatInv = Bone._tmpMats[0];
  76360. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76361. var rotMat = Bone._tmpMats[1];
  76362. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  76363. rotMatInv.multiplyToRef(rotMat, rotMat);
  76364. this._rotateWithMatrix(rotMat, space, mesh);
  76365. };
  76366. /**
  76367. * Set the rotation matrix of the bone in local of world space.
  76368. * @param rotMat The rotation matrix that the bone should be set to.
  76369. * @param space The space that the rotation is in.
  76370. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76371. */
  76372. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  76373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76374. var rotMatInv = Bone._tmpMats[0];
  76375. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76376. var rotMat2 = Bone._tmpMats[1];
  76377. rotMat2.copyFrom(rotMat);
  76378. rotMatInv.multiplyToRef(rotMat, rotMat2);
  76379. this._rotateWithMatrix(rotMat2, space, mesh);
  76380. };
  76381. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  76382. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76383. var lmat = this.getLocalMatrix();
  76384. var lx = lmat.m[12];
  76385. var ly = lmat.m[13];
  76386. var lz = lmat.m[14];
  76387. var parent = this.getParent();
  76388. var parentScale = Bone._tmpMats[3];
  76389. var parentScaleInv = Bone._tmpMats[4];
  76390. if (parent) {
  76391. if (space == BABYLON.Space.WORLD) {
  76392. if (mesh) {
  76393. parentScale.copyFrom(mesh.getWorldMatrix());
  76394. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  76395. }
  76396. else {
  76397. parentScale.copyFrom(parent.getAbsoluteTransform());
  76398. }
  76399. }
  76400. else {
  76401. parentScale = parent._scaleMatrix;
  76402. }
  76403. parentScaleInv.copyFrom(parentScale);
  76404. parentScaleInv.invert();
  76405. lmat.multiplyToRef(parentScale, lmat);
  76406. lmat.multiplyToRef(rmat, lmat);
  76407. lmat.multiplyToRef(parentScaleInv, lmat);
  76408. }
  76409. else {
  76410. if (space == BABYLON.Space.WORLD && mesh) {
  76411. parentScale.copyFrom(mesh.getWorldMatrix());
  76412. parentScaleInv.copyFrom(parentScale);
  76413. parentScaleInv.invert();
  76414. lmat.multiplyToRef(parentScale, lmat);
  76415. lmat.multiplyToRef(rmat, lmat);
  76416. lmat.multiplyToRef(parentScaleInv, lmat);
  76417. }
  76418. else {
  76419. lmat.multiplyToRef(rmat, lmat);
  76420. }
  76421. }
  76422. lmat.m[12] = lx;
  76423. lmat.m[13] = ly;
  76424. lmat.m[14] = lz;
  76425. this.computeAbsoluteTransforms();
  76426. this.markAsDirty();
  76427. };
  76428. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  76429. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76430. if (space == BABYLON.Space.WORLD) {
  76431. var scaleMatrix = Bone._tmpMats[2];
  76432. scaleMatrix.copyFrom(this._scaleMatrix);
  76433. rotMatInv.copyFrom(this.getAbsoluteTransform());
  76434. if (mesh) {
  76435. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  76436. var meshScale = Bone._tmpMats[3];
  76437. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  76438. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  76439. }
  76440. rotMatInv.invert();
  76441. scaleMatrix.m[0] *= this._scalingDeterminant;
  76442. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76443. }
  76444. else {
  76445. rotMatInv.copyFrom(this.getLocalMatrix());
  76446. rotMatInv.invert();
  76447. var scaleMatrix = Bone._tmpMats[2];
  76448. scaleMatrix.copyFrom(this._scaleMatrix);
  76449. if (this._parent) {
  76450. var pscaleMatrix = Bone._tmpMats[3];
  76451. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  76452. pscaleMatrix.invert();
  76453. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  76454. }
  76455. else {
  76456. scaleMatrix.m[0] *= this._scalingDeterminant;
  76457. }
  76458. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76459. }
  76460. };
  76461. /**
  76462. * Get the scale of the bone
  76463. * @returns the scale of the bone
  76464. */
  76465. Bone.prototype.getScale = function () {
  76466. return this._scaleVector.clone();
  76467. };
  76468. /**
  76469. * Copy the scale of the bone to a vector3.
  76470. * @param result The vector3 to copy the scale to
  76471. */
  76472. Bone.prototype.getScaleToRef = function (result) {
  76473. result.copyFrom(this._scaleVector);
  76474. };
  76475. /**
  76476. * Get the position of the bone in local or world space.
  76477. * @param space The space that the returned position is in.
  76478. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76479. * @returns The position of the bone
  76480. */
  76481. Bone.prototype.getPosition = function (space, mesh) {
  76482. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76483. if (mesh === void 0) { mesh = null; }
  76484. var pos = BABYLON.Vector3.Zero();
  76485. this.getPositionToRef(space, mesh, pos);
  76486. return pos;
  76487. };
  76488. /**
  76489. * Copy the position of the bone to a vector3 in local or world space.
  76490. * @param space The space that the returned position is in.
  76491. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76492. * @param result The vector3 to copy the position to.
  76493. */
  76494. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  76495. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76496. if (space == BABYLON.Space.LOCAL) {
  76497. var lm = this.getLocalMatrix();
  76498. result.x = lm.m[12];
  76499. result.y = lm.m[13];
  76500. result.z = lm.m[14];
  76501. }
  76502. else {
  76503. var wm = null;
  76504. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76505. if (mesh) {
  76506. wm = mesh.getWorldMatrix();
  76507. }
  76508. this._skeleton.computeAbsoluteTransforms();
  76509. var tmat = Bone._tmpMats[0];
  76510. if (mesh && wm) {
  76511. tmat.copyFrom(this.getAbsoluteTransform());
  76512. tmat.multiplyToRef(wm, tmat);
  76513. }
  76514. else {
  76515. tmat = this.getAbsoluteTransform();
  76516. }
  76517. result.x = tmat.m[12];
  76518. result.y = tmat.m[13];
  76519. result.z = tmat.m[14];
  76520. }
  76521. };
  76522. /**
  76523. * Get the absolute position of the bone (world space).
  76524. * @param mesh The mesh that this bone is attached to.
  76525. * @returns The absolute position of the bone
  76526. */
  76527. Bone.prototype.getAbsolutePosition = function (mesh) {
  76528. if (mesh === void 0) { mesh = null; }
  76529. var pos = BABYLON.Vector3.Zero();
  76530. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  76531. return pos;
  76532. };
  76533. /**
  76534. * Copy the absolute position of the bone (world space) to the result param.
  76535. * @param mesh The mesh that this bone is attached to.
  76536. * @param result The vector3 to copy the absolute position to.
  76537. */
  76538. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  76539. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  76540. };
  76541. /**
  76542. * Compute the absolute transforms of this bone and its children.
  76543. */
  76544. Bone.prototype.computeAbsoluteTransforms = function () {
  76545. if (this._parent) {
  76546. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76547. }
  76548. else {
  76549. this._absoluteTransform.copyFrom(this._localMatrix);
  76550. var poseMatrix = this._skeleton.getPoseMatrix();
  76551. if (poseMatrix) {
  76552. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  76553. }
  76554. }
  76555. var children = this.children;
  76556. var len = children.length;
  76557. for (var i = 0; i < len; i++) {
  76558. children[i].computeAbsoluteTransforms();
  76559. }
  76560. };
  76561. Bone.prototype._syncScaleVector = function () {
  76562. var lm = this.getLocalMatrix();
  76563. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  76564. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  76565. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  76566. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  76567. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  76568. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  76569. this._scaleVector.x = xs * Math.sqrt(xsq);
  76570. this._scaleVector.y = ys * Math.sqrt(ysq);
  76571. this._scaleVector.z = zs * Math.sqrt(zsq);
  76572. if (this._parent) {
  76573. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  76574. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  76575. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  76576. }
  76577. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  76578. };
  76579. /**
  76580. * Get the world direction from an axis that is in the local space of the bone.
  76581. * @param localAxis The local direction that is used to compute the world direction.
  76582. * @param mesh The mesh that this bone is attached to.
  76583. * @returns The world direction
  76584. */
  76585. Bone.prototype.getDirection = function (localAxis, mesh) {
  76586. if (mesh === void 0) { mesh = null; }
  76587. var result = BABYLON.Vector3.Zero();
  76588. this.getDirectionToRef(localAxis, mesh, result);
  76589. return result;
  76590. };
  76591. /**
  76592. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  76593. * @param localAxis The local direction that is used to compute the world direction.
  76594. * @param mesh The mesh that this bone is attached to.
  76595. * @param result The vector3 that the world direction will be copied to.
  76596. */
  76597. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  76598. if (mesh === void 0) { mesh = null; }
  76599. var wm = null;
  76600. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76601. if (mesh) {
  76602. wm = mesh.getWorldMatrix();
  76603. }
  76604. this._skeleton.computeAbsoluteTransforms();
  76605. var mat = Bone._tmpMats[0];
  76606. mat.copyFrom(this.getAbsoluteTransform());
  76607. if (mesh && wm) {
  76608. mat.multiplyToRef(wm, mat);
  76609. }
  76610. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  76611. result.normalize();
  76612. };
  76613. /**
  76614. * Get the euler rotation of the bone in local or world space.
  76615. * @param space The space that the rotation should be in.
  76616. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76617. * @returns The euler rotation
  76618. */
  76619. Bone.prototype.getRotation = function (space, mesh) {
  76620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76621. if (mesh === void 0) { mesh = null; }
  76622. var result = BABYLON.Vector3.Zero();
  76623. this.getRotationToRef(space, mesh, result);
  76624. return result;
  76625. };
  76626. /**
  76627. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  76628. * @param space The space that the rotation should be in.
  76629. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76630. * @param result The vector3 that the rotation should be copied to.
  76631. */
  76632. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  76633. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76634. if (mesh === void 0) { mesh = null; }
  76635. var quat = Bone._tmpQuat;
  76636. this.getRotationQuaternionToRef(space, mesh, quat);
  76637. quat.toEulerAnglesToRef(result);
  76638. };
  76639. /**
  76640. * Get the quaternion rotation of the bone in either local or world space.
  76641. * @param space The space that the rotation should be in.
  76642. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76643. * @returns The quaternion rotation
  76644. */
  76645. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  76646. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76647. if (mesh === void 0) { mesh = null; }
  76648. var result = BABYLON.Quaternion.Identity();
  76649. this.getRotationQuaternionToRef(space, mesh, result);
  76650. return result;
  76651. };
  76652. /**
  76653. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  76654. * @param space The space that the rotation should be in.
  76655. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76656. * @param result The quaternion that the rotation should be copied to.
  76657. */
  76658. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  76659. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76660. if (mesh === void 0) { mesh = null; }
  76661. if (space == BABYLON.Space.LOCAL) {
  76662. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  76663. }
  76664. else {
  76665. var mat = Bone._tmpMats[0];
  76666. var amat = this.getAbsoluteTransform();
  76667. if (mesh) {
  76668. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76669. }
  76670. else {
  76671. mat.copyFrom(amat);
  76672. }
  76673. mat.m[0] *= this._scalingDeterminant;
  76674. mat.m[1] *= this._scalingDeterminant;
  76675. mat.m[2] *= this._scalingDeterminant;
  76676. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  76677. }
  76678. };
  76679. /**
  76680. * Get the rotation matrix of the bone in local or world space.
  76681. * @param space The space that the rotation should be in.
  76682. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76683. * @returns The rotation matrix
  76684. */
  76685. Bone.prototype.getRotationMatrix = function (space, mesh) {
  76686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76687. var result = BABYLON.Matrix.Identity();
  76688. this.getRotationMatrixToRef(space, mesh, result);
  76689. return result;
  76690. };
  76691. /**
  76692. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  76693. * @param space The space that the rotation should be in.
  76694. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76695. * @param result The quaternion that the rotation should be copied to.
  76696. */
  76697. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  76698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76699. if (space == BABYLON.Space.LOCAL) {
  76700. this.getLocalMatrix().getRotationMatrixToRef(result);
  76701. }
  76702. else {
  76703. var mat = Bone._tmpMats[0];
  76704. var amat = this.getAbsoluteTransform();
  76705. if (mesh) {
  76706. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76707. }
  76708. else {
  76709. mat.copyFrom(amat);
  76710. }
  76711. mat.m[0] *= this._scalingDeterminant;
  76712. mat.m[1] *= this._scalingDeterminant;
  76713. mat.m[2] *= this._scalingDeterminant;
  76714. mat.getRotationMatrixToRef(result);
  76715. }
  76716. };
  76717. /**
  76718. * Get the world position of a point that is in the local space of the bone.
  76719. * @param position The local position
  76720. * @param mesh The mesh that this bone is attached to.
  76721. * @returns The world position
  76722. */
  76723. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  76724. if (mesh === void 0) { mesh = null; }
  76725. var result = BABYLON.Vector3.Zero();
  76726. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  76727. return result;
  76728. };
  76729. /**
  76730. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  76731. * @param position The local position
  76732. * @param mesh The mesh that this bone is attached to.
  76733. * @param result The vector3 that the world position should be copied to.
  76734. */
  76735. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  76736. if (mesh === void 0) { mesh = null; }
  76737. var wm = null;
  76738. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76739. if (mesh) {
  76740. wm = mesh.getWorldMatrix();
  76741. }
  76742. this._skeleton.computeAbsoluteTransforms();
  76743. var tmat = Bone._tmpMats[0];
  76744. if (mesh && wm) {
  76745. tmat.copyFrom(this.getAbsoluteTransform());
  76746. tmat.multiplyToRef(wm, tmat);
  76747. }
  76748. else {
  76749. tmat = this.getAbsoluteTransform();
  76750. }
  76751. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76752. };
  76753. /**
  76754. * Get the local position of a point that is in world space.
  76755. * @param position The world position
  76756. * @param mesh The mesh that this bone is attached to.
  76757. * @returns The local position
  76758. */
  76759. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  76760. if (mesh === void 0) { mesh = null; }
  76761. var result = BABYLON.Vector3.Zero();
  76762. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  76763. return result;
  76764. };
  76765. /**
  76766. * Get the local position of a point that is in world space and copy it to the result param.
  76767. * @param position The world position
  76768. * @param mesh The mesh that this bone is attached to.
  76769. * @param result The vector3 that the local position should be copied to.
  76770. */
  76771. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  76772. if (mesh === void 0) { mesh = null; }
  76773. var wm = null;
  76774. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76775. if (mesh) {
  76776. wm = mesh.getWorldMatrix();
  76777. }
  76778. this._skeleton.computeAbsoluteTransforms();
  76779. var tmat = Bone._tmpMats[0];
  76780. tmat.copyFrom(this.getAbsoluteTransform());
  76781. if (mesh && wm) {
  76782. tmat.multiplyToRef(wm, tmat);
  76783. }
  76784. tmat.invert();
  76785. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76786. };
  76787. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76788. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  76789. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76790. return Bone;
  76791. }(BABYLON.Node));
  76792. BABYLON.Bone = Bone;
  76793. })(BABYLON || (BABYLON = {}));
  76794. //# sourceMappingURL=babylon.bone.js.map
  76795. "use strict";
  76796. var BABYLON;
  76797. (function (BABYLON) {
  76798. var BoneIKController = /** @class */ (function () {
  76799. function BoneIKController(mesh, bone, options) {
  76800. this.targetPosition = BABYLON.Vector3.Zero();
  76801. this.poleTargetPosition = BABYLON.Vector3.Zero();
  76802. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  76803. this.poleAngle = 0;
  76804. this.slerpAmount = 1;
  76805. this._bone1Quat = BABYLON.Quaternion.Identity();
  76806. this._bone1Mat = BABYLON.Matrix.Identity();
  76807. this._bone2Ang = Math.PI;
  76808. this._maxAngle = Math.PI;
  76809. this._rightHandedSystem = false;
  76810. this._bendAxis = BABYLON.Vector3.Right();
  76811. this._slerping = false;
  76812. this._adjustRoll = 0;
  76813. this._bone2 = bone;
  76814. this._bone1 = bone.getParent();
  76815. if (!this._bone1) {
  76816. return;
  76817. }
  76818. this.mesh = mesh;
  76819. var bonePos = bone.getPosition();
  76820. if (bone.getAbsoluteTransform().determinant() > 0) {
  76821. this._rightHandedSystem = true;
  76822. this._bendAxis.x = 0;
  76823. this._bendAxis.y = 0;
  76824. this._bendAxis.z = -1;
  76825. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  76826. this._adjustRoll = Math.PI * .5;
  76827. this._bendAxis.z = 1;
  76828. }
  76829. }
  76830. if (this._bone1.length) {
  76831. var boneScale1 = this._bone1.getScale();
  76832. var boneScale2 = this._bone2.getScale();
  76833. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  76834. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  76835. }
  76836. else if (this._bone1.children[0]) {
  76837. mesh.computeWorldMatrix(true);
  76838. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  76839. var pos2 = this._bone2.getAbsolutePosition(mesh);
  76840. var pos3 = this._bone1.getAbsolutePosition(mesh);
  76841. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  76842. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  76843. }
  76844. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  76845. this.maxAngle = Math.PI;
  76846. if (options) {
  76847. if (options.targetMesh) {
  76848. this.targetMesh = options.targetMesh;
  76849. this.targetMesh.computeWorldMatrix(true);
  76850. }
  76851. if (options.poleTargetMesh) {
  76852. this.poleTargetMesh = options.poleTargetMesh;
  76853. this.poleTargetMesh.computeWorldMatrix(true);
  76854. }
  76855. else if (options.poleTargetBone) {
  76856. this.poleTargetBone = options.poleTargetBone;
  76857. }
  76858. else if (this._bone1.getParent()) {
  76859. this.poleTargetBone = this._bone1.getParent();
  76860. }
  76861. if (options.poleTargetLocalOffset) {
  76862. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  76863. }
  76864. if (options.poleAngle) {
  76865. this.poleAngle = options.poleAngle;
  76866. }
  76867. if (options.bendAxis) {
  76868. this._bendAxis.copyFrom(options.bendAxis);
  76869. }
  76870. if (options.maxAngle) {
  76871. this.maxAngle = options.maxAngle;
  76872. }
  76873. if (options.slerpAmount) {
  76874. this.slerpAmount = options.slerpAmount;
  76875. }
  76876. }
  76877. }
  76878. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  76879. get: function () {
  76880. return this._maxAngle;
  76881. },
  76882. set: function (value) {
  76883. this._setMaxAngle(value);
  76884. },
  76885. enumerable: true,
  76886. configurable: true
  76887. });
  76888. BoneIKController.prototype._setMaxAngle = function (ang) {
  76889. if (ang < 0) {
  76890. ang = 0;
  76891. }
  76892. if (ang > Math.PI || ang == undefined) {
  76893. ang = Math.PI;
  76894. }
  76895. this._maxAngle = ang;
  76896. var a = this._bone1Length;
  76897. var b = this._bone2Length;
  76898. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  76899. };
  76900. BoneIKController.prototype.update = function () {
  76901. var bone1 = this._bone1;
  76902. if (!bone1) {
  76903. return;
  76904. }
  76905. var target = this.targetPosition;
  76906. var poleTarget = this.poleTargetPosition;
  76907. var mat1 = BoneIKController._tmpMats[0];
  76908. var mat2 = BoneIKController._tmpMats[1];
  76909. if (this.targetMesh) {
  76910. target.copyFrom(this.targetMesh.getAbsolutePosition());
  76911. }
  76912. if (this.poleTargetBone) {
  76913. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  76914. }
  76915. else if (this.poleTargetMesh) {
  76916. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  76917. }
  76918. var bonePos = BoneIKController._tmpVecs[0];
  76919. var zaxis = BoneIKController._tmpVecs[1];
  76920. var xaxis = BoneIKController._tmpVecs[2];
  76921. var yaxis = BoneIKController._tmpVecs[3];
  76922. var upAxis = BoneIKController._tmpVecs[4];
  76923. var _tmpQuat = BoneIKController._tmpQuat;
  76924. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  76925. poleTarget.subtractToRef(bonePos, upAxis);
  76926. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  76927. upAxis.y = 1;
  76928. }
  76929. else {
  76930. upAxis.normalize();
  76931. }
  76932. target.subtractToRef(bonePos, yaxis);
  76933. yaxis.normalize();
  76934. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  76935. zaxis.normalize();
  76936. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  76937. xaxis.normalize();
  76938. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  76939. var a = this._bone1Length;
  76940. var b = this._bone2Length;
  76941. var c = BABYLON.Vector3.Distance(bonePos, target);
  76942. if (this._maxReach > 0) {
  76943. c = Math.min(this._maxReach, c);
  76944. }
  76945. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  76946. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  76947. if (acosa > 1) {
  76948. acosa = 1;
  76949. }
  76950. if (acosb > 1) {
  76951. acosb = 1;
  76952. }
  76953. if (acosa < -1) {
  76954. acosa = -1;
  76955. }
  76956. if (acosb < -1) {
  76957. acosb = -1;
  76958. }
  76959. var angA = Math.acos(acosa);
  76960. var angB = Math.acos(acosb);
  76961. var angC = -angA - angB;
  76962. if (this._rightHandedSystem) {
  76963. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  76964. mat2.multiplyToRef(mat1, mat1);
  76965. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  76966. mat2.multiplyToRef(mat1, mat1);
  76967. }
  76968. else {
  76969. var _tmpVec = BoneIKController._tmpVecs[5];
  76970. _tmpVec.copyFrom(this._bendAxis);
  76971. _tmpVec.x *= -1;
  76972. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  76973. mat2.multiplyToRef(mat1, mat1);
  76974. }
  76975. if (this.poleAngle) {
  76976. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  76977. mat1.multiplyToRef(mat2, mat1);
  76978. }
  76979. if (this._bone1) {
  76980. if (this.slerpAmount < 1) {
  76981. if (!this._slerping) {
  76982. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  76983. }
  76984. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  76985. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  76986. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  76987. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  76988. this._slerping = true;
  76989. }
  76990. else {
  76991. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  76992. this._bone1Mat.copyFrom(mat1);
  76993. this._slerping = false;
  76994. }
  76995. }
  76996. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  76997. this._bone2Ang = angC;
  76998. };
  76999. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77000. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  77001. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77002. return BoneIKController;
  77003. }());
  77004. BABYLON.BoneIKController = BoneIKController;
  77005. })(BABYLON || (BABYLON = {}));
  77006. //# sourceMappingURL=babylon.boneIKController.js.map
  77007. "use strict";
  77008. var BABYLON;
  77009. (function (BABYLON) {
  77010. var BoneLookController = /** @class */ (function () {
  77011. /**
  77012. * Create a BoneLookController
  77013. * @param mesh the mesh that the bone belongs to
  77014. * @param bone the bone that will be looking to the target
  77015. * @param target the target Vector3 to look at
  77016. * @param settings optional settings:
  77017. * - maxYaw: the maximum angle the bone will yaw to
  77018. * - minYaw: the minimum angle the bone will yaw to
  77019. * - maxPitch: the maximum angle the bone will pitch to
  77020. * - minPitch: the minimum angle the bone will yaw to
  77021. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  77022. * - upAxis: the up axis of the coordinate system
  77023. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77024. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  77025. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  77026. * - adjustYaw: used to make an adjustment to the yaw of the bone
  77027. * - adjustPitch: used to make an adjustment to the pitch of the bone
  77028. * - adjustRoll: used to make an adjustment to the roll of the bone
  77029. **/
  77030. function BoneLookController(mesh, bone, target, options) {
  77031. /**
  77032. * The up axis of the coordinate system that is used when the bone is rotated.
  77033. */
  77034. this.upAxis = BABYLON.Vector3.Up();
  77035. /**
  77036. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77037. */
  77038. this.upAxisSpace = BABYLON.Space.LOCAL;
  77039. /**
  77040. * Used to make an adjustment to the yaw of the bone.
  77041. */
  77042. this.adjustYaw = 0;
  77043. /**
  77044. * Used to make an adjustment to the pitch of the bone.
  77045. */
  77046. this.adjustPitch = 0;
  77047. /**
  77048. * Used to make an adjustment to the roll of the bone.
  77049. */
  77050. this.adjustRoll = 0;
  77051. /**
  77052. * 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).
  77053. */
  77054. this.slerpAmount = 1;
  77055. this._boneQuat = BABYLON.Quaternion.Identity();
  77056. this._slerping = false;
  77057. this._firstFrameSkipped = false;
  77058. this._fowardAxis = BABYLON.Vector3.Forward();
  77059. this.mesh = mesh;
  77060. this.bone = bone;
  77061. this.target = target;
  77062. if (options) {
  77063. if (options.adjustYaw) {
  77064. this.adjustYaw = options.adjustYaw;
  77065. }
  77066. if (options.adjustPitch) {
  77067. this.adjustPitch = options.adjustPitch;
  77068. }
  77069. if (options.adjustRoll) {
  77070. this.adjustRoll = options.adjustRoll;
  77071. }
  77072. if (options.maxYaw != null) {
  77073. this.maxYaw = options.maxYaw;
  77074. }
  77075. else {
  77076. this.maxYaw = Math.PI;
  77077. }
  77078. if (options.minYaw != null) {
  77079. this.minYaw = options.minYaw;
  77080. }
  77081. else {
  77082. this.minYaw = -Math.PI;
  77083. }
  77084. if (options.maxPitch != null) {
  77085. this.maxPitch = options.maxPitch;
  77086. }
  77087. else {
  77088. this.maxPitch = Math.PI;
  77089. }
  77090. if (options.minPitch != null) {
  77091. this.minPitch = options.minPitch;
  77092. }
  77093. else {
  77094. this.minPitch = -Math.PI;
  77095. }
  77096. if (options.slerpAmount != null) {
  77097. this.slerpAmount = options.slerpAmount;
  77098. }
  77099. if (options.upAxis != null) {
  77100. this.upAxis = options.upAxis;
  77101. }
  77102. if (options.upAxisSpace != null) {
  77103. this.upAxisSpace = options.upAxisSpace;
  77104. }
  77105. if (options.yawAxis != null || options.pitchAxis != null) {
  77106. var newYawAxis = BABYLON.Axis.Y;
  77107. var newPitchAxis = BABYLON.Axis.X;
  77108. if (options.yawAxis != null) {
  77109. newYawAxis = options.yawAxis.clone();
  77110. newYawAxis.normalize();
  77111. }
  77112. if (options.pitchAxis != null) {
  77113. newPitchAxis = options.pitchAxis.clone();
  77114. newPitchAxis.normalize();
  77115. }
  77116. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  77117. this._transformYawPitch = BABYLON.Matrix.Identity();
  77118. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  77119. this._transformYawPitchInv = this._transformYawPitch.clone();
  77120. this._transformYawPitch.invert();
  77121. }
  77122. }
  77123. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  77124. this.upAxisSpace = BABYLON.Space.LOCAL;
  77125. }
  77126. }
  77127. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  77128. /**
  77129. * Get/set the minimum yaw angle that the bone can look to.
  77130. */
  77131. get: function () {
  77132. return this._minYaw;
  77133. },
  77134. set: function (value) {
  77135. this._minYaw = value;
  77136. this._minYawSin = Math.sin(value);
  77137. this._minYawCos = Math.cos(value);
  77138. if (this._maxYaw != null) {
  77139. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77140. this._yawRange = this._maxYaw - this._minYaw;
  77141. }
  77142. },
  77143. enumerable: true,
  77144. configurable: true
  77145. });
  77146. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  77147. /**
  77148. * Get/set the maximum yaw angle that the bone can look to.
  77149. */
  77150. get: function () {
  77151. return this._maxYaw;
  77152. },
  77153. set: function (value) {
  77154. this._maxYaw = value;
  77155. this._maxYawSin = Math.sin(value);
  77156. this._maxYawCos = Math.cos(value);
  77157. if (this._minYaw != null) {
  77158. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77159. this._yawRange = this._maxYaw - this._minYaw;
  77160. }
  77161. },
  77162. enumerable: true,
  77163. configurable: true
  77164. });
  77165. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  77166. /**
  77167. * Get/set the minimum pitch angle that the bone can look to.
  77168. */
  77169. get: function () {
  77170. return this._minPitch;
  77171. },
  77172. set: function (value) {
  77173. this._minPitch = value;
  77174. this._minPitchTan = Math.tan(value);
  77175. },
  77176. enumerable: true,
  77177. configurable: true
  77178. });
  77179. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  77180. /**
  77181. * Get/set the maximum pitch angle that the bone can look to.
  77182. */
  77183. get: function () {
  77184. return this._maxPitch;
  77185. },
  77186. set: function (value) {
  77187. this._maxPitch = value;
  77188. this._maxPitchTan = Math.tan(value);
  77189. },
  77190. enumerable: true,
  77191. configurable: true
  77192. });
  77193. /**
  77194. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  77195. */
  77196. BoneLookController.prototype.update = function () {
  77197. //skip the first frame when slerping so that the mesh rotation is correct
  77198. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  77199. this._firstFrameSkipped = true;
  77200. return;
  77201. }
  77202. var bone = this.bone;
  77203. var bonePos = BoneLookController._tmpVecs[0];
  77204. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  77205. var target = this.target;
  77206. var _tmpMat1 = BoneLookController._tmpMats[0];
  77207. var _tmpMat2 = BoneLookController._tmpMats[1];
  77208. var mesh = this.mesh;
  77209. var parentBone = bone.getParent();
  77210. var upAxis = BoneLookController._tmpVecs[1];
  77211. upAxis.copyFrom(this.upAxis);
  77212. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  77213. if (this._transformYawPitch) {
  77214. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  77215. }
  77216. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  77217. }
  77218. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  77219. mesh.getDirectionToRef(upAxis, upAxis);
  77220. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  77221. upAxis.normalize();
  77222. }
  77223. }
  77224. var checkYaw = false;
  77225. var checkPitch = false;
  77226. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  77227. checkYaw = true;
  77228. }
  77229. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  77230. checkPitch = true;
  77231. }
  77232. if (checkYaw || checkPitch) {
  77233. var spaceMat = BoneLookController._tmpMats[2];
  77234. var spaceMatInv = BoneLookController._tmpMats[3];
  77235. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  77236. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  77237. }
  77238. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  77239. spaceMat.copyFrom(mesh.getWorldMatrix());
  77240. }
  77241. else {
  77242. var forwardAxis = BoneLookController._tmpVecs[2];
  77243. forwardAxis.copyFrom(this._fowardAxis);
  77244. if (this._transformYawPitch) {
  77245. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  77246. }
  77247. if (parentBone) {
  77248. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  77249. }
  77250. else {
  77251. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  77252. }
  77253. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  77254. rightAxis.normalize();
  77255. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  77256. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  77257. }
  77258. spaceMat.invertToRef(spaceMatInv);
  77259. var xzlen = null;
  77260. if (checkPitch) {
  77261. var localTarget = BoneLookController._tmpVecs[3];
  77262. target.subtractToRef(bonePos, localTarget);
  77263. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77264. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77265. var pitch = Math.atan2(localTarget.y, xzlen);
  77266. var newPitch = pitch;
  77267. if (pitch > this._maxPitch) {
  77268. localTarget.y = this._maxPitchTan * xzlen;
  77269. newPitch = this._maxPitch;
  77270. }
  77271. else if (pitch < this._minPitch) {
  77272. localTarget.y = this._minPitchTan * xzlen;
  77273. newPitch = this._minPitch;
  77274. }
  77275. if (pitch != newPitch) {
  77276. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77277. localTarget.addInPlace(bonePos);
  77278. target = localTarget;
  77279. }
  77280. }
  77281. if (checkYaw) {
  77282. var localTarget = BoneLookController._tmpVecs[4];
  77283. target.subtractToRef(bonePos, localTarget);
  77284. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77285. var yaw = Math.atan2(localTarget.x, localTarget.z);
  77286. var newYaw = yaw;
  77287. if (yaw > this._maxYaw || yaw < this._minYaw) {
  77288. if (xzlen == null) {
  77289. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77290. }
  77291. if (this._yawRange > Math.PI) {
  77292. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  77293. localTarget.z = this._maxYawCos * xzlen;
  77294. localTarget.x = this._maxYawSin * xzlen;
  77295. newYaw = this._maxYaw;
  77296. }
  77297. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  77298. localTarget.z = this._minYawCos * xzlen;
  77299. localTarget.x = this._minYawSin * xzlen;
  77300. newYaw = this._minYaw;
  77301. }
  77302. }
  77303. else {
  77304. if (yaw > this._maxYaw) {
  77305. localTarget.z = this._maxYawCos * xzlen;
  77306. localTarget.x = this._maxYawSin * xzlen;
  77307. newYaw = this._maxYaw;
  77308. }
  77309. else if (yaw < this._minYaw) {
  77310. localTarget.z = this._minYawCos * xzlen;
  77311. localTarget.x = this._minYawSin * xzlen;
  77312. newYaw = this._minYaw;
  77313. }
  77314. }
  77315. }
  77316. if (this._slerping && this._yawRange > Math.PI) {
  77317. //are we going to be crossing into the min/max region?
  77318. var boneFwd = BoneLookController._tmpVecs[8];
  77319. boneFwd.copyFrom(BABYLON.Axis.Z);
  77320. if (this._transformYawPitch) {
  77321. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  77322. }
  77323. var boneRotMat = BoneLookController._tmpMats[4];
  77324. this._boneQuat.toRotationMatrix(boneRotMat);
  77325. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  77326. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  77327. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  77328. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  77329. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  77330. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  77331. if (angBtwTar > angBtwMidYaw) {
  77332. if (xzlen == null) {
  77333. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77334. }
  77335. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  77336. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  77337. if (angBtwMin < angBtwMax) {
  77338. newYaw = boneYaw + Math.PI * .75;
  77339. localTarget.z = Math.cos(newYaw) * xzlen;
  77340. localTarget.x = Math.sin(newYaw) * xzlen;
  77341. }
  77342. else {
  77343. newYaw = boneYaw - Math.PI * .75;
  77344. localTarget.z = Math.cos(newYaw) * xzlen;
  77345. localTarget.x = Math.sin(newYaw) * xzlen;
  77346. }
  77347. }
  77348. }
  77349. if (yaw != newYaw) {
  77350. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77351. localTarget.addInPlace(bonePos);
  77352. target = localTarget;
  77353. }
  77354. }
  77355. }
  77356. var zaxis = BoneLookController._tmpVecs[5];
  77357. var xaxis = BoneLookController._tmpVecs[6];
  77358. var yaxis = BoneLookController._tmpVecs[7];
  77359. var _tmpQuat = BoneLookController._tmpQuat;
  77360. target.subtractToRef(bonePos, zaxis);
  77361. zaxis.normalize();
  77362. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  77363. xaxis.normalize();
  77364. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  77365. yaxis.normalize();
  77366. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  77367. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  77368. return;
  77369. }
  77370. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  77371. return;
  77372. }
  77373. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  77374. return;
  77375. }
  77376. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  77377. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  77378. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  77379. }
  77380. if (this.slerpAmount < 1) {
  77381. if (!this._slerping) {
  77382. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  77383. }
  77384. if (this._transformYawPitch) {
  77385. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77386. }
  77387. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  77388. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  77389. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  77390. this._slerping = true;
  77391. }
  77392. else {
  77393. if (this._transformYawPitch) {
  77394. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77395. }
  77396. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  77397. this._slerping = false;
  77398. }
  77399. };
  77400. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  77401. var angDiff = ang2 - ang1;
  77402. angDiff %= Math.PI * 2;
  77403. if (angDiff > Math.PI) {
  77404. angDiff -= Math.PI * 2;
  77405. }
  77406. else if (angDiff < -Math.PI) {
  77407. angDiff += Math.PI * 2;
  77408. }
  77409. return angDiff;
  77410. };
  77411. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  77412. ang1 %= (2 * Math.PI);
  77413. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77414. ang2 %= (2 * Math.PI);
  77415. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77416. var ab = 0;
  77417. if (ang1 < ang2) {
  77418. ab = ang2 - ang1;
  77419. }
  77420. else {
  77421. ab = ang1 - ang2;
  77422. }
  77423. if (ab > Math.PI) {
  77424. ab = Math.PI * 2 - ab;
  77425. }
  77426. return ab;
  77427. };
  77428. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  77429. ang %= (2 * Math.PI);
  77430. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  77431. ang1 %= (2 * Math.PI);
  77432. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77433. ang2 %= (2 * Math.PI);
  77434. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77435. if (ang1 < ang2) {
  77436. if (ang > ang1 && ang < ang2) {
  77437. return true;
  77438. }
  77439. }
  77440. else {
  77441. if (ang > ang2 && ang < ang1) {
  77442. return true;
  77443. }
  77444. }
  77445. return false;
  77446. };
  77447. 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()];
  77448. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  77449. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77450. return BoneLookController;
  77451. }());
  77452. BABYLON.BoneLookController = BoneLookController;
  77453. })(BABYLON || (BABYLON = {}));
  77454. //# sourceMappingURL=babylon.boneLookController.js.map
  77455. "use strict";
  77456. var BABYLON;
  77457. (function (BABYLON) {
  77458. var Skeleton = /** @class */ (function () {
  77459. function Skeleton(name, id, scene) {
  77460. this.name = name;
  77461. this.id = id;
  77462. this.bones = new Array();
  77463. this.needInitialSkinMatrix = false;
  77464. this._isDirty = true;
  77465. this._meshesWithPoseMatrix = new Array();
  77466. this._identity = BABYLON.Matrix.Identity();
  77467. this._ranges = {};
  77468. this._lastAbsoluteTransformsUpdateId = -1;
  77469. /**
  77470. * Specifies if the skeleton should be serialized.
  77471. */
  77472. this.doNotSerialize = false;
  77473. // Events
  77474. /**
  77475. * An event triggered before computing the skeleton's matrices
  77476. */
  77477. this.onBeforeComputeObservable = new BABYLON.Observable();
  77478. this.bones = [];
  77479. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77480. scene.skeletons.push(this);
  77481. //make sure it will recalculate the matrix next time prepare is called.
  77482. this._isDirty = true;
  77483. }
  77484. // Members
  77485. Skeleton.prototype.getTransformMatrices = function (mesh) {
  77486. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  77487. return mesh._bonesTransformMatrices;
  77488. }
  77489. if (!this._transformMatrices) {
  77490. this.prepare();
  77491. }
  77492. return this._transformMatrices;
  77493. };
  77494. Skeleton.prototype.getScene = function () {
  77495. return this._scene;
  77496. };
  77497. // Methods
  77498. /**
  77499. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  77500. */
  77501. Skeleton.prototype.toString = function (fullDetails) {
  77502. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  77503. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  77504. if (fullDetails) {
  77505. ret += ", Ranges: {";
  77506. var first = true;
  77507. for (var name_1 in this._ranges) {
  77508. if (first) {
  77509. ret += ", ";
  77510. first = false;
  77511. }
  77512. ret += name_1;
  77513. }
  77514. ret += "}";
  77515. }
  77516. return ret;
  77517. };
  77518. /**
  77519. * Get bone's index searching by name
  77520. * @param {string} name is bone's name to search for
  77521. * @return {number} Indice of the bone. Returns -1 if not found
  77522. */
  77523. Skeleton.prototype.getBoneIndexByName = function (name) {
  77524. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  77525. if (this.bones[boneIndex].name === name) {
  77526. return boneIndex;
  77527. }
  77528. }
  77529. return -1;
  77530. };
  77531. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  77532. // check name not already in use
  77533. if (!this._ranges[name]) {
  77534. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  77535. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77536. if (this.bones[i].animations[0]) {
  77537. this.bones[i].animations[0].createRange(name, from, to);
  77538. }
  77539. }
  77540. }
  77541. };
  77542. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  77543. if (deleteFrames === void 0) { deleteFrames = true; }
  77544. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77545. if (this.bones[i].animations[0]) {
  77546. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  77547. }
  77548. }
  77549. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  77550. };
  77551. Skeleton.prototype.getAnimationRange = function (name) {
  77552. return this._ranges[name];
  77553. };
  77554. /**
  77555. * Returns as an Array, all AnimationRanges defined on this skeleton
  77556. */
  77557. Skeleton.prototype.getAnimationRanges = function () {
  77558. var animationRanges = [];
  77559. var name;
  77560. var i = 0;
  77561. for (name in this._ranges) {
  77562. animationRanges[i] = this._ranges[name];
  77563. i++;
  77564. }
  77565. return animationRanges;
  77566. };
  77567. /**
  77568. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  77569. */
  77570. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  77571. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77572. if (this._ranges[name] || !source.getAnimationRange(name)) {
  77573. return false;
  77574. }
  77575. var ret = true;
  77576. var frameOffset = this._getHighestAnimationFrame() + 1;
  77577. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  77578. var boneDict = {};
  77579. var sourceBones = source.bones;
  77580. var nBones;
  77581. var i;
  77582. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  77583. boneDict[sourceBones[i].name] = sourceBones[i];
  77584. }
  77585. if (this.bones.length !== sourceBones.length) {
  77586. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  77587. ret = false;
  77588. }
  77589. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  77590. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  77591. var boneName = this.bones[i].name;
  77592. var sourceBone = boneDict[boneName];
  77593. if (sourceBone) {
  77594. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  77595. }
  77596. else {
  77597. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  77598. ret = false;
  77599. }
  77600. }
  77601. // do not call createAnimationRange(), since it also is done to bones, which was already done
  77602. var range = source.getAnimationRange(name);
  77603. if (range) {
  77604. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  77605. }
  77606. return ret;
  77607. };
  77608. Skeleton.prototype.returnToRest = function () {
  77609. for (var index = 0; index < this.bones.length; index++) {
  77610. this.bones[index].returnToRest();
  77611. }
  77612. };
  77613. Skeleton.prototype._getHighestAnimationFrame = function () {
  77614. var ret = 0;
  77615. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77616. if (this.bones[i].animations[0]) {
  77617. var highest = this.bones[i].animations[0].getHighestFrame();
  77618. if (ret < highest) {
  77619. ret = highest;
  77620. }
  77621. }
  77622. }
  77623. return ret;
  77624. };
  77625. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  77626. var range = this.getAnimationRange(name);
  77627. if (!range) {
  77628. return null;
  77629. }
  77630. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  77631. };
  77632. Skeleton.prototype._markAsDirty = function () {
  77633. this._isDirty = true;
  77634. };
  77635. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  77636. this._meshesWithPoseMatrix.push(mesh);
  77637. };
  77638. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  77639. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  77640. if (index > -1) {
  77641. this._meshesWithPoseMatrix.splice(index, 1);
  77642. }
  77643. };
  77644. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  77645. this.onBeforeComputeObservable.notifyObservers(this);
  77646. for (var index = 0; index < this.bones.length; index++) {
  77647. var bone = this.bones[index];
  77648. var parentBone = bone.getParent();
  77649. if (parentBone) {
  77650. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  77651. }
  77652. else {
  77653. if (initialSkinMatrix) {
  77654. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  77655. }
  77656. else {
  77657. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  77658. }
  77659. }
  77660. if (bone._index !== -1) {
  77661. var mappedIndex = bone._index === null ? index : bone._index;
  77662. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  77663. }
  77664. }
  77665. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  77666. };
  77667. Skeleton.prototype.prepare = function () {
  77668. if (!this._isDirty) {
  77669. return;
  77670. }
  77671. if (this.needInitialSkinMatrix) {
  77672. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  77673. var mesh = this._meshesWithPoseMatrix[index];
  77674. var poseMatrix = mesh.getPoseMatrix();
  77675. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  77676. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77677. }
  77678. if (this._synchronizedWithMesh !== mesh) {
  77679. this._synchronizedWithMesh = mesh;
  77680. // Prepare bones
  77681. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  77682. var bone = this.bones[boneIndex];
  77683. if (!bone.getParent()) {
  77684. var matrix = bone.getBaseMatrix();
  77685. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  77686. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  77687. }
  77688. }
  77689. }
  77690. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  77691. }
  77692. }
  77693. else {
  77694. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  77695. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77696. }
  77697. this._computeTransformMatrices(this._transformMatrices, null);
  77698. }
  77699. this._isDirty = false;
  77700. this._scene._activeBones.addCount(this.bones.length, false);
  77701. };
  77702. Skeleton.prototype.getAnimatables = function () {
  77703. if (!this._animatables || this._animatables.length !== this.bones.length) {
  77704. this._animatables = [];
  77705. for (var index = 0; index < this.bones.length; index++) {
  77706. this._animatables.push(this.bones[index]);
  77707. }
  77708. }
  77709. return this._animatables;
  77710. };
  77711. Skeleton.prototype.clone = function (name, id) {
  77712. var result = new Skeleton(name, id || name, this._scene);
  77713. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77714. for (var index = 0; index < this.bones.length; index++) {
  77715. var source = this.bones[index];
  77716. var parentBone = null;
  77717. var parent_1 = source.getParent();
  77718. if (parent_1) {
  77719. var parentIndex = this.bones.indexOf(parent_1);
  77720. parentBone = result.bones[parentIndex];
  77721. }
  77722. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  77723. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  77724. }
  77725. if (this._ranges) {
  77726. result._ranges = {};
  77727. for (var rangeName in this._ranges) {
  77728. var range = this._ranges[rangeName];
  77729. if (range) {
  77730. result._ranges[rangeName] = range.clone();
  77731. }
  77732. }
  77733. }
  77734. this._isDirty = true;
  77735. return result;
  77736. };
  77737. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  77738. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  77739. this.bones.forEach(function (bone) {
  77740. bone.animations.forEach(function (animation) {
  77741. animation.enableBlending = true;
  77742. animation.blendingSpeed = blendingSpeed;
  77743. });
  77744. });
  77745. };
  77746. Skeleton.prototype.dispose = function () {
  77747. this._meshesWithPoseMatrix = [];
  77748. // Animations
  77749. this.getScene().stopAnimation(this);
  77750. // Remove from scene
  77751. this.getScene().removeSkeleton(this);
  77752. };
  77753. Skeleton.prototype.serialize = function () {
  77754. var serializationObject = {};
  77755. serializationObject.name = this.name;
  77756. serializationObject.id = this.id;
  77757. if (this.dimensionsAtRest) {
  77758. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  77759. }
  77760. serializationObject.bones = [];
  77761. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77762. for (var index = 0; index < this.bones.length; index++) {
  77763. var bone = this.bones[index];
  77764. var parent_2 = bone.getParent();
  77765. var serializedBone = {
  77766. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  77767. name: bone.name,
  77768. matrix: bone.getBaseMatrix().toArray(),
  77769. rest: bone.getRestPose().toArray()
  77770. };
  77771. serializationObject.bones.push(serializedBone);
  77772. if (bone.length) {
  77773. serializedBone.length = bone.length;
  77774. }
  77775. if (bone.animations && bone.animations.length > 0) {
  77776. serializedBone.animation = bone.animations[0].serialize();
  77777. }
  77778. serializationObject.ranges = [];
  77779. for (var name in this._ranges) {
  77780. var source = this._ranges[name];
  77781. if (!source) {
  77782. continue;
  77783. }
  77784. var range = {};
  77785. range.name = name;
  77786. range.from = source.from;
  77787. range.to = source.to;
  77788. serializationObject.ranges.push(range);
  77789. }
  77790. }
  77791. return serializationObject;
  77792. };
  77793. Skeleton.Parse = function (parsedSkeleton, scene) {
  77794. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  77795. if (parsedSkeleton.dimensionsAtRest) {
  77796. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  77797. }
  77798. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  77799. var index;
  77800. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  77801. var parsedBone = parsedSkeleton.bones[index];
  77802. var parentBone = null;
  77803. if (parsedBone.parentBoneIndex > -1) {
  77804. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  77805. }
  77806. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  77807. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  77808. if (parsedBone.length) {
  77809. bone.length = parsedBone.length;
  77810. }
  77811. if (parsedBone.animation) {
  77812. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  77813. }
  77814. }
  77815. // placed after bones, so createAnimationRange can cascade down
  77816. if (parsedSkeleton.ranges) {
  77817. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  77818. var data = parsedSkeleton.ranges[index];
  77819. skeleton.createAnimationRange(data.name, data.from, data.to);
  77820. }
  77821. }
  77822. return skeleton;
  77823. };
  77824. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  77825. if (forceUpdate === void 0) { forceUpdate = false; }
  77826. var renderId = this._scene.getRenderId();
  77827. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  77828. this.bones[0].computeAbsoluteTransforms();
  77829. this._lastAbsoluteTransformsUpdateId = renderId;
  77830. }
  77831. };
  77832. Skeleton.prototype.getPoseMatrix = function () {
  77833. var poseMatrix = null;
  77834. if (this._meshesWithPoseMatrix.length > 0) {
  77835. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  77836. }
  77837. return poseMatrix;
  77838. };
  77839. Skeleton.prototype.sortBones = function () {
  77840. var bones = new Array();
  77841. var visited = new Array(this.bones.length);
  77842. for (var index = 0; index < this.bones.length; index++) {
  77843. this._sortBones(index, bones, visited);
  77844. }
  77845. this.bones = bones;
  77846. };
  77847. Skeleton.prototype._sortBones = function (index, bones, visited) {
  77848. if (visited[index]) {
  77849. return;
  77850. }
  77851. visited[index] = true;
  77852. var bone = this.bones[index];
  77853. if (bone._index === undefined) {
  77854. bone._index = index;
  77855. }
  77856. var parentBone = bone.getParent();
  77857. if (parentBone) {
  77858. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  77859. }
  77860. bones.push(bone);
  77861. };
  77862. return Skeleton;
  77863. }());
  77864. BABYLON.Skeleton = Skeleton;
  77865. })(BABYLON || (BABYLON = {}));
  77866. //# sourceMappingURL=babylon.skeleton.js.map
  77867. "use strict";
  77868. var BABYLON;
  77869. (function (BABYLON) {
  77870. var SphericalPolynomial = /** @class */ (function () {
  77871. function SphericalPolynomial() {
  77872. this.x = BABYLON.Vector3.Zero();
  77873. this.y = BABYLON.Vector3.Zero();
  77874. this.z = BABYLON.Vector3.Zero();
  77875. this.xx = BABYLON.Vector3.Zero();
  77876. this.yy = BABYLON.Vector3.Zero();
  77877. this.zz = BABYLON.Vector3.Zero();
  77878. this.xy = BABYLON.Vector3.Zero();
  77879. this.yz = BABYLON.Vector3.Zero();
  77880. this.zx = BABYLON.Vector3.Zero();
  77881. }
  77882. SphericalPolynomial.prototype.addAmbient = function (color) {
  77883. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77884. this.xx = this.xx.add(colorVector);
  77885. this.yy = this.yy.add(colorVector);
  77886. this.zz = this.zz.add(colorVector);
  77887. };
  77888. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  77889. var result = new SphericalPolynomial();
  77890. result.x = harmonics.L11.scale(1.02333);
  77891. result.y = harmonics.L1_1.scale(1.02333);
  77892. result.z = harmonics.L10.scale(1.02333);
  77893. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  77894. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  77895. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  77896. result.yz = harmonics.L2_1.scale(0.858086);
  77897. result.zx = harmonics.L21.scale(0.858086);
  77898. result.xy = harmonics.L2_2.scale(0.858086);
  77899. result.scale(1.0 / Math.PI);
  77900. return result;
  77901. };
  77902. SphericalPolynomial.prototype.scale = function (scale) {
  77903. this.x = this.x.scale(scale);
  77904. this.y = this.y.scale(scale);
  77905. this.z = this.z.scale(scale);
  77906. this.xx = this.xx.scale(scale);
  77907. this.yy = this.yy.scale(scale);
  77908. this.zz = this.zz.scale(scale);
  77909. this.yz = this.yz.scale(scale);
  77910. this.zx = this.zx.scale(scale);
  77911. this.xy = this.xy.scale(scale);
  77912. };
  77913. return SphericalPolynomial;
  77914. }());
  77915. BABYLON.SphericalPolynomial = SphericalPolynomial;
  77916. var SphericalHarmonics = /** @class */ (function () {
  77917. function SphericalHarmonics() {
  77918. this.L00 = BABYLON.Vector3.Zero();
  77919. this.L1_1 = BABYLON.Vector3.Zero();
  77920. this.L10 = BABYLON.Vector3.Zero();
  77921. this.L11 = BABYLON.Vector3.Zero();
  77922. this.L2_2 = BABYLON.Vector3.Zero();
  77923. this.L2_1 = BABYLON.Vector3.Zero();
  77924. this.L20 = BABYLON.Vector3.Zero();
  77925. this.L21 = BABYLON.Vector3.Zero();
  77926. this.L22 = BABYLON.Vector3.Zero();
  77927. }
  77928. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  77929. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77930. var c = colorVector.scale(deltaSolidAngle);
  77931. this.L00 = this.L00.add(c.scale(0.282095));
  77932. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  77933. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  77934. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  77935. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  77936. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  77937. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  77938. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  77939. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  77940. };
  77941. SphericalHarmonics.prototype.scale = function (scale) {
  77942. this.L00 = this.L00.scale(scale);
  77943. this.L1_1 = this.L1_1.scale(scale);
  77944. this.L10 = this.L10.scale(scale);
  77945. this.L11 = this.L11.scale(scale);
  77946. this.L2_2 = this.L2_2.scale(scale);
  77947. this.L2_1 = this.L2_1.scale(scale);
  77948. this.L20 = this.L20.scale(scale);
  77949. this.L21 = this.L21.scale(scale);
  77950. this.L22 = this.L22.scale(scale);
  77951. };
  77952. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  77953. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  77954. //
  77955. // E_lm = A_l * L_lm
  77956. //
  77957. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  77958. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  77959. // the scaling factors are given in equation 9.
  77960. // Constant (Band 0)
  77961. this.L00 = this.L00.scale(3.141593);
  77962. // Linear (Band 1)
  77963. this.L1_1 = this.L1_1.scale(2.094395);
  77964. this.L10 = this.L10.scale(2.094395);
  77965. this.L11 = this.L11.scale(2.094395);
  77966. // Quadratic (Band 2)
  77967. this.L2_2 = this.L2_2.scale(0.785398);
  77968. this.L2_1 = this.L2_1.scale(0.785398);
  77969. this.L20 = this.L20.scale(0.785398);
  77970. this.L21 = this.L21.scale(0.785398);
  77971. this.L22 = this.L22.scale(0.785398);
  77972. };
  77973. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  77974. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  77975. // L = (1/pi) * E * rho
  77976. //
  77977. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  77978. this.scale(1.0 / Math.PI);
  77979. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  77980. // (The pixel shader must apply albedo after texture fetches, etc).
  77981. };
  77982. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  77983. var result = new SphericalHarmonics();
  77984. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  77985. result.L1_1 = polynomial.y.scale(0.977204);
  77986. result.L10 = polynomial.z.scale(0.977204);
  77987. result.L11 = polynomial.x.scale(0.977204);
  77988. result.L2_2 = polynomial.xy.scale(1.16538);
  77989. result.L2_1 = polynomial.yz.scale(1.16538);
  77990. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  77991. result.L21 = polynomial.zx.scale(1.16538);
  77992. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  77993. result.scale(Math.PI);
  77994. return result;
  77995. };
  77996. return SphericalHarmonics;
  77997. }());
  77998. BABYLON.SphericalHarmonics = SphericalHarmonics;
  77999. })(BABYLON || (BABYLON = {}));
  78000. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  78001. "use strict";
  78002. var BABYLON;
  78003. (function (BABYLON) {
  78004. var FileFaceOrientation = /** @class */ (function () {
  78005. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  78006. this.name = name;
  78007. this.worldAxisForNormal = worldAxisForNormal;
  78008. this.worldAxisForFileX = worldAxisForFileX;
  78009. this.worldAxisForFileY = worldAxisForFileY;
  78010. }
  78011. return FileFaceOrientation;
  78012. }());
  78013. ;
  78014. /**
  78015. * Helper class dealing with the extraction of spherical polynomial dataArray
  78016. * from a cube map.
  78017. */
  78018. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  78019. function CubeMapToSphericalPolynomialTools() {
  78020. }
  78021. /**
  78022. * Converts a texture to the according Spherical Polynomial data.
  78023. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78024. *
  78025. * @param texture The texture to extract the information from.
  78026. * @return The Spherical Polynomial data.
  78027. */
  78028. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  78029. if (!texture.isCube) {
  78030. // Only supports cube Textures currently.
  78031. return null;
  78032. }
  78033. var size = texture.getSize().width;
  78034. var right = texture.readPixels(0);
  78035. var left = texture.readPixels(1);
  78036. var up;
  78037. var down;
  78038. if (texture.isRenderTarget) {
  78039. up = texture.readPixels(3);
  78040. down = texture.readPixels(2);
  78041. }
  78042. else {
  78043. up = texture.readPixels(2);
  78044. down = texture.readPixels(3);
  78045. }
  78046. var front = texture.readPixels(4);
  78047. var back = texture.readPixels(5);
  78048. var gammaSpace = texture.gammaSpace;
  78049. // Always read as RGBA.
  78050. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  78051. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78052. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78053. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78054. }
  78055. var cubeInfo = {
  78056. size: size,
  78057. right: right,
  78058. left: left,
  78059. up: up,
  78060. down: down,
  78061. front: front,
  78062. back: back,
  78063. format: format,
  78064. type: type,
  78065. gammaSpace: gammaSpace,
  78066. };
  78067. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  78068. };
  78069. /**
  78070. * Converts a cubemap to the according Spherical Polynomial data.
  78071. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78072. *
  78073. * @param cubeInfo The Cube map to extract the information from.
  78074. * @return The Spherical Polynomial data.
  78075. */
  78076. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  78077. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  78078. var totalSolidAngle = 0.0;
  78079. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  78080. var du = 2.0 / cubeInfo.size;
  78081. var dv = du;
  78082. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  78083. var minUV = du * 0.5 - 1.0;
  78084. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78085. var fileFace = this.FileFaces[faceIndex];
  78086. var dataArray = cubeInfo[fileFace.name];
  78087. var v = minUV;
  78088. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  78089. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  78090. // Because SP is still linear, so summation is fine in that basis.
  78091. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  78092. for (var y = 0; y < cubeInfo.size; y++) {
  78093. var u = minUV;
  78094. for (var x = 0; x < cubeInfo.size; x++) {
  78095. // World direction (not normalised)
  78096. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  78097. worldDirection.normalize();
  78098. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  78099. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  78100. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  78101. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  78102. // Handle Integer types.
  78103. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78104. r /= 255;
  78105. g /= 255;
  78106. b /= 255;
  78107. }
  78108. // Handle Gamma space textures.
  78109. if (cubeInfo.gammaSpace) {
  78110. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  78111. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  78112. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  78113. }
  78114. var color = new BABYLON.Color3(r, g, b);
  78115. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  78116. totalSolidAngle += deltaSolidAngle;
  78117. u += du;
  78118. }
  78119. v += dv;
  78120. }
  78121. }
  78122. // Solid angle for entire sphere is 4*pi
  78123. var sphereSolidAngle = 4.0 * Math.PI;
  78124. // Adjust the solid angle to allow for how many faces we processed.
  78125. var facesProcessed = 6.0;
  78126. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  78127. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  78128. // This is needed because the numerical integration over the cube uses a
  78129. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  78130. // and also to compensate for accumulative error due to float precision in the summation.
  78131. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  78132. sphericalHarmonics.scale(correctionFactor);
  78133. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  78134. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  78135. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  78136. };
  78137. CubeMapToSphericalPolynomialTools.FileFaces = [
  78138. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  78139. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  78140. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  78141. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  78142. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  78143. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  78144. ];
  78145. return CubeMapToSphericalPolynomialTools;
  78146. }());
  78147. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  78148. })(BABYLON || (BABYLON = {}));
  78149. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  78150. "use strict";
  78151. var BABYLON;
  78152. (function (BABYLON) {
  78153. /**
  78154. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  78155. */
  78156. var PanoramaToCubeMapTools = /** @class */ (function () {
  78157. function PanoramaToCubeMapTools() {
  78158. }
  78159. /**
  78160. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  78161. *
  78162. * @param float32Array The source data.
  78163. * @param inputWidth The width of the input panorama.
  78164. * @param inputhHeight The height of the input panorama.
  78165. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  78166. * @return The cubemap data
  78167. */
  78168. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  78169. if (!float32Array) {
  78170. throw "ConvertPanoramaToCubemap: input cannot be null";
  78171. }
  78172. if (float32Array.length != inputWidth * inputHeight * 3) {
  78173. throw "ConvertPanoramaToCubemap: input size is wrong";
  78174. }
  78175. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  78176. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  78177. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  78178. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  78179. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  78180. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  78181. return {
  78182. front: textureFront,
  78183. back: textureBack,
  78184. left: textureLeft,
  78185. right: textureRight,
  78186. up: textureUp,
  78187. down: textureDown,
  78188. size: size,
  78189. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  78190. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  78191. gammaSpace: false,
  78192. };
  78193. };
  78194. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  78195. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  78196. var textureArray = new Float32Array(buffer);
  78197. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  78198. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  78199. var dy = 1 / texSize;
  78200. var fy = 0;
  78201. for (var y = 0; y < texSize; y++) {
  78202. var xv1 = faceData[0];
  78203. var xv2 = faceData[2];
  78204. for (var x = 0; x < texSize; x++) {
  78205. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  78206. v.normalize();
  78207. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  78208. // 3 channels per pixels
  78209. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  78210. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  78211. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  78212. xv1 = xv1.add(rotDX1);
  78213. xv2 = xv2.add(rotDX2);
  78214. }
  78215. fy += dy;
  78216. }
  78217. return textureArray;
  78218. };
  78219. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  78220. var theta = Math.atan2(vDir.z, vDir.x);
  78221. var phi = Math.acos(vDir.y);
  78222. while (theta < -Math.PI)
  78223. theta += 2 * Math.PI;
  78224. while (theta > Math.PI)
  78225. theta -= 2 * Math.PI;
  78226. var dx = theta / Math.PI;
  78227. var dy = phi / Math.PI;
  78228. // recenter.
  78229. dx = dx * 0.5 + 0.5;
  78230. var px = Math.round(dx * inputWidth);
  78231. if (px < 0)
  78232. px = 0;
  78233. else if (px >= inputWidth)
  78234. px = inputWidth - 1;
  78235. var py = Math.round(dy * inputHeight);
  78236. if (py < 0)
  78237. py = 0;
  78238. else if (py >= inputHeight)
  78239. py = inputHeight - 1;
  78240. var inputY = (inputHeight - py - 1);
  78241. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  78242. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  78243. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  78244. return {
  78245. r: r,
  78246. g: g,
  78247. b: b
  78248. };
  78249. };
  78250. PanoramaToCubeMapTools.FACE_FRONT = [
  78251. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78252. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78253. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78254. new BABYLON.Vector3(1.0, 1.0, -1.0)
  78255. ];
  78256. PanoramaToCubeMapTools.FACE_BACK = [
  78257. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78258. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78259. new BABYLON.Vector3(1.0, 1.0, 1.0),
  78260. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  78261. ];
  78262. PanoramaToCubeMapTools.FACE_RIGHT = [
  78263. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78264. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78265. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78266. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78267. ];
  78268. PanoramaToCubeMapTools.FACE_LEFT = [
  78269. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78270. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78271. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78272. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  78273. ];
  78274. PanoramaToCubeMapTools.FACE_DOWN = [
  78275. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78276. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78277. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78278. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78279. ];
  78280. PanoramaToCubeMapTools.FACE_UP = [
  78281. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78282. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78283. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78284. new BABYLON.Vector3(1.0, -1.0, -1.0)
  78285. ];
  78286. return PanoramaToCubeMapTools;
  78287. }());
  78288. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  78289. })(BABYLON || (BABYLON = {}));
  78290. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  78291. "use strict";
  78292. var BABYLON;
  78293. (function (BABYLON) {
  78294. ;
  78295. /**
  78296. * This groups tools to convert HDR texture to native colors array.
  78297. */
  78298. var HDRTools = /** @class */ (function () {
  78299. function HDRTools() {
  78300. }
  78301. HDRTools.Ldexp = function (mantissa, exponent) {
  78302. if (exponent > 1023) {
  78303. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  78304. }
  78305. if (exponent < -1074) {
  78306. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  78307. }
  78308. return mantissa * Math.pow(2, exponent);
  78309. };
  78310. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  78311. if (exponent > 0) {
  78312. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  78313. float32array[index + 0] = red * exponent;
  78314. float32array[index + 1] = green * exponent;
  78315. float32array[index + 2] = blue * exponent;
  78316. }
  78317. else {
  78318. float32array[index + 0] = 0;
  78319. float32array[index + 1] = 0;
  78320. float32array[index + 2] = 0;
  78321. }
  78322. };
  78323. HDRTools.readStringLine = function (uint8array, startIndex) {
  78324. var line = "";
  78325. var character = "";
  78326. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  78327. character = String.fromCharCode(uint8array[i]);
  78328. if (character == "\n") {
  78329. break;
  78330. }
  78331. line += character;
  78332. }
  78333. return line;
  78334. };
  78335. /**
  78336. * Reads header information from an RGBE texture stored in a native array.
  78337. * More information on this format are available here:
  78338. * https://en.wikipedia.org/wiki/RGBE_image_format
  78339. *
  78340. * @param uint8array The binary file stored in native array.
  78341. * @return The header information.
  78342. */
  78343. HDRTools.RGBE_ReadHeader = function (uint8array) {
  78344. var height = 0;
  78345. var width = 0;
  78346. var line = this.readStringLine(uint8array, 0);
  78347. if (line[0] != '#' || line[1] != '?') {
  78348. throw "Bad HDR Format.";
  78349. }
  78350. var endOfHeader = false;
  78351. var findFormat = false;
  78352. var lineIndex = 0;
  78353. do {
  78354. lineIndex += (line.length + 1);
  78355. line = this.readStringLine(uint8array, lineIndex);
  78356. if (line == "FORMAT=32-bit_rle_rgbe") {
  78357. findFormat = true;
  78358. }
  78359. else if (line.length == 0) {
  78360. endOfHeader = true;
  78361. }
  78362. } while (!endOfHeader);
  78363. if (!findFormat) {
  78364. throw "HDR Bad header format, unsupported FORMAT";
  78365. }
  78366. lineIndex += (line.length + 1);
  78367. line = this.readStringLine(uint8array, lineIndex);
  78368. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  78369. var match = sizeRegexp.exec(line);
  78370. // TODO. Support +Y and -X if needed.
  78371. if (!match || match.length < 3) {
  78372. throw "HDR Bad header format, no size";
  78373. }
  78374. width = parseInt(match[2]);
  78375. height = parseInt(match[1]);
  78376. if (width < 8 || width > 0x7fff) {
  78377. throw "HDR Bad header format, unsupported size";
  78378. }
  78379. lineIndex += (line.length + 1);
  78380. return {
  78381. height: height,
  78382. width: width,
  78383. dataPosition: lineIndex
  78384. };
  78385. };
  78386. /**
  78387. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  78388. * This RGBE texture needs to store the information as a panorama.
  78389. *
  78390. * More information on this format are available here:
  78391. * https://en.wikipedia.org/wiki/RGBE_image_format
  78392. *
  78393. * @param buffer The binary file stored in an array buffer.
  78394. * @param size The expected size of the extracted cubemap.
  78395. * @return The Cube Map information.
  78396. */
  78397. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  78398. var uint8array = new Uint8Array(buffer);
  78399. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  78400. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78401. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  78402. return cubeMapData;
  78403. };
  78404. /**
  78405. * Returns the pixels data extracted from an RGBE texture.
  78406. * This pixels will be stored left to right up to down in the R G B order in one array.
  78407. *
  78408. * More information on this format are available here:
  78409. * https://en.wikipedia.org/wiki/RGBE_image_format
  78410. *
  78411. * @param uint8array The binary file stored in an array buffer.
  78412. * @param hdrInfo The header information of the file.
  78413. * @return The pixels data in RGB right to left up to down order.
  78414. */
  78415. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  78416. // Keep for multi format supports.
  78417. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78418. };
  78419. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  78420. var num_scanlines = hdrInfo.height;
  78421. var scanline_width = hdrInfo.width;
  78422. var a, b, c, d, count;
  78423. var dataIndex = hdrInfo.dataPosition;
  78424. var index = 0, endIndex = 0, i = 0;
  78425. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  78426. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  78427. // 3 channels of 4 bytes per pixel in float.
  78428. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  78429. var resultArray = new Float32Array(resultBuffer);
  78430. // read in each successive scanline
  78431. while (num_scanlines > 0) {
  78432. a = uint8array[dataIndex++];
  78433. b = uint8array[dataIndex++];
  78434. c = uint8array[dataIndex++];
  78435. d = uint8array[dataIndex++];
  78436. if (a != 2 || b != 2 || (c & 0x80)) {
  78437. // this file is not run length encoded
  78438. throw "HDR Bad header format, not RLE";
  78439. }
  78440. if (((c << 8) | d) != scanline_width) {
  78441. throw "HDR Bad header format, wrong scan line width";
  78442. }
  78443. index = 0;
  78444. // read each of the four channels for the scanline into the buffer
  78445. for (i = 0; i < 4; i++) {
  78446. endIndex = (i + 1) * scanline_width;
  78447. while (index < endIndex) {
  78448. a = uint8array[dataIndex++];
  78449. b = uint8array[dataIndex++];
  78450. if (a > 128) {
  78451. // a run of the same value
  78452. count = a - 128;
  78453. if ((count == 0) || (count > endIndex - index)) {
  78454. throw "HDR Bad Format, bad scanline data (run)";
  78455. }
  78456. while (count-- > 0) {
  78457. scanLineArray[index++] = b;
  78458. }
  78459. }
  78460. else {
  78461. // a non-run
  78462. count = a;
  78463. if ((count == 0) || (count > endIndex - index)) {
  78464. throw "HDR Bad Format, bad scanline data (non-run)";
  78465. }
  78466. scanLineArray[index++] = b;
  78467. if (--count > 0) {
  78468. for (var j = 0; j < count; j++) {
  78469. scanLineArray[index++] = uint8array[dataIndex++];
  78470. }
  78471. }
  78472. }
  78473. }
  78474. }
  78475. // now convert data from buffer into floats
  78476. for (i = 0; i < scanline_width; i++) {
  78477. a = scanLineArray[i];
  78478. b = scanLineArray[i + scanline_width];
  78479. c = scanLineArray[i + 2 * scanline_width];
  78480. d = scanLineArray[i + 3 * scanline_width];
  78481. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  78482. }
  78483. num_scanlines--;
  78484. }
  78485. return resultArray;
  78486. };
  78487. return HDRTools;
  78488. }());
  78489. BABYLON.HDRTools = HDRTools;
  78490. })(BABYLON || (BABYLON = {}));
  78491. //# sourceMappingURL=babylon.hdr.js.map
  78492. "use strict";
  78493. var BABYLON;
  78494. (function (BABYLON) {
  78495. /**
  78496. * This represents a texture coming from an HDR input.
  78497. *
  78498. * The only supported format is currently panorama picture stored in RGBE format.
  78499. * Example of such files can be found on HDRLib: http://hdrlib.com/
  78500. */
  78501. var HDRCubeTexture = /** @class */ (function (_super) {
  78502. __extends(HDRCubeTexture, _super);
  78503. /**
  78504. * Instantiates an HDRTexture from the following parameters.
  78505. *
  78506. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  78507. * @param scene The scene the texture will be used in
  78508. * @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.
  78509. * @param noMipmap Forces to not generate the mipmap if true
  78510. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  78511. * @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)
  78512. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  78513. */
  78514. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  78515. if (noMipmap === void 0) { noMipmap = false; }
  78516. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78517. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78518. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78519. if (onLoad === void 0) { onLoad = null; }
  78520. if (onError === void 0) { onError = null; }
  78521. var _this = _super.call(this, scene) || this;
  78522. _this._useInGammaSpace = false;
  78523. _this._generateHarmonics = true;
  78524. _this._isBABYLONPreprocessed = false;
  78525. _this._onLoad = null;
  78526. _this._onError = null;
  78527. /**
  78528. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  78529. */
  78530. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  78531. /**
  78532. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  78533. * This is usefull at run time to apply the good shader.
  78534. */
  78535. _this.isPMREM = false;
  78536. _this._isBlocking = true;
  78537. _this._rotationY = 0;
  78538. /**
  78539. * Gets or sets the center of the bounding box associated with the cube texture
  78540. * It must define where the camera used to render the texture was set
  78541. */
  78542. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  78543. if (!url) {
  78544. return _this;
  78545. }
  78546. _this.name = url;
  78547. _this.url = url;
  78548. _this.hasAlpha = false;
  78549. _this.isCube = true;
  78550. _this._textureMatrix = BABYLON.Matrix.Identity();
  78551. _this._onLoad = onLoad;
  78552. _this._onError = onError;
  78553. _this.gammaSpace = false;
  78554. var caps = scene.getEngine().getCaps();
  78555. if (size) {
  78556. _this._isBABYLONPreprocessed = false;
  78557. _this._noMipmap = noMipmap;
  78558. _this._size = size;
  78559. _this._useInGammaSpace = useInGammaSpace;
  78560. _this._usePMREMGenerator = usePMREMGenerator &&
  78561. caps.textureLOD &&
  78562. caps.textureFloat &&
  78563. !_this._useInGammaSpace;
  78564. }
  78565. else {
  78566. _this._isBABYLONPreprocessed = true;
  78567. _this._noMipmap = false;
  78568. _this._useInGammaSpace = false;
  78569. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  78570. !_this._useInGammaSpace;
  78571. }
  78572. _this.isPMREM = _this._usePMREMGenerator;
  78573. _this._texture = _this._getFromCache(url, _this._noMipmap);
  78574. if (!_this._texture) {
  78575. if (!scene.useDelayedTextureLoading) {
  78576. _this.loadTexture();
  78577. }
  78578. else {
  78579. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78580. }
  78581. }
  78582. return _this;
  78583. }
  78584. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  78585. /**
  78586. * Gets wether or not the texture is blocking during loading.
  78587. */
  78588. get: function () {
  78589. return this._isBlocking;
  78590. },
  78591. /**
  78592. * Sets wether or not the texture is blocking during loading.
  78593. */
  78594. set: function (value) {
  78595. this._isBlocking = value;
  78596. },
  78597. enumerable: true,
  78598. configurable: true
  78599. });
  78600. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  78601. /**
  78602. * Gets texture matrix rotation angle around Y axis radians.
  78603. */
  78604. get: function () {
  78605. return this._rotationY;
  78606. },
  78607. /**
  78608. * Sets texture matrix rotation angle around Y axis in radians.
  78609. */
  78610. set: function (value) {
  78611. this._rotationY = value;
  78612. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  78613. },
  78614. enumerable: true,
  78615. configurable: true
  78616. });
  78617. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  78618. get: function () {
  78619. return this._boundingBoxSize;
  78620. },
  78621. /**
  78622. * Gets or sets the size of the bounding box associated with the cube texture
  78623. * When defined, the cubemap will switch to local mode
  78624. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  78625. * @example https://www.babylonjs-playground.com/#RNASML
  78626. */
  78627. set: function (value) {
  78628. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  78629. return;
  78630. }
  78631. this._boundingBoxSize = value;
  78632. var scene = this.getScene();
  78633. if (scene) {
  78634. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  78635. }
  78636. },
  78637. enumerable: true,
  78638. configurable: true
  78639. });
  78640. /**
  78641. * Occurs when the file is a preprocessed .babylon.hdr file.
  78642. */
  78643. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  78644. var _this = this;
  78645. var mipLevels = 0;
  78646. var floatArrayView = null;
  78647. var scene = this.getScene();
  78648. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  78649. var mips = new Array();
  78650. if (!floatArrayView) {
  78651. return mips;
  78652. }
  78653. var startIndex = 30;
  78654. for (var level = 0; level < mipLevels; level++) {
  78655. mips.push([]);
  78656. // Fill each pixel of the mip level.
  78657. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  78658. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78659. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  78660. mips[level].push(faceData);
  78661. startIndex += faceSize;
  78662. }
  78663. }
  78664. return mips;
  78665. } : null;
  78666. var callback = function (buffer) {
  78667. var scene = _this.getScene();
  78668. if (!scene) {
  78669. return null;
  78670. }
  78671. // Create Native Array Views
  78672. var intArrayView = new Int32Array(buffer);
  78673. floatArrayView = new Float32Array(buffer);
  78674. // Fill header.
  78675. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  78676. _this._size = intArrayView[1]; // CubeMap max mip face size.
  78677. // Update Texture Information.
  78678. if (!_this._texture) {
  78679. return null;
  78680. }
  78681. _this._texture.updateSize(_this._size, _this._size);
  78682. // Fill polynomial information.
  78683. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  78684. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  78685. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  78686. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  78687. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  78688. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  78689. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  78690. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  78691. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  78692. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  78693. _this.sphericalPolynomial = sphericalPolynomial;
  78694. // Fill pixel data.
  78695. mipLevels = intArrayView[29]; // Number of mip levels.
  78696. var startIndex = 30;
  78697. var data = [];
  78698. var faceSize = Math.pow(_this._size, 2) * 3;
  78699. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78700. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  78701. startIndex += faceSize;
  78702. }
  78703. var results = [];
  78704. var byteArray = null;
  78705. // Push each faces.
  78706. for (var k = 0; k < 6; k++) {
  78707. var dataFace = null;
  78708. // To be deprecated.
  78709. if (version === 1) {
  78710. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  78711. dataFace = data[j];
  78712. }
  78713. // If special cases.
  78714. if (!mipmapGenerator && dataFace) {
  78715. if (!scene.getEngine().getCaps().textureFloat) {
  78716. // 3 channels of 1 bytes per pixel in bytes.
  78717. var byteBuffer = new ArrayBuffer(faceSize);
  78718. byteArray = new Uint8Array(byteBuffer);
  78719. }
  78720. for (var i = 0; i < _this._size * _this._size; i++) {
  78721. // Put in gamma space if requested.
  78722. if (_this._useInGammaSpace) {
  78723. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78724. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78725. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78726. }
  78727. // Convert to int texture for fallback.
  78728. if (byteArray) {
  78729. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78730. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78731. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78732. // May use luminance instead if the result is not accurate.
  78733. var max = Math.max(Math.max(r, g), b);
  78734. if (max > 255) {
  78735. var scale = 255 / max;
  78736. r *= scale;
  78737. g *= scale;
  78738. b *= scale;
  78739. }
  78740. byteArray[(i * 3) + 0] = r;
  78741. byteArray[(i * 3) + 1] = g;
  78742. byteArray[(i * 3) + 2] = b;
  78743. }
  78744. }
  78745. }
  78746. // Fill the array accordingly.
  78747. if (byteArray) {
  78748. results.push(byteArray);
  78749. }
  78750. else {
  78751. results.push(dataFace);
  78752. }
  78753. }
  78754. return results;
  78755. };
  78756. if (scene) {
  78757. 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);
  78758. }
  78759. };
  78760. /**
  78761. * Occurs when the file is raw .hdr file.
  78762. */
  78763. HDRCubeTexture.prototype.loadHDRTexture = function () {
  78764. var _this = this;
  78765. var callback = function (buffer) {
  78766. var scene = _this.getScene();
  78767. if (!scene) {
  78768. return null;
  78769. }
  78770. // Extract the raw linear data.
  78771. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  78772. // Generate harmonics if needed.
  78773. if (_this._generateHarmonics) {
  78774. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  78775. _this.sphericalPolynomial = sphericalPolynomial;
  78776. }
  78777. var results = [];
  78778. var byteArray = null;
  78779. // Push each faces.
  78780. for (var j = 0; j < 6; j++) {
  78781. // Create uintarray fallback.
  78782. if (!scene.getEngine().getCaps().textureFloat) {
  78783. // 3 channels of 1 bytes per pixel in bytes.
  78784. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  78785. byteArray = new Uint8Array(byteBuffer);
  78786. }
  78787. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  78788. // If special cases.
  78789. if (_this._useInGammaSpace || byteArray) {
  78790. for (var i = 0; i < _this._size * _this._size; i++) {
  78791. // Put in gamma space if requested.
  78792. if (_this._useInGammaSpace) {
  78793. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78794. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78795. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78796. }
  78797. // Convert to int texture for fallback.
  78798. if (byteArray) {
  78799. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78800. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78801. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78802. // May use luminance instead if the result is not accurate.
  78803. var max = Math.max(Math.max(r, g), b);
  78804. if (max > 255) {
  78805. var scale = 255 / max;
  78806. r *= scale;
  78807. g *= scale;
  78808. b *= scale;
  78809. }
  78810. byteArray[(i * 3) + 0] = r;
  78811. byteArray[(i * 3) + 1] = g;
  78812. byteArray[(i * 3) + 2] = b;
  78813. }
  78814. }
  78815. }
  78816. if (byteArray) {
  78817. results.push(byteArray);
  78818. }
  78819. else {
  78820. results.push(dataFace);
  78821. }
  78822. }
  78823. return results;
  78824. };
  78825. var mipmapGenerator = null;
  78826. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  78827. // if (!this._noMipmap &&
  78828. // this._usePMREMGenerator) {
  78829. // mipmapGenerator = (data: ArrayBufferView[]) => {
  78830. // // Custom setup of the generator matching with the PBR shader values.
  78831. // var generator = new BABYLON.PMREMGenerator(data,
  78832. // this._size,
  78833. // this._size,
  78834. // 0,
  78835. // 3,
  78836. // this.getScene().getEngine().getCaps().textureFloat,
  78837. // 2048,
  78838. // 0.25,
  78839. // false,
  78840. // true);
  78841. // return generator.filterCubeMap();
  78842. // };
  78843. // }
  78844. var scene = this.getScene();
  78845. if (scene) {
  78846. 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);
  78847. }
  78848. };
  78849. /**
  78850. * Starts the loading process of the texture.
  78851. */
  78852. HDRCubeTexture.prototype.loadTexture = function () {
  78853. if (this._isBABYLONPreprocessed) {
  78854. this.loadBabylonTexture();
  78855. }
  78856. else {
  78857. this.loadHDRTexture();
  78858. }
  78859. };
  78860. HDRCubeTexture.prototype.clone = function () {
  78861. var scene = this.getScene();
  78862. if (!scene) {
  78863. return this;
  78864. }
  78865. var size = (this._isBABYLONPreprocessed ? null : this._size);
  78866. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  78867. // Base texture
  78868. newTexture.level = this.level;
  78869. newTexture.wrapU = this.wrapU;
  78870. newTexture.wrapV = this.wrapV;
  78871. newTexture.coordinatesIndex = this.coordinatesIndex;
  78872. newTexture.coordinatesMode = this.coordinatesMode;
  78873. return newTexture;
  78874. };
  78875. // Methods
  78876. HDRCubeTexture.prototype.delayLoad = function () {
  78877. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78878. return;
  78879. }
  78880. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78881. this._texture = this._getFromCache(this.url, this._noMipmap);
  78882. if (!this._texture) {
  78883. this.loadTexture();
  78884. }
  78885. };
  78886. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  78887. return this._textureMatrix;
  78888. };
  78889. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  78890. this._textureMatrix = value;
  78891. };
  78892. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78893. var texture = null;
  78894. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78895. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  78896. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  78897. texture.name = parsedTexture.name;
  78898. texture.hasAlpha = parsedTexture.hasAlpha;
  78899. texture.level = parsedTexture.level;
  78900. texture.coordinatesMode = parsedTexture.coordinatesMode;
  78901. texture.isBlocking = parsedTexture.isBlocking;
  78902. }
  78903. if (texture) {
  78904. if (parsedTexture.boundingBoxPosition) {
  78905. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  78906. }
  78907. if (parsedTexture.boundingBoxSize) {
  78908. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  78909. }
  78910. if (parsedTexture.rotationY) {
  78911. texture.rotationY = parsedTexture.rotationY;
  78912. }
  78913. }
  78914. return texture;
  78915. };
  78916. HDRCubeTexture.prototype.serialize = function () {
  78917. if (!this.name) {
  78918. return null;
  78919. }
  78920. var serializationObject = {};
  78921. serializationObject.name = this.name;
  78922. serializationObject.hasAlpha = this.hasAlpha;
  78923. serializationObject.isCube = true;
  78924. serializationObject.level = this.level;
  78925. serializationObject.size = this._size;
  78926. serializationObject.coordinatesMode = this.coordinatesMode;
  78927. serializationObject.useInGammaSpace = this._useInGammaSpace;
  78928. serializationObject.generateHarmonics = this._generateHarmonics;
  78929. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  78930. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  78931. serializationObject.customType = "BABYLON.HDRCubeTexture";
  78932. serializationObject.noMipmap = this._noMipmap;
  78933. serializationObject.isBlocking = this._isBlocking;
  78934. serializationObject.rotationY = this._rotationY;
  78935. return serializationObject;
  78936. };
  78937. /**
  78938. * Saves as a file the data contained in the texture in a binary format.
  78939. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78940. * as the spherical used in the lighting.
  78941. * @param url The HDR file url.
  78942. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78943. * @param onError Method called if any error happens during download.
  78944. * @return The packed binary data.
  78945. */
  78946. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  78947. if (onError === void 0) { onError = null; }
  78948. var callback = function (buffer) {
  78949. var data = new Blob([buffer], { type: 'application/octet-stream' });
  78950. // Returns a URL you can use as a href.
  78951. var objUrl = window.URL.createObjectURL(data);
  78952. // Simulates a link to it and click to dowload.
  78953. var a = document.createElement("a");
  78954. document.body.appendChild(a);
  78955. a.style.display = "none";
  78956. a.href = objUrl;
  78957. a.download = "envmap.babylon.hdr";
  78958. a.click();
  78959. };
  78960. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  78961. };
  78962. /**
  78963. * Serializes the data contained in the texture in a binary format.
  78964. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78965. * as the spherical used in the lighting.
  78966. * @param url The HDR file url.
  78967. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78968. * @param onError Method called if any error happens during download.
  78969. * @return The packed binary data.
  78970. */
  78971. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  78972. if (onError === void 0) { onError = null; }
  78973. // Needs the url tho create the texture.
  78974. if (!url) {
  78975. return;
  78976. }
  78977. // Check Power of two size.
  78978. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  78979. return;
  78980. }
  78981. // Coming Back in 3.x.
  78982. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  78983. };
  78984. HDRCubeTexture._facesMapping = [
  78985. "right",
  78986. "left",
  78987. "up",
  78988. "down",
  78989. "front",
  78990. "back"
  78991. ];
  78992. return HDRCubeTexture;
  78993. }(BABYLON.BaseTexture));
  78994. BABYLON.HDRCubeTexture = HDRCubeTexture;
  78995. })(BABYLON || (BABYLON = {}));
  78996. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  78997. "use strict";
  78998. var BABYLON;
  78999. (function (BABYLON) {
  79000. var IndexedVector2 = /** @class */ (function (_super) {
  79001. __extends(IndexedVector2, _super);
  79002. function IndexedVector2(original, index) {
  79003. var _this = _super.call(this, original.x, original.y) || this;
  79004. _this.index = index;
  79005. return _this;
  79006. }
  79007. return IndexedVector2;
  79008. }(BABYLON.Vector2));
  79009. var PolygonPoints = /** @class */ (function () {
  79010. function PolygonPoints() {
  79011. this.elements = new Array();
  79012. }
  79013. PolygonPoints.prototype.add = function (originalPoints) {
  79014. var _this = this;
  79015. var result = new Array();
  79016. originalPoints.forEach(function (point) {
  79017. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  79018. var newPoint = new IndexedVector2(point, _this.elements.length);
  79019. result.push(newPoint);
  79020. _this.elements.push(newPoint);
  79021. }
  79022. });
  79023. return result;
  79024. };
  79025. PolygonPoints.prototype.computeBounds = function () {
  79026. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79027. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79028. this.elements.forEach(function (point) {
  79029. // x
  79030. if (point.x < lmin.x) {
  79031. lmin.x = point.x;
  79032. }
  79033. else if (point.x > lmax.x) {
  79034. lmax.x = point.x;
  79035. }
  79036. // y
  79037. if (point.y < lmin.y) {
  79038. lmin.y = point.y;
  79039. }
  79040. else if (point.y > lmax.y) {
  79041. lmax.y = point.y;
  79042. }
  79043. });
  79044. return {
  79045. min: lmin,
  79046. max: lmax,
  79047. width: lmax.x - lmin.x,
  79048. height: lmax.y - lmin.y
  79049. };
  79050. };
  79051. return PolygonPoints;
  79052. }());
  79053. var Polygon = /** @class */ (function () {
  79054. function Polygon() {
  79055. }
  79056. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  79057. return [
  79058. new BABYLON.Vector2(xmin, ymin),
  79059. new BABYLON.Vector2(xmax, ymin),
  79060. new BABYLON.Vector2(xmax, ymax),
  79061. new BABYLON.Vector2(xmin, ymax)
  79062. ];
  79063. };
  79064. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  79065. if (cx === void 0) { cx = 0; }
  79066. if (cy === void 0) { cy = 0; }
  79067. if (numberOfSides === void 0) { numberOfSides = 32; }
  79068. var result = new Array();
  79069. var angle = 0;
  79070. var increment = (Math.PI * 2) / numberOfSides;
  79071. for (var i = 0; i < numberOfSides; i++) {
  79072. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  79073. angle -= increment;
  79074. }
  79075. return result;
  79076. };
  79077. Polygon.Parse = function (input) {
  79078. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  79079. var i, result = [];
  79080. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  79081. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  79082. }
  79083. return result;
  79084. };
  79085. Polygon.StartingAt = function (x, y) {
  79086. return BABYLON.Path2.StartingAt(x, y);
  79087. };
  79088. return Polygon;
  79089. }());
  79090. BABYLON.Polygon = Polygon;
  79091. var PolygonMeshBuilder = /** @class */ (function () {
  79092. function PolygonMeshBuilder(name, contours, scene) {
  79093. this._points = new PolygonPoints();
  79094. this._outlinepoints = new PolygonPoints();
  79095. this._holes = new Array();
  79096. this._epoints = new Array();
  79097. this._eholes = new Array();
  79098. this._name = name;
  79099. this._scene = scene;
  79100. var points;
  79101. if (contours instanceof BABYLON.Path2) {
  79102. points = contours.getPoints();
  79103. }
  79104. else {
  79105. points = contours;
  79106. }
  79107. this._addToepoint(points);
  79108. this._points.add(points);
  79109. this._outlinepoints.add(points);
  79110. if (typeof earcut === 'undefined') {
  79111. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  79112. }
  79113. }
  79114. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  79115. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  79116. var p = points_1[_i];
  79117. this._epoints.push(p.x, p.y);
  79118. }
  79119. };
  79120. PolygonMeshBuilder.prototype.addHole = function (hole) {
  79121. this._points.add(hole);
  79122. var holepoints = new PolygonPoints();
  79123. holepoints.add(hole);
  79124. this._holes.push(holepoints);
  79125. this._eholes.push(this._epoints.length / 2);
  79126. this._addToepoint(hole);
  79127. return this;
  79128. };
  79129. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  79130. var _this = this;
  79131. if (updatable === void 0) { updatable = false; }
  79132. if (depth === void 0) { depth = 0; }
  79133. var result = new BABYLON.Mesh(this._name, this._scene);
  79134. var normals = new Array();
  79135. var positions = new Array();
  79136. var uvs = new Array();
  79137. var bounds = this._points.computeBounds();
  79138. this._points.elements.forEach(function (p) {
  79139. normals.push(0, 1.0, 0);
  79140. positions.push(p.x, 0, p.y);
  79141. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  79142. });
  79143. var indices = new Array();
  79144. var res = earcut(this._epoints, this._eholes, 2);
  79145. for (var i = 0; i < res.length; i++) {
  79146. indices.push(res[i]);
  79147. }
  79148. if (depth > 0) {
  79149. var positionscount = (positions.length / 3); //get the current pointcount
  79150. this._points.elements.forEach(function (p) {
  79151. normals.push(0, -1.0, 0);
  79152. positions.push(p.x, -depth, p.y);
  79153. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  79154. });
  79155. var totalCount = indices.length;
  79156. for (var i = 0; i < totalCount; i += 3) {
  79157. var i0 = indices[i + 0];
  79158. var i1 = indices[i + 1];
  79159. var i2 = indices[i + 2];
  79160. indices.push(i2 + positionscount);
  79161. indices.push(i1 + positionscount);
  79162. indices.push(i0 + positionscount);
  79163. }
  79164. //Add the sides
  79165. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  79166. this._holes.forEach(function (hole) {
  79167. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  79168. });
  79169. }
  79170. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  79171. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  79172. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  79173. result.setIndices(indices);
  79174. return result;
  79175. };
  79176. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  79177. var StartIndex = positions.length / 3;
  79178. var ulength = 0;
  79179. for (var i = 0; i < points.elements.length; i++) {
  79180. var p = points.elements[i];
  79181. var p1;
  79182. if ((i + 1) > points.elements.length - 1) {
  79183. p1 = points.elements[0];
  79184. }
  79185. else {
  79186. p1 = points.elements[i + 1];
  79187. }
  79188. positions.push(p.x, 0, p.y);
  79189. positions.push(p.x, -depth, p.y);
  79190. positions.push(p1.x, 0, p1.y);
  79191. positions.push(p1.x, -depth, p1.y);
  79192. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  79193. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  79194. var v3 = v2.subtract(v1);
  79195. var v4 = new BABYLON.Vector3(0, 1, 0);
  79196. var vn = BABYLON.Vector3.Cross(v3, v4);
  79197. vn = vn.normalize();
  79198. uvs.push(ulength / bounds.width, 0);
  79199. uvs.push(ulength / bounds.width, 1);
  79200. ulength += v3.length();
  79201. uvs.push((ulength / bounds.width), 0);
  79202. uvs.push((ulength / bounds.width), 1);
  79203. if (!flip) {
  79204. normals.push(-vn.x, -vn.y, -vn.z);
  79205. normals.push(-vn.x, -vn.y, -vn.z);
  79206. normals.push(-vn.x, -vn.y, -vn.z);
  79207. normals.push(-vn.x, -vn.y, -vn.z);
  79208. indices.push(StartIndex);
  79209. indices.push(StartIndex + 1);
  79210. indices.push(StartIndex + 2);
  79211. indices.push(StartIndex + 1);
  79212. indices.push(StartIndex + 3);
  79213. indices.push(StartIndex + 2);
  79214. }
  79215. else {
  79216. normals.push(vn.x, vn.y, vn.z);
  79217. normals.push(vn.x, vn.y, vn.z);
  79218. normals.push(vn.x, vn.y, vn.z);
  79219. normals.push(vn.x, vn.y, vn.z);
  79220. indices.push(StartIndex);
  79221. indices.push(StartIndex + 2);
  79222. indices.push(StartIndex + 1);
  79223. indices.push(StartIndex + 1);
  79224. indices.push(StartIndex + 2);
  79225. indices.push(StartIndex + 3);
  79226. }
  79227. StartIndex += 4;
  79228. }
  79229. ;
  79230. };
  79231. return PolygonMeshBuilder;
  79232. }());
  79233. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  79234. })(BABYLON || (BABYLON = {}));
  79235. //# sourceMappingURL=babylon.polygonMesh.js.map
  79236. "use strict";
  79237. var BABYLON;
  79238. (function (BABYLON) {
  79239. // Unique ID when we import meshes from Babylon to CSG
  79240. var currentCSGMeshId = 0;
  79241. // # class Vertex
  79242. // Represents a vertex of a polygon. Use your own vertex class instead of this
  79243. // one to provide additional features like texture coordinates and vertex
  79244. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  79245. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  79246. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  79247. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  79248. // is not used anywhere else.
  79249. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  79250. var Vertex = /** @class */ (function () {
  79251. function Vertex(pos, normal, uv) {
  79252. this.pos = pos;
  79253. this.normal = normal;
  79254. this.uv = uv;
  79255. }
  79256. Vertex.prototype.clone = function () {
  79257. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  79258. };
  79259. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  79260. // orientation of a polygon is flipped.
  79261. Vertex.prototype.flip = function () {
  79262. this.normal = this.normal.scale(-1);
  79263. };
  79264. // Create a new vertex between this vertex and `other` by linearly
  79265. // interpolating all properties using a parameter of `t`. Subclasses should
  79266. // override this to interpolate additional properties.
  79267. Vertex.prototype.interpolate = function (other, t) {
  79268. 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));
  79269. };
  79270. return Vertex;
  79271. }());
  79272. // # class Plane
  79273. // Represents a plane in 3D space.
  79274. var Plane = /** @class */ (function () {
  79275. function Plane(normal, w) {
  79276. this.normal = normal;
  79277. this.w = w;
  79278. }
  79279. Plane.FromPoints = function (a, b, c) {
  79280. var v0 = c.subtract(a);
  79281. var v1 = b.subtract(a);
  79282. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  79283. return null;
  79284. }
  79285. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  79286. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  79287. };
  79288. Plane.prototype.clone = function () {
  79289. return new Plane(this.normal.clone(), this.w);
  79290. };
  79291. Plane.prototype.flip = function () {
  79292. this.normal.scaleInPlace(-1);
  79293. this.w = -this.w;
  79294. };
  79295. // Split `polygon` by this plane if needed, then put the polygon or polygon
  79296. // fragments in the appropriate lists. Coplanar polygons go into either
  79297. // `coplanarFront` or `coplanarBack` depending on their orientation with
  79298. // respect to this plane. Polygons in front or in back of this plane go into
  79299. // either `front` or `back`.
  79300. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  79301. var COPLANAR = 0;
  79302. var FRONT = 1;
  79303. var BACK = 2;
  79304. var SPANNING = 3;
  79305. // Classify each point as well as the entire polygon into one of the above
  79306. // four classes.
  79307. var polygonType = 0;
  79308. var types = [];
  79309. var i;
  79310. var t;
  79311. for (i = 0; i < polygon.vertices.length; i++) {
  79312. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  79313. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  79314. polygonType |= type;
  79315. types.push(type);
  79316. }
  79317. // Put the polygon in the correct list, splitting it when necessary.
  79318. switch (polygonType) {
  79319. case COPLANAR:
  79320. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  79321. break;
  79322. case FRONT:
  79323. front.push(polygon);
  79324. break;
  79325. case BACK:
  79326. back.push(polygon);
  79327. break;
  79328. case SPANNING:
  79329. var f = [], b = [];
  79330. for (i = 0; i < polygon.vertices.length; i++) {
  79331. var j = (i + 1) % polygon.vertices.length;
  79332. var ti = types[i], tj = types[j];
  79333. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  79334. if (ti !== BACK)
  79335. f.push(vi);
  79336. if (ti !== FRONT)
  79337. b.push(ti !== BACK ? vi.clone() : vi);
  79338. if ((ti | tj) === SPANNING) {
  79339. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  79340. var v = vi.interpolate(vj, t);
  79341. f.push(v);
  79342. b.push(v.clone());
  79343. }
  79344. }
  79345. var poly;
  79346. if (f.length >= 3) {
  79347. poly = new Polygon(f, polygon.shared);
  79348. if (poly.plane)
  79349. front.push(poly);
  79350. }
  79351. if (b.length >= 3) {
  79352. poly = new Polygon(b, polygon.shared);
  79353. if (poly.plane)
  79354. back.push(poly);
  79355. }
  79356. break;
  79357. }
  79358. };
  79359. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  79360. // point is on the plane.
  79361. Plane.EPSILON = 1e-5;
  79362. return Plane;
  79363. }());
  79364. // # class Polygon
  79365. // Represents a convex polygon. The vertices used to initialize a polygon must
  79366. // be coplanar and form a convex loop.
  79367. //
  79368. // Each convex polygon has a `shared` property, which is shared between all
  79369. // polygons that are clones of each other or were split from the same polygon.
  79370. // This can be used to define per-polygon properties (such as surface color).
  79371. var Polygon = /** @class */ (function () {
  79372. function Polygon(vertices, shared) {
  79373. this.vertices = vertices;
  79374. this.shared = shared;
  79375. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  79376. }
  79377. Polygon.prototype.clone = function () {
  79378. var vertices = this.vertices.map(function (v) { return v.clone(); });
  79379. return new Polygon(vertices, this.shared);
  79380. };
  79381. Polygon.prototype.flip = function () {
  79382. this.vertices.reverse().map(function (v) { v.flip(); });
  79383. this.plane.flip();
  79384. };
  79385. return Polygon;
  79386. }());
  79387. // # class Node
  79388. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  79389. // by picking a polygon to split along. That polygon (and all other coplanar
  79390. // polygons) are added directly to that node and the other polygons are added to
  79391. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  79392. // no distinction between internal and leaf nodes.
  79393. var Node = /** @class */ (function () {
  79394. function Node(polygons) {
  79395. this.plane = null;
  79396. this.front = null;
  79397. this.back = null;
  79398. this.polygons = new Array();
  79399. if (polygons) {
  79400. this.build(polygons);
  79401. }
  79402. }
  79403. Node.prototype.clone = function () {
  79404. var node = new Node();
  79405. node.plane = this.plane && this.plane.clone();
  79406. node.front = this.front && this.front.clone();
  79407. node.back = this.back && this.back.clone();
  79408. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  79409. return node;
  79410. };
  79411. // Convert solid space to empty space and empty space to solid space.
  79412. Node.prototype.invert = function () {
  79413. for (var i = 0; i < this.polygons.length; i++) {
  79414. this.polygons[i].flip();
  79415. }
  79416. if (this.plane) {
  79417. this.plane.flip();
  79418. }
  79419. if (this.front) {
  79420. this.front.invert();
  79421. }
  79422. if (this.back) {
  79423. this.back.invert();
  79424. }
  79425. var temp = this.front;
  79426. this.front = this.back;
  79427. this.back = temp;
  79428. };
  79429. // Recursively remove all polygons in `polygons` that are inside this BSP
  79430. // tree.
  79431. Node.prototype.clipPolygons = function (polygons) {
  79432. if (!this.plane)
  79433. return polygons.slice();
  79434. var front = new Array(), back = new Array();
  79435. for (var i = 0; i < polygons.length; i++) {
  79436. this.plane.splitPolygon(polygons[i], front, back, front, back);
  79437. }
  79438. if (this.front) {
  79439. front = this.front.clipPolygons(front);
  79440. }
  79441. if (this.back) {
  79442. back = this.back.clipPolygons(back);
  79443. }
  79444. else {
  79445. back = [];
  79446. }
  79447. return front.concat(back);
  79448. };
  79449. // Remove all polygons in this BSP tree that are inside the other BSP tree
  79450. // `bsp`.
  79451. Node.prototype.clipTo = function (bsp) {
  79452. this.polygons = bsp.clipPolygons(this.polygons);
  79453. if (this.front)
  79454. this.front.clipTo(bsp);
  79455. if (this.back)
  79456. this.back.clipTo(bsp);
  79457. };
  79458. // Return a list of all polygons in this BSP tree.
  79459. Node.prototype.allPolygons = function () {
  79460. var polygons = this.polygons.slice();
  79461. if (this.front)
  79462. polygons = polygons.concat(this.front.allPolygons());
  79463. if (this.back)
  79464. polygons = polygons.concat(this.back.allPolygons());
  79465. return polygons;
  79466. };
  79467. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  79468. // new polygons are filtered down to the bottom of the tree and become new
  79469. // nodes there. Each set of polygons is partitioned using the first polygon
  79470. // (no heuristic is used to pick a good split).
  79471. Node.prototype.build = function (polygons) {
  79472. if (!polygons.length)
  79473. return;
  79474. if (!this.plane)
  79475. this.plane = polygons[0].plane.clone();
  79476. var front = new Array(), back = new Array();
  79477. for (var i = 0; i < polygons.length; i++) {
  79478. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  79479. }
  79480. if (front.length) {
  79481. if (!this.front)
  79482. this.front = new Node();
  79483. this.front.build(front);
  79484. }
  79485. if (back.length) {
  79486. if (!this.back)
  79487. this.back = new Node();
  79488. this.back.build(back);
  79489. }
  79490. };
  79491. return Node;
  79492. }());
  79493. var CSG = /** @class */ (function () {
  79494. function CSG() {
  79495. this.polygons = new Array();
  79496. }
  79497. // Convert BABYLON.Mesh to BABYLON.CSG
  79498. CSG.FromMesh = function (mesh) {
  79499. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  79500. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  79501. if (mesh instanceof BABYLON.Mesh) {
  79502. mesh.computeWorldMatrix(true);
  79503. matrix = mesh.getWorldMatrix();
  79504. meshPosition = mesh.position.clone();
  79505. meshRotation = mesh.rotation.clone();
  79506. if (mesh.rotationQuaternion) {
  79507. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  79508. }
  79509. meshScaling = mesh.scaling.clone();
  79510. }
  79511. else {
  79512. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  79513. }
  79514. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  79515. var subMeshes = mesh.subMeshes;
  79516. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  79517. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  79518. vertices = [];
  79519. for (var j = 0; j < 3; j++) {
  79520. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  79521. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  79522. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  79523. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  79524. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  79525. vertex = new Vertex(position, normal, uv);
  79526. vertices.push(vertex);
  79527. }
  79528. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  79529. // To handle the case of degenerated triangle
  79530. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  79531. if (polygon.plane)
  79532. polygons.push(polygon);
  79533. }
  79534. }
  79535. var csg = CSG.FromPolygons(polygons);
  79536. csg.matrix = matrix;
  79537. csg.position = meshPosition;
  79538. csg.rotation = meshRotation;
  79539. csg.scaling = meshScaling;
  79540. csg.rotationQuaternion = meshRotationQuaternion;
  79541. currentCSGMeshId++;
  79542. return csg;
  79543. };
  79544. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  79545. CSG.FromPolygons = function (polygons) {
  79546. var csg = new CSG();
  79547. csg.polygons = polygons;
  79548. return csg;
  79549. };
  79550. CSG.prototype.clone = function () {
  79551. var csg = new CSG();
  79552. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  79553. csg.copyTransformAttributes(this);
  79554. return csg;
  79555. };
  79556. CSG.prototype.union = function (csg) {
  79557. var a = new Node(this.clone().polygons);
  79558. var b = new Node(csg.clone().polygons);
  79559. a.clipTo(b);
  79560. b.clipTo(a);
  79561. b.invert();
  79562. b.clipTo(a);
  79563. b.invert();
  79564. a.build(b.allPolygons());
  79565. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79566. };
  79567. CSG.prototype.unionInPlace = function (csg) {
  79568. var a = new Node(this.polygons);
  79569. var b = new Node(csg.polygons);
  79570. a.clipTo(b);
  79571. b.clipTo(a);
  79572. b.invert();
  79573. b.clipTo(a);
  79574. b.invert();
  79575. a.build(b.allPolygons());
  79576. this.polygons = a.allPolygons();
  79577. };
  79578. CSG.prototype.subtract = function (csg) {
  79579. var a = new Node(this.clone().polygons);
  79580. var b = new Node(csg.clone().polygons);
  79581. a.invert();
  79582. a.clipTo(b);
  79583. b.clipTo(a);
  79584. b.invert();
  79585. b.clipTo(a);
  79586. b.invert();
  79587. a.build(b.allPolygons());
  79588. a.invert();
  79589. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79590. };
  79591. CSG.prototype.subtractInPlace = function (csg) {
  79592. var a = new Node(this.polygons);
  79593. var b = new Node(csg.polygons);
  79594. a.invert();
  79595. a.clipTo(b);
  79596. b.clipTo(a);
  79597. b.invert();
  79598. b.clipTo(a);
  79599. b.invert();
  79600. a.build(b.allPolygons());
  79601. a.invert();
  79602. this.polygons = a.allPolygons();
  79603. };
  79604. CSG.prototype.intersect = function (csg) {
  79605. var a = new Node(this.clone().polygons);
  79606. var b = new Node(csg.clone().polygons);
  79607. a.invert();
  79608. b.clipTo(a);
  79609. b.invert();
  79610. a.clipTo(b);
  79611. b.clipTo(a);
  79612. a.build(b.allPolygons());
  79613. a.invert();
  79614. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79615. };
  79616. CSG.prototype.intersectInPlace = function (csg) {
  79617. var a = new Node(this.polygons);
  79618. var b = new Node(csg.polygons);
  79619. a.invert();
  79620. b.clipTo(a);
  79621. b.invert();
  79622. a.clipTo(b);
  79623. b.clipTo(a);
  79624. a.build(b.allPolygons());
  79625. a.invert();
  79626. this.polygons = a.allPolygons();
  79627. };
  79628. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  79629. // not modified.
  79630. CSG.prototype.inverse = function () {
  79631. var csg = this.clone();
  79632. csg.inverseInPlace();
  79633. return csg;
  79634. };
  79635. CSG.prototype.inverseInPlace = function () {
  79636. this.polygons.map(function (p) { p.flip(); });
  79637. };
  79638. // This is used to keep meshes transformations so they can be restored
  79639. // when we build back a Babylon Mesh
  79640. // NB : All CSG operations are performed in world coordinates
  79641. CSG.prototype.copyTransformAttributes = function (csg) {
  79642. this.matrix = csg.matrix;
  79643. this.position = csg.position;
  79644. this.rotation = csg.rotation;
  79645. this.scaling = csg.scaling;
  79646. this.rotationQuaternion = csg.rotationQuaternion;
  79647. return this;
  79648. };
  79649. // Build Raw mesh from CSG
  79650. // Coordinates here are in world space
  79651. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  79652. var matrix = this.matrix.clone();
  79653. matrix.invert();
  79654. 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;
  79655. if (keepSubMeshes) {
  79656. // Sort Polygons, since subMeshes are indices range
  79657. polygons.sort(function (a, b) {
  79658. if (a.shared.meshId === b.shared.meshId) {
  79659. return a.shared.subMeshId - b.shared.subMeshId;
  79660. }
  79661. else {
  79662. return a.shared.meshId - b.shared.meshId;
  79663. }
  79664. });
  79665. }
  79666. for (var i = 0, il = polygons.length; i < il; i++) {
  79667. polygon = polygons[i];
  79668. // Building SubMeshes
  79669. if (!subMesh_dict[polygon.shared.meshId]) {
  79670. subMesh_dict[polygon.shared.meshId] = {};
  79671. }
  79672. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  79673. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  79674. indexStart: +Infinity,
  79675. indexEnd: -Infinity,
  79676. materialIndex: polygon.shared.materialIndex
  79677. };
  79678. }
  79679. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  79680. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  79681. polygonIndices[0] = 0;
  79682. polygonIndices[1] = j - 1;
  79683. polygonIndices[2] = j;
  79684. for (var k = 0; k < 3; k++) {
  79685. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  79686. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  79687. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  79688. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  79689. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  79690. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  79691. // Check if 2 points can be merged
  79692. if (!(typeof vertex_idx !== 'undefined' &&
  79693. normals[vertex_idx * 3] === localNormal.x &&
  79694. normals[vertex_idx * 3 + 1] === localNormal.y &&
  79695. normals[vertex_idx * 3 + 2] === localNormal.z &&
  79696. uvs[vertex_idx * 2] === uv.x &&
  79697. uvs[vertex_idx * 2 + 1] === uv.y)) {
  79698. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  79699. uvs.push(uv.x, uv.y);
  79700. normals.push(normal.x, normal.y, normal.z);
  79701. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  79702. }
  79703. indices.push(vertex_idx);
  79704. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  79705. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  79706. currentIndex++;
  79707. }
  79708. }
  79709. }
  79710. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  79711. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  79712. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  79713. mesh.setIndices(indices, null);
  79714. if (keepSubMeshes) {
  79715. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  79716. var materialIndexOffset = 0, materialMaxIndex;
  79717. mesh.subMeshes = new Array();
  79718. for (var m in subMesh_dict) {
  79719. materialMaxIndex = -1;
  79720. for (var sm in subMesh_dict[m]) {
  79721. subMesh_obj = subMesh_dict[m][sm];
  79722. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  79723. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  79724. }
  79725. materialIndexOffset += ++materialMaxIndex;
  79726. }
  79727. }
  79728. return mesh;
  79729. };
  79730. // Build Mesh from CSG taking material and transforms into account
  79731. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  79732. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  79733. mesh.material = material;
  79734. mesh.position.copyFrom(this.position);
  79735. mesh.rotation.copyFrom(this.rotation);
  79736. if (this.rotationQuaternion) {
  79737. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  79738. }
  79739. mesh.scaling.copyFrom(this.scaling);
  79740. mesh.computeWorldMatrix(true);
  79741. return mesh;
  79742. };
  79743. return CSG;
  79744. }());
  79745. BABYLON.CSG = CSG;
  79746. })(BABYLON || (BABYLON = {}));
  79747. //# sourceMappingURL=babylon.csg.js.map
  79748. "use strict";
  79749. var BABYLON;
  79750. (function (BABYLON) {
  79751. var LensFlare = /** @class */ (function () {
  79752. function LensFlare(size, position, color, imgUrl, system) {
  79753. this.size = size;
  79754. this.position = position;
  79755. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  79756. this.color = color || new BABYLON.Color3(1, 1, 1);
  79757. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  79758. this._system = system;
  79759. system.lensFlares.push(this);
  79760. }
  79761. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  79762. return new LensFlare(size, position, color, imgUrl, system);
  79763. };
  79764. LensFlare.prototype.dispose = function () {
  79765. if (this.texture) {
  79766. this.texture.dispose();
  79767. }
  79768. // Remove from scene
  79769. var index = this._system.lensFlares.indexOf(this);
  79770. this._system.lensFlares.splice(index, 1);
  79771. };
  79772. ;
  79773. return LensFlare;
  79774. }());
  79775. BABYLON.LensFlare = LensFlare;
  79776. })(BABYLON || (BABYLON = {}));
  79777. //# sourceMappingURL=babylon.lensFlare.js.map
  79778. "use strict";
  79779. var BABYLON;
  79780. (function (BABYLON) {
  79781. var LensFlareSystem = /** @class */ (function () {
  79782. function LensFlareSystem(name, emitter, scene) {
  79783. this.name = name;
  79784. this.lensFlares = new Array();
  79785. this.borderLimit = 300;
  79786. this.viewportBorder = 0;
  79787. this.layerMask = 0x0FFFFFFF;
  79788. this._vertexBuffers = {};
  79789. this._isEnabled = true;
  79790. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79791. this._emitter = emitter;
  79792. this.id = name;
  79793. scene.lensFlareSystems.push(this);
  79794. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  79795. var engine = scene.getEngine();
  79796. // VBO
  79797. var vertices = [];
  79798. vertices.push(1, 1);
  79799. vertices.push(-1, 1);
  79800. vertices.push(-1, -1);
  79801. vertices.push(1, -1);
  79802. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79803. // Indices
  79804. var indices = [];
  79805. indices.push(0);
  79806. indices.push(1);
  79807. indices.push(2);
  79808. indices.push(0);
  79809. indices.push(2);
  79810. indices.push(3);
  79811. this._indexBuffer = engine.createIndexBuffer(indices);
  79812. // Effects
  79813. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  79814. }
  79815. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  79816. get: function () {
  79817. return this._isEnabled;
  79818. },
  79819. set: function (value) {
  79820. this._isEnabled = value;
  79821. },
  79822. enumerable: true,
  79823. configurable: true
  79824. });
  79825. LensFlareSystem.prototype.getScene = function () {
  79826. return this._scene;
  79827. };
  79828. LensFlareSystem.prototype.getEmitter = function () {
  79829. return this._emitter;
  79830. };
  79831. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  79832. this._emitter = newEmitter;
  79833. };
  79834. LensFlareSystem.prototype.getEmitterPosition = function () {
  79835. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  79836. };
  79837. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  79838. var position = this.getEmitterPosition();
  79839. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  79840. this._positionX = position.x;
  79841. this._positionY = position.y;
  79842. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  79843. if (this.viewportBorder > 0) {
  79844. globalViewport.x -= this.viewportBorder;
  79845. globalViewport.y -= this.viewportBorder;
  79846. globalViewport.width += this.viewportBorder * 2;
  79847. globalViewport.height += this.viewportBorder * 2;
  79848. position.x += this.viewportBorder;
  79849. position.y += this.viewportBorder;
  79850. this._positionX += this.viewportBorder;
  79851. this._positionY += this.viewportBorder;
  79852. }
  79853. if (position.z > 0) {
  79854. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  79855. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  79856. return true;
  79857. }
  79858. return true;
  79859. }
  79860. return false;
  79861. };
  79862. LensFlareSystem.prototype._isVisible = function () {
  79863. if (!this._isEnabled || !this._scene.activeCamera) {
  79864. return false;
  79865. }
  79866. var emitterPosition = this.getEmitterPosition();
  79867. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  79868. var distance = direction.length();
  79869. direction.normalize();
  79870. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  79871. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  79872. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  79873. };
  79874. LensFlareSystem.prototype.render = function () {
  79875. if (!this._effect.isReady() || !this._scene.activeCamera)
  79876. return false;
  79877. var engine = this._scene.getEngine();
  79878. var viewport = this._scene.activeCamera.viewport;
  79879. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  79880. // Position
  79881. if (!this.computeEffectivePosition(globalViewport)) {
  79882. return false;
  79883. }
  79884. // Visibility
  79885. if (!this._isVisible()) {
  79886. return false;
  79887. }
  79888. // Intensity
  79889. var awayX;
  79890. var awayY;
  79891. if (this._positionX < this.borderLimit + globalViewport.x) {
  79892. awayX = this.borderLimit + globalViewport.x - this._positionX;
  79893. }
  79894. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  79895. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  79896. }
  79897. else {
  79898. awayX = 0;
  79899. }
  79900. if (this._positionY < this.borderLimit + globalViewport.y) {
  79901. awayY = this.borderLimit + globalViewport.y - this._positionY;
  79902. }
  79903. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  79904. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  79905. }
  79906. else {
  79907. awayY = 0;
  79908. }
  79909. var away = (awayX > awayY) ? awayX : awayY;
  79910. away -= this.viewportBorder;
  79911. if (away > this.borderLimit) {
  79912. away = this.borderLimit;
  79913. }
  79914. var intensity = 1.0 - (away / this.borderLimit);
  79915. if (intensity < 0) {
  79916. return false;
  79917. }
  79918. if (intensity > 1.0) {
  79919. intensity = 1.0;
  79920. }
  79921. if (this.viewportBorder > 0) {
  79922. globalViewport.x += this.viewportBorder;
  79923. globalViewport.y += this.viewportBorder;
  79924. globalViewport.width -= this.viewportBorder * 2;
  79925. globalViewport.height -= this.viewportBorder * 2;
  79926. this._positionX -= this.viewportBorder;
  79927. this._positionY -= this.viewportBorder;
  79928. }
  79929. // Position
  79930. var centerX = globalViewport.x + globalViewport.width / 2;
  79931. var centerY = globalViewport.y + globalViewport.height / 2;
  79932. var distX = centerX - this._positionX;
  79933. var distY = centerY - this._positionY;
  79934. // Effects
  79935. engine.enableEffect(this._effect);
  79936. engine.setState(false);
  79937. engine.setDepthBuffer(false);
  79938. // VBOs
  79939. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79940. // Flares
  79941. for (var index = 0; index < this.lensFlares.length; index++) {
  79942. var flare = this.lensFlares[index];
  79943. engine.setAlphaMode(flare.alphaMode);
  79944. var x = centerX - (distX * flare.position);
  79945. var y = centerY - (distY * flare.position);
  79946. var cw = flare.size;
  79947. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  79948. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  79949. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  79950. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  79951. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  79952. // Texture
  79953. this._effect.setTexture("textureSampler", flare.texture);
  79954. // Color
  79955. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  79956. // Draw order
  79957. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79958. }
  79959. engine.setDepthBuffer(true);
  79960. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79961. return true;
  79962. };
  79963. LensFlareSystem.prototype.dispose = function () {
  79964. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79965. if (vertexBuffer) {
  79966. vertexBuffer.dispose();
  79967. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79968. }
  79969. if (this._indexBuffer) {
  79970. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79971. this._indexBuffer = null;
  79972. }
  79973. while (this.lensFlares.length) {
  79974. this.lensFlares[0].dispose();
  79975. }
  79976. // Remove from scene
  79977. var index = this._scene.lensFlareSystems.indexOf(this);
  79978. this._scene.lensFlareSystems.splice(index, 1);
  79979. };
  79980. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  79981. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  79982. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  79983. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  79984. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  79985. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  79986. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  79987. var parsedFlare = parsedLensFlareSystem.flares[index];
  79988. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  79989. }
  79990. return lensFlareSystem;
  79991. };
  79992. LensFlareSystem.prototype.serialize = function () {
  79993. var serializationObject = {};
  79994. serializationObject.id = this.id;
  79995. serializationObject.name = this.name;
  79996. serializationObject.emitterId = this.getEmitter().id;
  79997. serializationObject.borderLimit = this.borderLimit;
  79998. serializationObject.flares = [];
  79999. for (var index = 0; index < this.lensFlares.length; index++) {
  80000. var flare = this.lensFlares[index];
  80001. serializationObject.flares.push({
  80002. size: flare.size,
  80003. position: flare.position,
  80004. color: flare.color.asArray(),
  80005. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  80006. });
  80007. }
  80008. return serializationObject;
  80009. };
  80010. return LensFlareSystem;
  80011. }());
  80012. BABYLON.LensFlareSystem = LensFlareSystem;
  80013. })(BABYLON || (BABYLON = {}));
  80014. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  80015. "use strict";
  80016. var BABYLON;
  80017. (function (BABYLON) {
  80018. /**
  80019. * This is a holder class for the physics joint created by the physics plugin.
  80020. * It holds a set of functions to control the underlying joint.
  80021. */
  80022. var PhysicsJoint = /** @class */ (function () {
  80023. function PhysicsJoint(type, jointData) {
  80024. this.type = type;
  80025. this.jointData = jointData;
  80026. jointData.nativeParams = jointData.nativeParams || {};
  80027. }
  80028. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  80029. get: function () {
  80030. return this._physicsJoint;
  80031. },
  80032. set: function (newJoint) {
  80033. if (this._physicsJoint) {
  80034. //remove from the wolrd
  80035. }
  80036. this._physicsJoint = newJoint;
  80037. },
  80038. enumerable: true,
  80039. configurable: true
  80040. });
  80041. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  80042. set: function (physicsPlugin) {
  80043. this._physicsPlugin = physicsPlugin;
  80044. },
  80045. enumerable: true,
  80046. configurable: true
  80047. });
  80048. /**
  80049. * Execute a function that is physics-plugin specific.
  80050. * @param {Function} func the function that will be executed.
  80051. * It accepts two parameters: the physics world and the physics joint.
  80052. */
  80053. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  80054. func(this._physicsPlugin.world, this._physicsJoint);
  80055. };
  80056. //TODO check if the native joints are the same
  80057. //Joint Types
  80058. PhysicsJoint.DistanceJoint = 0;
  80059. PhysicsJoint.HingeJoint = 1;
  80060. PhysicsJoint.BallAndSocketJoint = 2;
  80061. PhysicsJoint.WheelJoint = 3;
  80062. PhysicsJoint.SliderJoint = 4;
  80063. //OIMO
  80064. PhysicsJoint.PrismaticJoint = 5;
  80065. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  80066. PhysicsJoint.UniversalJoint = 6;
  80067. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  80068. //Cannon
  80069. //Similar to a Ball-Joint. Different in params
  80070. PhysicsJoint.PointToPointJoint = 8;
  80071. //Cannon only at the moment
  80072. PhysicsJoint.SpringJoint = 9;
  80073. PhysicsJoint.LockJoint = 10;
  80074. return PhysicsJoint;
  80075. }());
  80076. BABYLON.PhysicsJoint = PhysicsJoint;
  80077. /**
  80078. * A class representing a physics distance joint.
  80079. */
  80080. var DistanceJoint = /** @class */ (function (_super) {
  80081. __extends(DistanceJoint, _super);
  80082. function DistanceJoint(jointData) {
  80083. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  80084. }
  80085. /**
  80086. * Update the predefined distance.
  80087. */
  80088. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  80089. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  80090. };
  80091. return DistanceJoint;
  80092. }(PhysicsJoint));
  80093. BABYLON.DistanceJoint = DistanceJoint;
  80094. var MotorEnabledJoint = /** @class */ (function (_super) {
  80095. __extends(MotorEnabledJoint, _super);
  80096. function MotorEnabledJoint(type, jointData) {
  80097. return _super.call(this, type, jointData) || this;
  80098. }
  80099. /**
  80100. * Set the motor values.
  80101. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80102. * @param {number} force the force to apply
  80103. * @param {number} maxForce max force for this motor.
  80104. */
  80105. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  80106. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  80107. };
  80108. /**
  80109. * Set the motor's limits.
  80110. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80111. */
  80112. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  80113. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  80114. };
  80115. return MotorEnabledJoint;
  80116. }(PhysicsJoint));
  80117. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  80118. /**
  80119. * This class represents a single hinge physics joint
  80120. */
  80121. var HingeJoint = /** @class */ (function (_super) {
  80122. __extends(HingeJoint, _super);
  80123. function HingeJoint(jointData) {
  80124. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  80125. }
  80126. /**
  80127. * Set the motor values.
  80128. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80129. * @param {number} force the force to apply
  80130. * @param {number} maxForce max force for this motor.
  80131. */
  80132. HingeJoint.prototype.setMotor = function (force, maxForce) {
  80133. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  80134. };
  80135. /**
  80136. * Set the motor's limits.
  80137. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80138. */
  80139. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  80140. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  80141. };
  80142. return HingeJoint;
  80143. }(MotorEnabledJoint));
  80144. BABYLON.HingeJoint = HingeJoint;
  80145. /**
  80146. * This class represents a dual hinge physics joint (same as wheel joint)
  80147. */
  80148. var Hinge2Joint = /** @class */ (function (_super) {
  80149. __extends(Hinge2Joint, _super);
  80150. function Hinge2Joint(jointData) {
  80151. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  80152. }
  80153. /**
  80154. * Set the motor values.
  80155. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80156. * @param {number} force the force to apply
  80157. * @param {number} maxForce max force for this motor.
  80158. * @param {motorIndex} the motor's index, 0 or 1.
  80159. */
  80160. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  80161. if (motorIndex === void 0) { motorIndex = 0; }
  80162. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  80163. };
  80164. /**
  80165. * Set the motor limits.
  80166. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80167. * @param {number} upperLimit the upper limit
  80168. * @param {number} lowerLimit lower limit
  80169. * @param {motorIndex} the motor's index, 0 or 1.
  80170. */
  80171. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  80172. if (motorIndex === void 0) { motorIndex = 0; }
  80173. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  80174. };
  80175. return Hinge2Joint;
  80176. }(MotorEnabledJoint));
  80177. BABYLON.Hinge2Joint = Hinge2Joint;
  80178. })(BABYLON || (BABYLON = {}));
  80179. //# sourceMappingURL=babylon.physicsJoint.js.map
  80180. "use strict";
  80181. var BABYLON;
  80182. (function (BABYLON) {
  80183. var PhysicsImpostor = /** @class */ (function () {
  80184. function PhysicsImpostor(object, type, _options, _scene) {
  80185. if (_options === void 0) { _options = { mass: 0 }; }
  80186. var _this = this;
  80187. this.object = object;
  80188. this.type = type;
  80189. this._options = _options;
  80190. this._scene = _scene;
  80191. this._bodyUpdateRequired = false;
  80192. this._onBeforePhysicsStepCallbacks = new Array();
  80193. this._onAfterPhysicsStepCallbacks = new Array();
  80194. this._onPhysicsCollideCallbacks = [];
  80195. this._deltaPosition = BABYLON.Vector3.Zero();
  80196. this._isDisposed = false;
  80197. //temp variables for parent rotation calculations
  80198. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  80199. this._tmpQuat = new BABYLON.Quaternion();
  80200. this._tmpQuat2 = new BABYLON.Quaternion();
  80201. /**
  80202. * this function is executed by the physics engine.
  80203. */
  80204. this.beforeStep = function () {
  80205. if (!_this._physicsEngine) {
  80206. return;
  80207. }
  80208. _this.object.translate(_this._deltaPosition, -1);
  80209. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  80210. _this.object.computeWorldMatrix(false);
  80211. if (_this.object.parent && _this.object.rotationQuaternion) {
  80212. _this.getParentsRotation();
  80213. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  80214. }
  80215. else {
  80216. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  80217. }
  80218. if (!_this._options.disableBidirectionalTransformation) {
  80219. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  80220. }
  80221. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  80222. func(_this);
  80223. });
  80224. };
  80225. /**
  80226. * this function is executed by the physics engine.
  80227. */
  80228. this.afterStep = function () {
  80229. if (!_this._physicsEngine) {
  80230. return;
  80231. }
  80232. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  80233. func(_this);
  80234. });
  80235. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  80236. // object has now its world rotation. needs to be converted to local.
  80237. if (_this.object.parent && _this.object.rotationQuaternion) {
  80238. _this.getParentsRotation();
  80239. _this._tmpQuat.conjugateInPlace();
  80240. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  80241. }
  80242. // take the position set and make it the absolute position of this object.
  80243. _this.object.setAbsolutePosition(_this.object.position);
  80244. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  80245. _this.object.translate(_this._deltaPosition, 1);
  80246. };
  80247. /**
  80248. * Legacy collision detection event support
  80249. */
  80250. this.onCollideEvent = null;
  80251. //event and body object due to cannon's event-based architecture.
  80252. this.onCollide = function (e) {
  80253. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  80254. return;
  80255. }
  80256. if (!_this._physicsEngine) {
  80257. return;
  80258. }
  80259. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  80260. if (otherImpostor) {
  80261. // Legacy collision detection event support
  80262. if (_this.onCollideEvent) {
  80263. _this.onCollideEvent(_this, otherImpostor);
  80264. }
  80265. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  80266. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  80267. }).forEach(function (obj) {
  80268. obj.callback(_this, otherImpostor);
  80269. });
  80270. }
  80271. };
  80272. //sanity check!
  80273. if (!this.object) {
  80274. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  80275. return;
  80276. }
  80277. //legacy support for old syntax.
  80278. if (!this._scene && object.getScene) {
  80279. this._scene = object.getScene();
  80280. }
  80281. if (!this._scene) {
  80282. return;
  80283. }
  80284. this._physicsEngine = this._scene.getPhysicsEngine();
  80285. if (!this._physicsEngine) {
  80286. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  80287. }
  80288. else {
  80289. //set the object's quaternion, if not set
  80290. if (!this.object.rotationQuaternion) {
  80291. if (this.object.rotation) {
  80292. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  80293. }
  80294. else {
  80295. this.object.rotationQuaternion = new BABYLON.Quaternion();
  80296. }
  80297. }
  80298. //default options params
  80299. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  80300. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  80301. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  80302. this._joints = [];
  80303. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  80304. if (!this.object.parent || this._options.ignoreParent) {
  80305. this._init();
  80306. }
  80307. else if (this.object.parent.physicsImpostor) {
  80308. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  80309. }
  80310. }
  80311. }
  80312. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  80313. get: function () {
  80314. return this._isDisposed;
  80315. },
  80316. enumerable: true,
  80317. configurable: true
  80318. });
  80319. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  80320. get: function () {
  80321. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  80322. },
  80323. set: function (value) {
  80324. this.setMass(value);
  80325. },
  80326. enumerable: true,
  80327. configurable: true
  80328. });
  80329. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  80330. get: function () {
  80331. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  80332. },
  80333. set: function (value) {
  80334. if (!this._physicsEngine) {
  80335. return;
  80336. }
  80337. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  80338. },
  80339. enumerable: true,
  80340. configurable: true
  80341. });
  80342. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  80343. get: function () {
  80344. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  80345. },
  80346. set: function (value) {
  80347. if (!this._physicsEngine) {
  80348. return;
  80349. }
  80350. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  80351. },
  80352. enumerable: true,
  80353. configurable: true
  80354. });
  80355. /**
  80356. * This function will completly initialize this impostor.
  80357. * It will create a new body - but only if this mesh has no parent.
  80358. * If it has, this impostor will not be used other than to define the impostor
  80359. * of the child mesh.
  80360. */
  80361. PhysicsImpostor.prototype._init = function () {
  80362. if (!this._physicsEngine) {
  80363. return;
  80364. }
  80365. this._physicsEngine.removeImpostor(this);
  80366. this.physicsBody = null;
  80367. this._parent = this._parent || this._getPhysicsParent();
  80368. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  80369. this._physicsEngine.addImpostor(this);
  80370. }
  80371. };
  80372. PhysicsImpostor.prototype._getPhysicsParent = function () {
  80373. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  80374. var parentMesh = this.object.parent;
  80375. return parentMesh.physicsImpostor;
  80376. }
  80377. return null;
  80378. };
  80379. /**
  80380. * Should a new body be generated.
  80381. */
  80382. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  80383. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  80384. };
  80385. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  80386. this.forceUpdate();
  80387. };
  80388. /**
  80389. * Force a regeneration of this or the parent's impostor's body.
  80390. * Use under cautious - This will remove all joints already implemented.
  80391. */
  80392. PhysicsImpostor.prototype.forceUpdate = function () {
  80393. this._init();
  80394. if (this.parent && !this._options.ignoreParent) {
  80395. this.parent.forceUpdate();
  80396. }
  80397. };
  80398. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  80399. /*public get mesh(): AbstractMesh {
  80400. return this._mesh;
  80401. }*/
  80402. /**
  80403. * Gets the body that holds this impostor. Either its own, or its parent.
  80404. */
  80405. get: function () {
  80406. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  80407. },
  80408. /**
  80409. * Set the physics body. Used mainly by the physics engine/plugin
  80410. */
  80411. set: function (physicsBody) {
  80412. if (this._physicsBody && this._physicsEngine) {
  80413. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  80414. }
  80415. this._physicsBody = physicsBody;
  80416. this.resetUpdateFlags();
  80417. },
  80418. enumerable: true,
  80419. configurable: true
  80420. });
  80421. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  80422. get: function () {
  80423. return !this._options.ignoreParent && this._parent ? this._parent : null;
  80424. },
  80425. set: function (value) {
  80426. this._parent = value;
  80427. },
  80428. enumerable: true,
  80429. configurable: true
  80430. });
  80431. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  80432. this._bodyUpdateRequired = false;
  80433. };
  80434. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  80435. if (this.object.getBoundingInfo) {
  80436. var q = this.object.rotationQuaternion;
  80437. //reset rotation
  80438. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  80439. //calculate the world matrix with no rotation
  80440. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80441. var boundingInfo = this.object.getBoundingInfo();
  80442. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  80443. //bring back the rotation
  80444. this.object.rotationQuaternion = q;
  80445. //calculate the world matrix with the new rotation
  80446. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80447. return size;
  80448. }
  80449. else {
  80450. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  80451. }
  80452. };
  80453. PhysicsImpostor.prototype.getObjectCenter = function () {
  80454. if (this.object.getBoundingInfo) {
  80455. var boundingInfo = this.object.getBoundingInfo();
  80456. return boundingInfo.boundingBox.centerWorld;
  80457. }
  80458. else {
  80459. return this.object.position;
  80460. }
  80461. };
  80462. /**
  80463. * Get a specific parametes from the options parameter.
  80464. */
  80465. PhysicsImpostor.prototype.getParam = function (paramName) {
  80466. return this._options[paramName];
  80467. };
  80468. /**
  80469. * Sets a specific parameter in the options given to the physics plugin
  80470. */
  80471. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  80472. this._options[paramName] = value;
  80473. this._bodyUpdateRequired = true;
  80474. };
  80475. /**
  80476. * Specifically change the body's mass option. Won't recreate the physics body object
  80477. */
  80478. PhysicsImpostor.prototype.setMass = function (mass) {
  80479. if (this.getParam("mass") !== mass) {
  80480. this.setParam("mass", mass);
  80481. }
  80482. if (this._physicsEngine) {
  80483. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  80484. }
  80485. };
  80486. PhysicsImpostor.prototype.getLinearVelocity = function () {
  80487. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  80488. };
  80489. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  80490. if (this._physicsEngine) {
  80491. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  80492. }
  80493. };
  80494. PhysicsImpostor.prototype.getAngularVelocity = function () {
  80495. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  80496. };
  80497. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  80498. if (this._physicsEngine) {
  80499. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  80500. }
  80501. };
  80502. /**
  80503. * Execute a function with the physics plugin native code.
  80504. * Provide a function the will have two variables - the world object and the physics body object.
  80505. */
  80506. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  80507. if (this._physicsEngine) {
  80508. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  80509. }
  80510. };
  80511. /**
  80512. * Register a function that will be executed before the physics world is stepping forward.
  80513. */
  80514. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  80515. this._onBeforePhysicsStepCallbacks.push(func);
  80516. };
  80517. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  80518. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  80519. if (index > -1) {
  80520. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  80521. }
  80522. else {
  80523. BABYLON.Tools.Warn("Function to remove was not found");
  80524. }
  80525. };
  80526. /**
  80527. * Register a function that will be executed after the physics step
  80528. */
  80529. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  80530. this._onAfterPhysicsStepCallbacks.push(func);
  80531. };
  80532. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  80533. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  80534. if (index > -1) {
  80535. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  80536. }
  80537. else {
  80538. BABYLON.Tools.Warn("Function to remove was not found");
  80539. }
  80540. };
  80541. /**
  80542. * register a function that will be executed when this impostor collides against a different body.
  80543. */
  80544. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  80545. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80546. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  80547. };
  80548. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  80549. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80550. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  80551. if (index > -1) {
  80552. this._onPhysicsCollideCallbacks.splice(index, 1);
  80553. }
  80554. else {
  80555. BABYLON.Tools.Warn("Function to remove was not found");
  80556. }
  80557. };
  80558. PhysicsImpostor.prototype.getParentsRotation = function () {
  80559. var parent = this.object.parent;
  80560. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  80561. while (parent) {
  80562. if (parent.rotationQuaternion) {
  80563. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  80564. }
  80565. else {
  80566. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  80567. }
  80568. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  80569. parent = parent.parent;
  80570. }
  80571. return this._tmpQuat;
  80572. };
  80573. /**
  80574. * Apply a force
  80575. */
  80576. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  80577. if (this._physicsEngine) {
  80578. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  80579. }
  80580. return this;
  80581. };
  80582. /**
  80583. * Apply an impulse
  80584. */
  80585. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  80586. if (this._physicsEngine) {
  80587. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  80588. }
  80589. return this;
  80590. };
  80591. /**
  80592. * A help function to create a joint.
  80593. */
  80594. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  80595. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  80596. this.addJoint(otherImpostor, joint);
  80597. return this;
  80598. };
  80599. /**
  80600. * Add a joint to this impostor with a different impostor.
  80601. */
  80602. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  80603. this._joints.push({
  80604. otherImpostor: otherImpostor,
  80605. joint: joint
  80606. });
  80607. if (this._physicsEngine) {
  80608. this._physicsEngine.addJoint(this, otherImpostor, joint);
  80609. }
  80610. return this;
  80611. };
  80612. /**
  80613. * Will keep this body still, in a sleep mode.
  80614. */
  80615. PhysicsImpostor.prototype.sleep = function () {
  80616. if (this._physicsEngine) {
  80617. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  80618. }
  80619. return this;
  80620. };
  80621. /**
  80622. * Wake the body up.
  80623. */
  80624. PhysicsImpostor.prototype.wakeUp = function () {
  80625. if (this._physicsEngine) {
  80626. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  80627. }
  80628. return this;
  80629. };
  80630. PhysicsImpostor.prototype.clone = function (newObject) {
  80631. if (!newObject)
  80632. return null;
  80633. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  80634. };
  80635. PhysicsImpostor.prototype.dispose = function () {
  80636. var _this = this;
  80637. //no dispose if no physics engine is available.
  80638. if (!this._physicsEngine) {
  80639. return;
  80640. }
  80641. this._joints.forEach(function (j) {
  80642. if (_this._physicsEngine) {
  80643. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  80644. }
  80645. });
  80646. //dispose the physics body
  80647. this._physicsEngine.removeImpostor(this);
  80648. if (this.parent) {
  80649. this.parent.forceUpdate();
  80650. }
  80651. else {
  80652. /*this._object.getChildMeshes().forEach(function(mesh) {
  80653. if (mesh.physicsImpostor) {
  80654. if (disposeChildren) {
  80655. mesh.physicsImpostor.dispose();
  80656. mesh.physicsImpostor = null;
  80657. }
  80658. }
  80659. })*/
  80660. }
  80661. this._isDisposed = true;
  80662. };
  80663. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  80664. this._deltaPosition.copyFrom(position);
  80665. };
  80666. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  80667. if (!this._deltaRotation) {
  80668. this._deltaRotation = new BABYLON.Quaternion();
  80669. }
  80670. this._deltaRotation.copyFrom(rotation);
  80671. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  80672. };
  80673. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  80674. if (this._physicsEngine) {
  80675. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  80676. }
  80677. return this;
  80678. };
  80679. PhysicsImpostor.prototype.getRadius = function () {
  80680. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  80681. };
  80682. /**
  80683. * Sync a bone with this impostor
  80684. * @param bone The bone to sync to the impostor.
  80685. * @param boneMesh The mesh that the bone is influencing.
  80686. * @param jointPivot The pivot of the joint / bone in local space.
  80687. * @param distToJoint Optional distance from the impostor to the joint.
  80688. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80689. */
  80690. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  80691. var tempVec = PhysicsImpostor._tmpVecs[0];
  80692. var mesh = this.object;
  80693. if (mesh.rotationQuaternion) {
  80694. if (adjustRotation) {
  80695. var tempQuat = PhysicsImpostor._tmpQuat;
  80696. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  80697. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  80698. }
  80699. else {
  80700. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  80701. }
  80702. }
  80703. tempVec.x = 0;
  80704. tempVec.y = 0;
  80705. tempVec.z = 0;
  80706. if (jointPivot) {
  80707. tempVec.x = jointPivot.x;
  80708. tempVec.y = jointPivot.y;
  80709. tempVec.z = jointPivot.z;
  80710. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  80711. if (distToJoint === undefined || distToJoint === null) {
  80712. distToJoint = jointPivot.length();
  80713. }
  80714. tempVec.x *= distToJoint;
  80715. tempVec.y *= distToJoint;
  80716. tempVec.z *= distToJoint;
  80717. }
  80718. if (bone.getParent()) {
  80719. tempVec.addInPlace(mesh.getAbsolutePosition());
  80720. bone.setAbsolutePosition(tempVec, boneMesh);
  80721. }
  80722. else {
  80723. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  80724. boneMesh.position.x -= tempVec.x;
  80725. boneMesh.position.y -= tempVec.y;
  80726. boneMesh.position.z -= tempVec.z;
  80727. }
  80728. };
  80729. /**
  80730. * Sync impostor to a bone
  80731. * @param bone The bone that the impostor will be synced to.
  80732. * @param boneMesh The mesh that the bone is influencing.
  80733. * @param jointPivot The pivot of the joint / bone in local space.
  80734. * @param distToJoint Optional distance from the impostor to the joint.
  80735. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80736. * @param boneAxis Optional vector3 axis the bone is aligned with
  80737. */
  80738. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  80739. var mesh = this.object;
  80740. if (mesh.rotationQuaternion) {
  80741. if (adjustRotation) {
  80742. var tempQuat = PhysicsImpostor._tmpQuat;
  80743. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  80744. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  80745. }
  80746. else {
  80747. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  80748. }
  80749. }
  80750. var pos = PhysicsImpostor._tmpVecs[0];
  80751. var boneDir = PhysicsImpostor._tmpVecs[1];
  80752. if (!boneAxis) {
  80753. boneAxis = PhysicsImpostor._tmpVecs[2];
  80754. boneAxis.x = 0;
  80755. boneAxis.y = 1;
  80756. boneAxis.z = 0;
  80757. }
  80758. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  80759. bone.getAbsolutePositionToRef(boneMesh, pos);
  80760. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  80761. distToJoint = jointPivot.length();
  80762. }
  80763. if (distToJoint !== undefined && distToJoint !== null) {
  80764. pos.x += boneDir.x * distToJoint;
  80765. pos.y += boneDir.y * distToJoint;
  80766. pos.z += boneDir.z * distToJoint;
  80767. }
  80768. mesh.setAbsolutePosition(pos);
  80769. };
  80770. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  80771. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  80772. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80773. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  80774. //Impostor types
  80775. PhysicsImpostor.NoImpostor = 0;
  80776. PhysicsImpostor.SphereImpostor = 1;
  80777. PhysicsImpostor.BoxImpostor = 2;
  80778. PhysicsImpostor.PlaneImpostor = 3;
  80779. PhysicsImpostor.MeshImpostor = 4;
  80780. PhysicsImpostor.CylinderImpostor = 7;
  80781. PhysicsImpostor.ParticleImpostor = 8;
  80782. PhysicsImpostor.HeightmapImpostor = 9;
  80783. return PhysicsImpostor;
  80784. }());
  80785. BABYLON.PhysicsImpostor = PhysicsImpostor;
  80786. })(BABYLON || (BABYLON = {}));
  80787. //# sourceMappingURL=babylon.physicsImpostor.js.map
  80788. "use strict";
  80789. var BABYLON;
  80790. (function (BABYLON) {
  80791. var PhysicsEngine = /** @class */ (function () {
  80792. function PhysicsEngine(gravity, _physicsPlugin) {
  80793. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  80794. this._physicsPlugin = _physicsPlugin;
  80795. //new methods and parameters
  80796. this._impostors = [];
  80797. this._joints = [];
  80798. if (!this._physicsPlugin.isSupported()) {
  80799. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  80800. + "Please make sure it is included.");
  80801. }
  80802. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  80803. this.setGravity(gravity);
  80804. this.setTimeStep();
  80805. }
  80806. PhysicsEngine.prototype.setGravity = function (gravity) {
  80807. this.gravity = gravity;
  80808. this._physicsPlugin.setGravity(this.gravity);
  80809. };
  80810. /**
  80811. * Set the time step of the physics engine.
  80812. * default is 1/60.
  80813. * To slow it down, enter 1/600 for example.
  80814. * To speed it up, 1/30
  80815. * @param {number} newTimeStep the new timestep to apply to this world.
  80816. */
  80817. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  80818. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  80819. this._physicsPlugin.setTimeStep(newTimeStep);
  80820. };
  80821. /**
  80822. * Get the time step of the physics engine.
  80823. */
  80824. PhysicsEngine.prototype.getTimeStep = function () {
  80825. return this._physicsPlugin.getTimeStep();
  80826. };
  80827. PhysicsEngine.prototype.dispose = function () {
  80828. this._impostors.forEach(function (impostor) {
  80829. impostor.dispose();
  80830. });
  80831. this._physicsPlugin.dispose();
  80832. };
  80833. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  80834. return this._physicsPlugin.name;
  80835. };
  80836. /**
  80837. * Adding a new impostor for the impostor tracking.
  80838. * This will be done by the impostor itself.
  80839. * @param {PhysicsImpostor} impostor the impostor to add
  80840. */
  80841. PhysicsEngine.prototype.addImpostor = function (impostor) {
  80842. impostor.uniqueId = this._impostors.push(impostor);
  80843. //if no parent, generate the body
  80844. if (!impostor.parent) {
  80845. this._physicsPlugin.generatePhysicsBody(impostor);
  80846. }
  80847. };
  80848. /**
  80849. * Remove an impostor from the engine.
  80850. * This impostor and its mesh will not longer be updated by the physics engine.
  80851. * @param {PhysicsImpostor} impostor the impostor to remove
  80852. */
  80853. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  80854. var index = this._impostors.indexOf(impostor);
  80855. if (index > -1) {
  80856. var removed = this._impostors.splice(index, 1);
  80857. //Is it needed?
  80858. if (removed.length) {
  80859. //this will also remove it from the world.
  80860. removed[0].physicsBody = null;
  80861. }
  80862. }
  80863. };
  80864. /**
  80865. * Add a joint to the physics engine
  80866. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  80867. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  80868. * @param {PhysicsJoint} the joint that will connect both impostors.
  80869. */
  80870. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  80871. var impostorJoint = {
  80872. mainImpostor: mainImpostor,
  80873. connectedImpostor: connectedImpostor,
  80874. joint: joint
  80875. };
  80876. joint.physicsPlugin = this._physicsPlugin;
  80877. this._joints.push(impostorJoint);
  80878. this._physicsPlugin.generateJoint(impostorJoint);
  80879. };
  80880. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  80881. var matchingJoints = this._joints.filter(function (impostorJoint) {
  80882. return (impostorJoint.connectedImpostor === connectedImpostor
  80883. && impostorJoint.joint === joint
  80884. && impostorJoint.mainImpostor === mainImpostor);
  80885. });
  80886. if (matchingJoints.length) {
  80887. this._physicsPlugin.removeJoint(matchingJoints[0]);
  80888. //TODO remove it from the list as well
  80889. }
  80890. };
  80891. /**
  80892. * Called by the scene. no need to call it.
  80893. */
  80894. PhysicsEngine.prototype._step = function (delta) {
  80895. var _this = this;
  80896. //check if any mesh has no body / requires an update
  80897. this._impostors.forEach(function (impostor) {
  80898. if (impostor.isBodyInitRequired()) {
  80899. _this._physicsPlugin.generatePhysicsBody(impostor);
  80900. }
  80901. });
  80902. if (delta > 0.1) {
  80903. delta = 0.1;
  80904. }
  80905. else if (delta <= 0) {
  80906. delta = 1.0 / 60.0;
  80907. }
  80908. this._physicsPlugin.executeStep(delta, this._impostors);
  80909. };
  80910. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  80911. return this._physicsPlugin;
  80912. };
  80913. PhysicsEngine.prototype.getImpostors = function () {
  80914. return this._impostors;
  80915. };
  80916. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  80917. for (var i = 0; i < this._impostors.length; ++i) {
  80918. if (this._impostors[i].object === object) {
  80919. return this._impostors[i];
  80920. }
  80921. }
  80922. return null;
  80923. };
  80924. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  80925. for (var i = 0; i < this._impostors.length; ++i) {
  80926. if (this._impostors[i].physicsBody === body) {
  80927. return this._impostors[i];
  80928. }
  80929. }
  80930. return null;
  80931. };
  80932. // Statics
  80933. PhysicsEngine.Epsilon = 0.001;
  80934. return PhysicsEngine;
  80935. }());
  80936. BABYLON.PhysicsEngine = PhysicsEngine;
  80937. })(BABYLON || (BABYLON = {}));
  80938. //# sourceMappingURL=babylon.physicsEngine.js.map
  80939. "use strict";
  80940. var BABYLON;
  80941. (function (BABYLON) {
  80942. var PhysicsHelper = /** @class */ (function () {
  80943. function PhysicsHelper(scene) {
  80944. this._scene = scene;
  80945. this._physicsEngine = this._scene.getPhysicsEngine();
  80946. if (!this._physicsEngine) {
  80947. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  80948. }
  80949. }
  80950. /**
  80951. * @param {Vector3} origin the origin of the explosion
  80952. * @param {number} radius the explosion radius
  80953. * @param {number} strength the explosion strength
  80954. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80955. */
  80956. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  80957. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80958. if (!this._physicsEngine) {
  80959. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  80960. return null;
  80961. }
  80962. var impostors = this._physicsEngine.getImpostors();
  80963. if (impostors.length === 0) {
  80964. return null;
  80965. }
  80966. var event = new PhysicsRadialExplosionEvent(this._scene);
  80967. impostors.forEach(function (impostor) {
  80968. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80969. if (!impostorForceAndContactPoint) {
  80970. return;
  80971. }
  80972. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80973. });
  80974. event.dispose(false);
  80975. return event;
  80976. };
  80977. /**
  80978. * @param {Vector3} origin the origin of the explosion
  80979. * @param {number} radius the explosion radius
  80980. * @param {number} strength the explosion strength
  80981. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80982. */
  80983. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  80984. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80985. if (!this._physicsEngine) {
  80986. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80987. return null;
  80988. }
  80989. var impostors = this._physicsEngine.getImpostors();
  80990. if (impostors.length === 0) {
  80991. return null;
  80992. }
  80993. var event = new PhysicsRadialExplosionEvent(this._scene);
  80994. impostors.forEach(function (impostor) {
  80995. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80996. if (!impostorForceAndContactPoint) {
  80997. return;
  80998. }
  80999. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81000. });
  81001. event.dispose(false);
  81002. return event;
  81003. };
  81004. /**
  81005. * @param {Vector3} origin the origin of the explosion
  81006. * @param {number} radius the explosion radius
  81007. * @param {number} strength the explosion strength
  81008. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81009. */
  81010. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  81011. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81012. if (!this._physicsEngine) {
  81013. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81014. return null;
  81015. }
  81016. var impostors = this._physicsEngine.getImpostors();
  81017. if (impostors.length === 0) {
  81018. return null;
  81019. }
  81020. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  81021. event.dispose(false);
  81022. return event;
  81023. };
  81024. /**
  81025. * @param {Vector3} origin the origin of the updraft
  81026. * @param {number} radius the radius of the updraft
  81027. * @param {number} strength the strength of the updraft
  81028. * @param {number} height the height of the updraft
  81029. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  81030. */
  81031. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  81032. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  81033. if (!this._physicsEngine) {
  81034. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81035. return null;
  81036. }
  81037. if (this._physicsEngine.getImpostors().length === 0) {
  81038. return null;
  81039. }
  81040. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  81041. event.dispose(false);
  81042. return event;
  81043. };
  81044. /**
  81045. * @param {Vector3} origin the of the vortex
  81046. * @param {number} radius the radius of the vortex
  81047. * @param {number} strength the strength of the vortex
  81048. * @param {number} height the height of the vortex
  81049. */
  81050. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  81051. if (!this._physicsEngine) {
  81052. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81053. return null;
  81054. }
  81055. if (this._physicsEngine.getImpostors().length === 0) {
  81056. return null;
  81057. }
  81058. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  81059. event.dispose(false);
  81060. return event;
  81061. };
  81062. return PhysicsHelper;
  81063. }());
  81064. BABYLON.PhysicsHelper = PhysicsHelper;
  81065. /***** Radial explosion *****/
  81066. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  81067. function PhysicsRadialExplosionEvent(scene) {
  81068. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  81069. this._rays = [];
  81070. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  81071. this._scene = scene;
  81072. }
  81073. /**
  81074. * Returns the data related to the radial explosion event (sphere & rays).
  81075. * @returns {PhysicsRadialExplosionEventData}
  81076. */
  81077. PhysicsRadialExplosionEvent.prototype.getData = function () {
  81078. this._dataFetched = true;
  81079. return {
  81080. sphere: this._sphere,
  81081. rays: this._rays,
  81082. };
  81083. };
  81084. /**
  81085. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  81086. * @param impostor
  81087. * @param {Vector3} origin the origin of the explosion
  81088. * @param {number} radius the explosion radius
  81089. * @param {number} strength the explosion strength
  81090. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  81091. * @returns {Nullable<PhysicsForceAndContactPoint>}
  81092. */
  81093. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  81094. if (impostor.mass === 0) {
  81095. return null;
  81096. }
  81097. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  81098. return null;
  81099. }
  81100. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81101. return null;
  81102. }
  81103. var impostorObjectCenter = impostor.getObjectCenter();
  81104. var direction = impostorObjectCenter.subtract(origin);
  81105. var ray = new BABYLON.Ray(origin, direction, radius);
  81106. this._rays.push(ray);
  81107. var hit = ray.intersectsMesh(impostor.object);
  81108. var contactPoint = hit.pickedPoint;
  81109. if (!contactPoint) {
  81110. return null;
  81111. }
  81112. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  81113. if (distanceFromOrigin > radius) {
  81114. return null;
  81115. }
  81116. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  81117. ? strength
  81118. : strength * (1 - (distanceFromOrigin / radius));
  81119. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81120. return { force: force, contactPoint: contactPoint };
  81121. };
  81122. /**
  81123. * Disposes the sphere.
  81124. * @param {bolean} force
  81125. */
  81126. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  81127. var _this = this;
  81128. if (force === void 0) { force = true; }
  81129. if (force) {
  81130. this._sphere.dispose();
  81131. }
  81132. else {
  81133. setTimeout(function () {
  81134. if (!_this._dataFetched) {
  81135. _this._sphere.dispose();
  81136. }
  81137. }, 0);
  81138. }
  81139. };
  81140. /*** Helpers ***/
  81141. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  81142. if (!this._sphere) {
  81143. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  81144. this._sphere.isVisible = false;
  81145. }
  81146. };
  81147. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  81148. var impostorObject = impostor.object;
  81149. this._prepareSphere();
  81150. this._sphere.position = origin;
  81151. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  81152. this._sphere._updateBoundingInfo();
  81153. this._sphere.computeWorldMatrix(true);
  81154. return this._sphere.intersectsMesh(impostorObject, true);
  81155. };
  81156. return PhysicsRadialExplosionEvent;
  81157. }());
  81158. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  81159. /***** Gravitational Field *****/
  81160. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  81161. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  81162. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81163. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81164. this._physicsHelper = physicsHelper;
  81165. this._scene = scene;
  81166. this._origin = origin;
  81167. this._radius = radius;
  81168. this._strength = strength;
  81169. this._falloff = falloff;
  81170. this._tickCallback = this._tick.bind(this);
  81171. }
  81172. /**
  81173. * Returns the data related to the gravitational field event (sphere).
  81174. * @returns {PhysicsGravitationalFieldEventData}
  81175. */
  81176. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  81177. this._dataFetched = true;
  81178. return {
  81179. sphere: this._sphere,
  81180. };
  81181. };
  81182. /**
  81183. * Enables the gravitational field.
  81184. */
  81185. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  81186. this._tickCallback.call(this);
  81187. this._scene.registerBeforeRender(this._tickCallback);
  81188. };
  81189. /**
  81190. * Disables the gravitational field.
  81191. */
  81192. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  81193. this._scene.unregisterBeforeRender(this._tickCallback);
  81194. };
  81195. /**
  81196. * Disposes the sphere.
  81197. * @param {bolean} force
  81198. */
  81199. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  81200. var _this = this;
  81201. if (force === void 0) { force = true; }
  81202. if (force) {
  81203. this._sphere.dispose();
  81204. }
  81205. else {
  81206. setTimeout(function () {
  81207. if (!_this._dataFetched) {
  81208. _this._sphere.dispose();
  81209. }
  81210. }, 0);
  81211. }
  81212. };
  81213. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  81214. // Since the params won't change, we fetch the event only once
  81215. if (this._sphere) {
  81216. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  81217. }
  81218. else {
  81219. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  81220. if (radialExplosionEvent) {
  81221. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  81222. }
  81223. }
  81224. };
  81225. return PhysicsGravitationalFieldEvent;
  81226. }());
  81227. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  81228. /***** Updraft *****/
  81229. var PhysicsUpdraftEvent = /** @class */ (function () {
  81230. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  81231. this._scene = _scene;
  81232. this._origin = _origin;
  81233. this._radius = _radius;
  81234. this._strength = _strength;
  81235. this._height = _height;
  81236. this._updraftMode = _updraftMode;
  81237. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81238. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  81239. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81240. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81241. this._physicsEngine = this._scene.getPhysicsEngine();
  81242. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81243. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81244. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81245. this._originDirection = this._origin.subtract(this._originTop).normalize();
  81246. }
  81247. this._tickCallback = this._tick.bind(this);
  81248. }
  81249. /**
  81250. * Returns the data related to the updraft event (cylinder).
  81251. * @returns {PhysicsUpdraftEventData}
  81252. */
  81253. PhysicsUpdraftEvent.prototype.getData = function () {
  81254. this._dataFetched = true;
  81255. return {
  81256. cylinder: this._cylinder,
  81257. };
  81258. };
  81259. /**
  81260. * Enables the updraft.
  81261. */
  81262. PhysicsUpdraftEvent.prototype.enable = function () {
  81263. this._tickCallback.call(this);
  81264. this._scene.registerBeforeRender(this._tickCallback);
  81265. };
  81266. /**
  81267. * Disables the cortex.
  81268. */
  81269. PhysicsUpdraftEvent.prototype.disable = function () {
  81270. this._scene.unregisterBeforeRender(this._tickCallback);
  81271. };
  81272. /**
  81273. * Disposes the sphere.
  81274. * @param {bolean} force
  81275. */
  81276. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  81277. var _this = this;
  81278. if (force === void 0) { force = true; }
  81279. if (force) {
  81280. this._cylinder.dispose();
  81281. }
  81282. else {
  81283. setTimeout(function () {
  81284. if (!_this._dataFetched) {
  81285. _this._cylinder.dispose();
  81286. }
  81287. }, 0);
  81288. }
  81289. };
  81290. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81291. if (impostor.mass === 0) {
  81292. return null;
  81293. }
  81294. if (!this._intersectsWithCylinder(impostor)) {
  81295. return null;
  81296. }
  81297. var impostorObjectCenter = impostor.getObjectCenter();
  81298. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81299. var direction = this._originDirection;
  81300. }
  81301. else {
  81302. var direction = impostorObjectCenter.subtract(this._originTop);
  81303. }
  81304. var multiplier = this._strength * -1;
  81305. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81306. return { force: force, contactPoint: impostorObjectCenter };
  81307. };
  81308. PhysicsUpdraftEvent.prototype._tick = function () {
  81309. var _this = this;
  81310. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81311. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81312. if (!impostorForceAndContactPoint) {
  81313. return;
  81314. }
  81315. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81316. });
  81317. };
  81318. /*** Helpers ***/
  81319. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  81320. if (!this._cylinder) {
  81321. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  81322. height: this._height,
  81323. diameter: this._radius * 2,
  81324. }, this._scene);
  81325. this._cylinder.isVisible = false;
  81326. }
  81327. };
  81328. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  81329. var impostorObject = impostor.object;
  81330. this._prepareCylinder();
  81331. this._cylinder.position = this._cylinderPosition;
  81332. return this._cylinder.intersectsMesh(impostorObject, true);
  81333. };
  81334. return PhysicsUpdraftEvent;
  81335. }());
  81336. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  81337. /***** Vortex *****/
  81338. var PhysicsVortexEvent = /** @class */ (function () {
  81339. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  81340. this._scene = _scene;
  81341. this._origin = _origin;
  81342. this._radius = _radius;
  81343. this._strength = _strength;
  81344. this._height = _height;
  81345. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81346. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  81347. this._updraftMultiplier = 0.02;
  81348. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81349. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81350. this._physicsEngine = this._scene.getPhysicsEngine();
  81351. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81352. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81353. this._tickCallback = this._tick.bind(this);
  81354. }
  81355. /**
  81356. * Returns the data related to the vortex event (cylinder).
  81357. * @returns {PhysicsVortexEventData}
  81358. */
  81359. PhysicsVortexEvent.prototype.getData = function () {
  81360. this._dataFetched = true;
  81361. return {
  81362. cylinder: this._cylinder,
  81363. };
  81364. };
  81365. /**
  81366. * Enables the vortex.
  81367. */
  81368. PhysicsVortexEvent.prototype.enable = function () {
  81369. this._tickCallback.call(this);
  81370. this._scene.registerBeforeRender(this._tickCallback);
  81371. };
  81372. /**
  81373. * Disables the cortex.
  81374. */
  81375. PhysicsVortexEvent.prototype.disable = function () {
  81376. this._scene.unregisterBeforeRender(this._tickCallback);
  81377. };
  81378. /**
  81379. * Disposes the sphere.
  81380. * @param {bolean} force
  81381. */
  81382. PhysicsVortexEvent.prototype.dispose = function (force) {
  81383. var _this = this;
  81384. if (force === void 0) { force = true; }
  81385. if (force) {
  81386. this._cylinder.dispose();
  81387. }
  81388. else {
  81389. setTimeout(function () {
  81390. if (!_this._dataFetched) {
  81391. _this._cylinder.dispose();
  81392. }
  81393. }, 0);
  81394. }
  81395. };
  81396. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81397. if (impostor.mass === 0) {
  81398. return null;
  81399. }
  81400. if (!this._intersectsWithCylinder(impostor)) {
  81401. return null;
  81402. }
  81403. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81404. return null;
  81405. }
  81406. var impostorObjectCenter = impostor.getObjectCenter();
  81407. 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)
  81408. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  81409. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  81410. var hit = ray.intersectsMesh(impostor.object);
  81411. var contactPoint = hit.pickedPoint;
  81412. if (!contactPoint) {
  81413. return null;
  81414. }
  81415. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  81416. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  81417. var directionToOrigin = contactPoint.normalize();
  81418. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81419. directionToOrigin = directionToOrigin.negate();
  81420. }
  81421. // TODO: find a more physically based solution
  81422. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81423. var forceX = directionToOrigin.x * this._strength / 8;
  81424. var forceY = directionToOrigin.y * this._updraftMultiplier;
  81425. var forceZ = directionToOrigin.z * this._strength / 8;
  81426. }
  81427. else {
  81428. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  81429. var forceY = this._originTop.y * this._updraftMultiplier;
  81430. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  81431. }
  81432. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  81433. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  81434. return { force: force, contactPoint: impostorObjectCenter };
  81435. };
  81436. PhysicsVortexEvent.prototype._tick = function () {
  81437. var _this = this;
  81438. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81439. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81440. if (!impostorForceAndContactPoint) {
  81441. return;
  81442. }
  81443. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81444. });
  81445. };
  81446. /*** Helpers ***/
  81447. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  81448. if (!this._cylinder) {
  81449. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  81450. height: this._height,
  81451. diameter: this._radius * 2,
  81452. }, this._scene);
  81453. this._cylinder.isVisible = false;
  81454. }
  81455. };
  81456. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  81457. var impostorObject = impostor.object;
  81458. this._prepareCylinder();
  81459. this._cylinder.position = this._cylinderPosition;
  81460. return this._cylinder.intersectsMesh(impostorObject, true);
  81461. };
  81462. return PhysicsVortexEvent;
  81463. }());
  81464. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  81465. /***** Enums *****/
  81466. /**
  81467. * The strenght of the force in correspondence to the distance of the affected object
  81468. */
  81469. var PhysicsRadialImpulseFalloff;
  81470. (function (PhysicsRadialImpulseFalloff) {
  81471. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  81472. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  81473. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  81474. /**
  81475. * The strenght of the force in correspondence to the distance of the affected object
  81476. */
  81477. var PhysicsUpdraftMode;
  81478. (function (PhysicsUpdraftMode) {
  81479. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  81480. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  81481. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  81482. })(BABYLON || (BABYLON = {}));
  81483. //# sourceMappingURL=babylon.physicsHelper.js.map
  81484. "use strict";
  81485. var BABYLON;
  81486. (function (BABYLON) {
  81487. var CannonJSPlugin = /** @class */ (function () {
  81488. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  81489. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  81490. if (iterations === void 0) { iterations = 10; }
  81491. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  81492. this.name = "CannonJSPlugin";
  81493. this._physicsMaterials = new Array();
  81494. this._fixedTimeStep = 1 / 60;
  81495. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  81496. this.BJSCANNON = CANNON;
  81497. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  81498. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  81499. this._tmpPosition = BABYLON.Vector3.Zero();
  81500. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  81501. this._tmpUnityRotation = new BABYLON.Quaternion();
  81502. if (!this.isSupported()) {
  81503. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  81504. return;
  81505. }
  81506. this._extendNamespace();
  81507. this.world = new this.BJSCANNON.World();
  81508. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  81509. this.world.solver.iterations = iterations;
  81510. }
  81511. CannonJSPlugin.prototype.setGravity = function (gravity) {
  81512. this.world.gravity.copy(gravity);
  81513. };
  81514. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  81515. this._fixedTimeStep = timeStep;
  81516. };
  81517. CannonJSPlugin.prototype.getTimeStep = function () {
  81518. return this._fixedTimeStep;
  81519. };
  81520. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  81521. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  81522. };
  81523. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81524. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81525. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81526. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  81527. };
  81528. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81529. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81530. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81531. impostor.physicsBody.applyForce(impulse, worldPoint);
  81532. };
  81533. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81534. //parent-child relationship. Does this impostor has a parent impostor?
  81535. if (impostor.parent) {
  81536. if (impostor.physicsBody) {
  81537. this.removePhysicsBody(impostor);
  81538. //TODO is that needed?
  81539. impostor.forceUpdate();
  81540. }
  81541. return;
  81542. }
  81543. //should a new body be created for this impostor?
  81544. if (impostor.isBodyInitRequired()) {
  81545. var shape = this._createShape(impostor);
  81546. //unregister events, if body is being changed
  81547. var oldBody = impostor.physicsBody;
  81548. if (oldBody) {
  81549. this.removePhysicsBody(impostor);
  81550. }
  81551. //create the body and material
  81552. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  81553. var bodyCreationObject = {
  81554. mass: impostor.getParam("mass"),
  81555. material: material
  81556. };
  81557. // A simple extend, in case native options were used.
  81558. var nativeOptions = impostor.getParam("nativeOptions");
  81559. for (var key in nativeOptions) {
  81560. if (nativeOptions.hasOwnProperty(key)) {
  81561. bodyCreationObject[key] = nativeOptions[key];
  81562. }
  81563. }
  81564. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  81565. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  81566. this.world.addEventListener("preStep", impostor.beforeStep);
  81567. this.world.addEventListener("postStep", impostor.afterStep);
  81568. impostor.physicsBody.addShape(shape);
  81569. this.world.add(impostor.physicsBody);
  81570. //try to keep the body moving in the right direction by taking old properties.
  81571. //Should be tested!
  81572. if (oldBody) {
  81573. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  81574. impostor.physicsBody[param].copy(oldBody[param]);
  81575. });
  81576. }
  81577. this._processChildMeshes(impostor);
  81578. }
  81579. //now update the body's transformation
  81580. this._updatePhysicsBodyTransformation(impostor);
  81581. };
  81582. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  81583. var _this = this;
  81584. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  81585. var currentRotation = mainImpostor.object.rotationQuaternion;
  81586. if (meshChildren.length) {
  81587. var processMesh = function (localPosition, mesh) {
  81588. if (!currentRotation || !mesh.rotationQuaternion) {
  81589. return;
  81590. }
  81591. var childImpostor = mesh.getPhysicsImpostor();
  81592. if (childImpostor) {
  81593. var parent = childImpostor.parent;
  81594. if (parent !== mainImpostor) {
  81595. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  81596. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  81597. if (childImpostor.physicsBody) {
  81598. _this.removePhysicsBody(childImpostor);
  81599. childImpostor.physicsBody = null;
  81600. }
  81601. childImpostor.parent = mainImpostor;
  81602. childImpostor.resetUpdateFlags();
  81603. 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));
  81604. //Add the mass of the children.
  81605. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  81606. }
  81607. }
  81608. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  81609. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  81610. };
  81611. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  81612. }
  81613. };
  81614. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81615. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  81616. this.world.removeEventListener("preStep", impostor.beforeStep);
  81617. this.world.removeEventListener("postStep", impostor.afterStep);
  81618. this.world.remove(impostor.physicsBody);
  81619. };
  81620. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81621. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81622. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81623. if (!mainBody || !connectedBody) {
  81624. return;
  81625. }
  81626. var constraint;
  81627. var jointData = impostorJoint.joint.jointData;
  81628. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  81629. var constraintData = {
  81630. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  81631. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  81632. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  81633. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  81634. maxForce: jointData.nativeParams.maxForce,
  81635. collideConnected: !!jointData.collision
  81636. };
  81637. switch (impostorJoint.joint.type) {
  81638. case BABYLON.PhysicsJoint.HingeJoint:
  81639. case BABYLON.PhysicsJoint.Hinge2Joint:
  81640. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  81641. break;
  81642. case BABYLON.PhysicsJoint.DistanceJoint:
  81643. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  81644. break;
  81645. case BABYLON.PhysicsJoint.SpringJoint:
  81646. var springData = jointData;
  81647. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  81648. restLength: springData.length,
  81649. stiffness: springData.stiffness,
  81650. damping: springData.damping,
  81651. localAnchorA: constraintData.pivotA,
  81652. localAnchorB: constraintData.pivotB
  81653. });
  81654. break;
  81655. case BABYLON.PhysicsJoint.LockJoint:
  81656. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  81657. break;
  81658. case BABYLON.PhysicsJoint.PointToPointJoint:
  81659. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81660. default:
  81661. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  81662. break;
  81663. }
  81664. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  81665. constraint.collideConnected = !!jointData.collision;
  81666. impostorJoint.joint.physicsJoint = constraint;
  81667. //don't add spring as constraint, as it is not one.
  81668. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  81669. this.world.addConstraint(constraint);
  81670. }
  81671. else {
  81672. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  81673. constraint.applyForce();
  81674. });
  81675. }
  81676. };
  81677. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  81678. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  81679. };
  81680. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  81681. var index;
  81682. var mat;
  81683. for (index = 0; index < this._physicsMaterials.length; index++) {
  81684. mat = this._physicsMaterials[index];
  81685. if (mat.friction === friction && mat.restitution === restitution) {
  81686. return mat;
  81687. }
  81688. }
  81689. var currentMat = new this.BJSCANNON.Material(name);
  81690. currentMat.friction = friction;
  81691. currentMat.restitution = restitution;
  81692. this._physicsMaterials.push(currentMat);
  81693. return currentMat;
  81694. };
  81695. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  81696. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  81697. };
  81698. CannonJSPlugin.prototype._createShape = function (impostor) {
  81699. var object = impostor.object;
  81700. var returnValue;
  81701. var extendSize = impostor.getObjectExtendSize();
  81702. switch (impostor.type) {
  81703. case BABYLON.PhysicsImpostor.SphereImpostor:
  81704. var radiusX = extendSize.x;
  81705. var radiusY = extendSize.y;
  81706. var radiusZ = extendSize.z;
  81707. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  81708. break;
  81709. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  81710. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81711. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  81712. break;
  81713. case BABYLON.PhysicsImpostor.BoxImpostor:
  81714. var box = extendSize.scale(0.5);
  81715. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  81716. break;
  81717. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81718. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  81719. returnValue = new this.BJSCANNON.Plane();
  81720. break;
  81721. case BABYLON.PhysicsImpostor.MeshImpostor:
  81722. // should transform the vertex data to world coordinates!!
  81723. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  81724. var rawFaces = object.getIndices ? object.getIndices() : [];
  81725. if (!rawVerts)
  81726. return;
  81727. // get only scale! so the object could transform correctly.
  81728. var oldPosition = object.position.clone();
  81729. var oldRotation = object.rotation && object.rotation.clone();
  81730. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  81731. object.position.copyFromFloats(0, 0, 0);
  81732. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81733. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81734. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81735. var transform = object.computeWorldMatrix(true);
  81736. // convert rawVerts to object space
  81737. var temp = new Array();
  81738. var index;
  81739. for (index = 0; index < rawVerts.length; index += 3) {
  81740. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  81741. }
  81742. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  81743. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  81744. //now set back the transformation!
  81745. object.position.copyFrom(oldPosition);
  81746. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  81747. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  81748. break;
  81749. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  81750. var oldPosition2 = object.position.clone();
  81751. var oldRotation2 = object.rotation && object.rotation.clone();
  81752. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  81753. object.position.copyFromFloats(0, 0, 0);
  81754. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81755. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81756. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81757. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  81758. returnValue = this._createHeightmap(object);
  81759. object.position.copyFrom(oldPosition2);
  81760. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  81761. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  81762. object.computeWorldMatrix(true);
  81763. break;
  81764. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81765. returnValue = new this.BJSCANNON.Particle();
  81766. break;
  81767. }
  81768. return returnValue;
  81769. };
  81770. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  81771. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81772. var transform = object.computeWorldMatrix(true);
  81773. // convert rawVerts to object space
  81774. var temp = new Array();
  81775. var index;
  81776. for (index = 0; index < pos.length; index += 3) {
  81777. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  81778. }
  81779. pos = temp;
  81780. var matrix = new Array();
  81781. //For now pointDepth will not be used and will be automatically calculated.
  81782. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  81783. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  81784. var boundingInfo = object.getBoundingInfo();
  81785. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  81786. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  81787. var elementSize = dim * 2 / arraySize;
  81788. for (var i = 0; i < pos.length; i = i + 3) {
  81789. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  81790. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  81791. var y = -pos[i + 2] + minY;
  81792. if (!matrix[x]) {
  81793. matrix[x] = [];
  81794. }
  81795. if (!matrix[x][z]) {
  81796. matrix[x][z] = y;
  81797. }
  81798. matrix[x][z] = Math.max(y, matrix[x][z]);
  81799. }
  81800. for (var x = 0; x <= arraySize; ++x) {
  81801. if (!matrix[x]) {
  81802. var loc = 1;
  81803. while (!matrix[(x + loc) % arraySize]) {
  81804. loc++;
  81805. }
  81806. matrix[x] = matrix[(x + loc) % arraySize].slice();
  81807. //console.log("missing x", x);
  81808. }
  81809. for (var z = 0; z <= arraySize; ++z) {
  81810. if (!matrix[x][z]) {
  81811. var loc = 1;
  81812. var newValue;
  81813. while (newValue === undefined) {
  81814. newValue = matrix[x][(z + loc++) % arraySize];
  81815. }
  81816. matrix[x][z] = newValue;
  81817. }
  81818. }
  81819. }
  81820. var shape = new this.BJSCANNON.Heightfield(matrix, {
  81821. elementSize: elementSize
  81822. });
  81823. //For future reference, needed for body transformation
  81824. shape.minY = minY;
  81825. return shape;
  81826. };
  81827. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  81828. var object = impostor.object;
  81829. //make sure it is updated...
  81830. object.computeWorldMatrix && object.computeWorldMatrix(true);
  81831. // The delta between the mesh position and the mesh bounding box center
  81832. var bInfo = object.getBoundingInfo();
  81833. if (!bInfo)
  81834. return;
  81835. var center = impostor.getObjectCenter();
  81836. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  81837. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  81838. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  81839. this._tmpPosition.copyFrom(center);
  81840. var quaternion = object.rotationQuaternion;
  81841. if (!quaternion) {
  81842. return;
  81843. }
  81844. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  81845. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  81846. //-90 DEG in X, precalculated
  81847. quaternion = quaternion.multiply(this._minus90X);
  81848. //Invert! (Precalculated, 90 deg in X)
  81849. //No need to clone. this will never change.
  81850. impostor.setDeltaRotation(this._plus90X);
  81851. }
  81852. //If it is a heightfield, if should be centered.
  81853. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  81854. var mesh = object;
  81855. var boundingInfo = mesh.getBoundingInfo();
  81856. //calculate the correct body position:
  81857. var rotationQuaternion = mesh.rotationQuaternion;
  81858. mesh.rotationQuaternion = this._tmpUnityRotation;
  81859. mesh.computeWorldMatrix(true);
  81860. //get original center with no rotation
  81861. var c = center.clone();
  81862. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  81863. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  81864. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  81865. mesh.setPreTransformMatrix(p);
  81866. mesh.computeWorldMatrix(true);
  81867. //calculate the translation
  81868. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  81869. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  81870. //add it inverted to the delta
  81871. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  81872. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  81873. //rotation is back
  81874. mesh.rotationQuaternion = rotationQuaternion;
  81875. mesh.setPreTransformMatrix(oldPivot);
  81876. mesh.computeWorldMatrix(true);
  81877. }
  81878. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  81879. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  81880. //this._tmpPosition.copyFrom(object.position);
  81881. }
  81882. impostor.setDeltaPosition(this._tmpDeltaPosition);
  81883. //Now update the impostor object
  81884. impostor.physicsBody.position.copy(this._tmpPosition);
  81885. impostor.physicsBody.quaternion.copy(quaternion);
  81886. };
  81887. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81888. impostor.object.position.copyFrom(impostor.physicsBody.position);
  81889. if (impostor.object.rotationQuaternion) {
  81890. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  81891. }
  81892. };
  81893. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81894. impostor.physicsBody.position.copy(newPosition);
  81895. impostor.physicsBody.quaternion.copy(newRotation);
  81896. };
  81897. CannonJSPlugin.prototype.isSupported = function () {
  81898. return this.BJSCANNON !== undefined;
  81899. };
  81900. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  81901. impostor.physicsBody.velocity.copy(velocity);
  81902. };
  81903. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  81904. impostor.physicsBody.angularVelocity.copy(velocity);
  81905. };
  81906. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  81907. var v = impostor.physicsBody.velocity;
  81908. if (!v) {
  81909. return null;
  81910. }
  81911. return new BABYLON.Vector3(v.x, v.y, v.z);
  81912. };
  81913. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  81914. var v = impostor.physicsBody.angularVelocity;
  81915. if (!v) {
  81916. return null;
  81917. }
  81918. return new BABYLON.Vector3(v.x, v.y, v.z);
  81919. };
  81920. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  81921. impostor.physicsBody.mass = mass;
  81922. impostor.physicsBody.updateMassProperties();
  81923. };
  81924. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  81925. return impostor.physicsBody.mass;
  81926. };
  81927. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  81928. return impostor.physicsBody.material.friction;
  81929. };
  81930. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  81931. impostor.physicsBody.material.friction = friction;
  81932. };
  81933. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  81934. return impostor.physicsBody.material.restitution;
  81935. };
  81936. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  81937. impostor.physicsBody.material.restitution = restitution;
  81938. };
  81939. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  81940. impostor.physicsBody.sleep();
  81941. };
  81942. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  81943. impostor.physicsBody.wakeUp();
  81944. };
  81945. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  81946. joint.physicsJoint.distance = maxDistance;
  81947. };
  81948. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81949. // if (!motorIndex) {
  81950. // joint.physicsJoint.enableMotor();
  81951. // }
  81952. // }
  81953. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81954. // if (!motorIndex) {
  81955. // joint.physicsJoint.disableMotor();
  81956. // }
  81957. // }
  81958. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  81959. if (!motorIndex) {
  81960. joint.physicsJoint.enableMotor();
  81961. joint.physicsJoint.setMotorSpeed(speed);
  81962. if (maxForce) {
  81963. this.setLimit(joint, maxForce);
  81964. }
  81965. }
  81966. };
  81967. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  81968. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  81969. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  81970. };
  81971. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  81972. var body = impostor.physicsBody;
  81973. mesh.position.x = body.position.x;
  81974. mesh.position.y = body.position.y;
  81975. mesh.position.z = body.position.z;
  81976. if (mesh.rotationQuaternion) {
  81977. mesh.rotationQuaternion.x = body.quaternion.x;
  81978. mesh.rotationQuaternion.y = body.quaternion.y;
  81979. mesh.rotationQuaternion.z = body.quaternion.z;
  81980. mesh.rotationQuaternion.w = body.quaternion.w;
  81981. }
  81982. };
  81983. CannonJSPlugin.prototype.getRadius = function (impostor) {
  81984. var shape = impostor.physicsBody.shapes[0];
  81985. return shape.boundingSphereRadius;
  81986. };
  81987. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  81988. var shape = impostor.physicsBody.shapes[0];
  81989. result.x = shape.halfExtents.x * 2;
  81990. result.y = shape.halfExtents.y * 2;
  81991. result.z = shape.halfExtents.z * 2;
  81992. };
  81993. CannonJSPlugin.prototype.dispose = function () {
  81994. };
  81995. CannonJSPlugin.prototype._extendNamespace = function () {
  81996. //this will force cannon to execute at least one step when using interpolation
  81997. var step_tmp1 = new this.BJSCANNON.Vec3();
  81998. var Engine = this.BJSCANNON;
  81999. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  82000. maxSubSteps = maxSubSteps || 10;
  82001. timeSinceLastCalled = timeSinceLastCalled || 0;
  82002. if (timeSinceLastCalled === 0) {
  82003. this.internalStep(dt);
  82004. this.time += dt;
  82005. }
  82006. else {
  82007. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  82008. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  82009. var t0 = performance.now();
  82010. for (var i = 0; i !== internalSteps; i++) {
  82011. this.internalStep(dt);
  82012. if (performance.now() - t0 > dt * 1000) {
  82013. break;
  82014. }
  82015. }
  82016. this.time += timeSinceLastCalled;
  82017. var h = this.time % dt;
  82018. var h_div_dt = h / dt;
  82019. var interpvelo = step_tmp1;
  82020. var bodies = this.bodies;
  82021. for (var j = 0; j !== bodies.length; j++) {
  82022. var b = bodies[j];
  82023. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  82024. b.position.vsub(b.previousPosition, interpvelo);
  82025. interpvelo.scale(h_div_dt, interpvelo);
  82026. b.position.vadd(interpvelo, b.interpolatedPosition);
  82027. }
  82028. else {
  82029. b.interpolatedPosition.copy(b.position);
  82030. b.interpolatedQuaternion.copy(b.quaternion);
  82031. }
  82032. }
  82033. }
  82034. };
  82035. };
  82036. return CannonJSPlugin;
  82037. }());
  82038. BABYLON.CannonJSPlugin = CannonJSPlugin;
  82039. })(BABYLON || (BABYLON = {}));
  82040. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  82041. "use strict";
  82042. var BABYLON;
  82043. (function (BABYLON) {
  82044. var OimoJSPlugin = /** @class */ (function () {
  82045. function OimoJSPlugin(iterations) {
  82046. this.name = "OimoJSPlugin";
  82047. this._tmpImpostorsArray = [];
  82048. this._tmpPositionVector = BABYLON.Vector3.Zero();
  82049. this.BJSOIMO = OIMO;
  82050. this.world = new this.BJSOIMO.World({
  82051. iterations: iterations
  82052. });
  82053. this.world.clear();
  82054. }
  82055. OimoJSPlugin.prototype.setGravity = function (gravity) {
  82056. this.world.gravity.copy(gravity);
  82057. };
  82058. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  82059. this.world.timeStep = timeStep;
  82060. };
  82061. OimoJSPlugin.prototype.getTimeStep = function () {
  82062. return this.world.timeStep;
  82063. };
  82064. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  82065. var _this = this;
  82066. impostors.forEach(function (impostor) {
  82067. impostor.beforeStep();
  82068. });
  82069. this.world.step();
  82070. impostors.forEach(function (impostor) {
  82071. impostor.afterStep();
  82072. //update the ordered impostors array
  82073. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  82074. });
  82075. //check for collisions
  82076. var contact = this.world.contacts;
  82077. while (contact !== null) {
  82078. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  82079. contact = contact.next;
  82080. continue;
  82081. }
  82082. //is this body colliding with any other? get the impostor
  82083. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  82084. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  82085. if (!mainImpostor || !collidingImpostor) {
  82086. contact = contact.next;
  82087. continue;
  82088. }
  82089. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  82090. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  82091. contact = contact.next;
  82092. }
  82093. };
  82094. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82095. var mass = impostor.physicsBody.mass;
  82096. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  82097. };
  82098. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82099. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  82100. this.applyImpulse(impostor, force, contactPoint);
  82101. };
  82102. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82103. var _this = this;
  82104. //parent-child relationship. Does this impostor has a parent impostor?
  82105. if (impostor.parent) {
  82106. if (impostor.physicsBody) {
  82107. this.removePhysicsBody(impostor);
  82108. //TODO is that needed?
  82109. impostor.forceUpdate();
  82110. }
  82111. return;
  82112. }
  82113. if (impostor.isBodyInitRequired()) {
  82114. var bodyConfig = {
  82115. name: impostor.uniqueId,
  82116. //Oimo must have mass, also for static objects.
  82117. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  82118. size: [],
  82119. type: [],
  82120. pos: [],
  82121. posShape: [],
  82122. rot: [],
  82123. rotShape: [],
  82124. move: impostor.getParam("mass") !== 0,
  82125. density: impostor.getParam("mass"),
  82126. friction: impostor.getParam("friction"),
  82127. restitution: impostor.getParam("restitution"),
  82128. //Supporting older versions of Oimo
  82129. world: this.world
  82130. };
  82131. var impostors = [impostor];
  82132. var addToArray = function (parent) {
  82133. if (!parent.getChildMeshes)
  82134. return;
  82135. parent.getChildMeshes().forEach(function (m) {
  82136. if (m.physicsImpostor) {
  82137. impostors.push(m.physicsImpostor);
  82138. //m.physicsImpostor._init();
  82139. }
  82140. });
  82141. };
  82142. addToArray(impostor.object);
  82143. var checkWithEpsilon_1 = function (value) {
  82144. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  82145. };
  82146. impostors.forEach(function (i) {
  82147. if (!i.object.rotationQuaternion) {
  82148. return;
  82149. }
  82150. //get the correct bounding box
  82151. var oldQuaternion = i.object.rotationQuaternion;
  82152. var rot = oldQuaternion.toEulerAngles();
  82153. var extendSize = i.getObjectExtendSize();
  82154. var radToDeg = 57.295779513082320876;
  82155. if (i === impostor) {
  82156. var center = impostor.getObjectCenter();
  82157. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  82158. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  82159. //Can also use Array.prototype.push.apply
  82160. bodyConfig.pos.push(center.x);
  82161. bodyConfig.pos.push(center.y);
  82162. bodyConfig.pos.push(center.z);
  82163. bodyConfig.posShape.push(0, 0, 0);
  82164. //tmp solution
  82165. bodyConfig.rot.push(rot.x * radToDeg);
  82166. bodyConfig.rot.push(rot.y * radToDeg);
  82167. bodyConfig.rot.push(rot.z * radToDeg);
  82168. bodyConfig.rotShape.push(0, 0, 0);
  82169. }
  82170. else {
  82171. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  82172. bodyConfig.posShape.push(localPosition.x);
  82173. bodyConfig.posShape.push(localPosition.y);
  82174. bodyConfig.posShape.push(localPosition.z);
  82175. bodyConfig.pos.push(0, 0, 0);
  82176. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  82177. bodyConfig.rot.push(0);
  82178. bodyConfig.rot.push(0);
  82179. bodyConfig.rot.push(0);
  82180. bodyConfig.rotShape.push(rot.x * radToDeg);
  82181. bodyConfig.rotShape.push(rot.y * radToDeg);
  82182. bodyConfig.rotShape.push(rot.z * radToDeg);
  82183. }
  82184. // register mesh
  82185. switch (i.type) {
  82186. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82187. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  82188. case BABYLON.PhysicsImpostor.SphereImpostor:
  82189. var radiusX = extendSize.x;
  82190. var radiusY = extendSize.y;
  82191. var radiusZ = extendSize.z;
  82192. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  82193. bodyConfig.type.push('sphere');
  82194. //due to the way oimo works with compounds, add 3 times
  82195. bodyConfig.size.push(size);
  82196. bodyConfig.size.push(size);
  82197. bodyConfig.size.push(size);
  82198. break;
  82199. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82200. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  82201. var sizeY = checkWithEpsilon_1(extendSize.y);
  82202. bodyConfig.type.push('cylinder');
  82203. bodyConfig.size.push(sizeX);
  82204. bodyConfig.size.push(sizeY);
  82205. //due to the way oimo works with compounds, add one more value.
  82206. bodyConfig.size.push(sizeY);
  82207. break;
  82208. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82209. case BABYLON.PhysicsImpostor.BoxImpostor:
  82210. default:
  82211. var sizeX = checkWithEpsilon_1(extendSize.x);
  82212. var sizeY = checkWithEpsilon_1(extendSize.y);
  82213. var sizeZ = checkWithEpsilon_1(extendSize.z);
  82214. bodyConfig.type.push('box');
  82215. //if (i === impostor) {
  82216. bodyConfig.size.push(sizeX);
  82217. bodyConfig.size.push(sizeY);
  82218. bodyConfig.size.push(sizeZ);
  82219. //} else {
  82220. // bodyConfig.size.push(0,0,0);
  82221. //}
  82222. break;
  82223. }
  82224. //actually not needed, but hey...
  82225. i.object.rotationQuaternion = oldQuaternion;
  82226. });
  82227. impostor.physicsBody = this.world.add(bodyConfig);
  82228. }
  82229. else {
  82230. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  82231. }
  82232. impostor.setDeltaPosition(this._tmpPositionVector);
  82233. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  82234. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  82235. };
  82236. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82237. //impostor.physicsBody.dispose();
  82238. //Same as : (older oimo versions)
  82239. this.world.removeRigidBody(impostor.physicsBody);
  82240. };
  82241. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82242. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82243. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82244. if (!mainBody || !connectedBody) {
  82245. return;
  82246. }
  82247. var jointData = impostorJoint.joint.jointData;
  82248. var options = jointData.nativeParams || {};
  82249. var type;
  82250. var nativeJointData = {
  82251. body1: mainBody,
  82252. body2: connectedBody,
  82253. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  82254. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  82255. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  82256. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  82257. min: options.min,
  82258. max: options.max,
  82259. collision: options.collision || jointData.collision,
  82260. spring: options.spring,
  82261. //supporting older version of Oimo
  82262. world: this.world
  82263. };
  82264. switch (impostorJoint.joint.type) {
  82265. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82266. type = "jointBall";
  82267. break;
  82268. case BABYLON.PhysicsJoint.SpringJoint:
  82269. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  82270. var springData = jointData;
  82271. nativeJointData.min = springData.length || nativeJointData.min;
  82272. //Max should also be set, just make sure it is at least min
  82273. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  82274. case BABYLON.PhysicsJoint.DistanceJoint:
  82275. type = "jointDistance";
  82276. nativeJointData.max = jointData.maxDistance;
  82277. break;
  82278. case BABYLON.PhysicsJoint.PrismaticJoint:
  82279. type = "jointPrisme";
  82280. break;
  82281. case BABYLON.PhysicsJoint.SliderJoint:
  82282. type = "jointSlide";
  82283. break;
  82284. case BABYLON.PhysicsJoint.WheelJoint:
  82285. type = "jointWheel";
  82286. break;
  82287. case BABYLON.PhysicsJoint.HingeJoint:
  82288. default:
  82289. type = "jointHinge";
  82290. break;
  82291. }
  82292. nativeJointData.type = type;
  82293. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  82294. };
  82295. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82296. //Bug in Oimo prevents us from disposing a joint in the playground
  82297. //joint.joint.physicsJoint.dispose();
  82298. //So we will bruteforce it!
  82299. try {
  82300. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  82301. }
  82302. catch (e) {
  82303. BABYLON.Tools.Warn(e);
  82304. }
  82305. };
  82306. OimoJSPlugin.prototype.isSupported = function () {
  82307. return this.BJSOIMO !== undefined;
  82308. };
  82309. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82310. if (!impostor.physicsBody.sleeping) {
  82311. //TODO check that
  82312. /*if (impostor.physicsBody.shapes.next) {
  82313. var parentShape = this._getLastShape(impostor.physicsBody);
  82314. impostor.object.position.copyFrom(parentShape.position);
  82315. console.log(parentShape.position);
  82316. } else {*/
  82317. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  82318. //}
  82319. if (impostor.object.rotationQuaternion) {
  82320. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  82321. }
  82322. }
  82323. };
  82324. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82325. var body = impostor.physicsBody;
  82326. body.position.copy(newPosition);
  82327. body.orientation.copy(newRotation);
  82328. body.syncShapes();
  82329. body.awake();
  82330. };
  82331. /*private _getLastShape(body: any): any {
  82332. var lastShape = body.shapes;
  82333. while (lastShape.next) {
  82334. lastShape = lastShape.next;
  82335. }
  82336. return lastShape;
  82337. }*/
  82338. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82339. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  82340. };
  82341. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82342. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  82343. };
  82344. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82345. var v = impostor.physicsBody.linearVelocity;
  82346. if (!v) {
  82347. return null;
  82348. }
  82349. return new BABYLON.Vector3(v.x, v.y, v.z);
  82350. };
  82351. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82352. var v = impostor.physicsBody.angularVelocity;
  82353. if (!v) {
  82354. return null;
  82355. }
  82356. return new BABYLON.Vector3(v.x, v.y, v.z);
  82357. };
  82358. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82359. var staticBody = mass === 0;
  82360. //this will actually set the body's density and not its mass.
  82361. //But this is how oimo treats the mass variable.
  82362. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  82363. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  82364. };
  82365. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  82366. return impostor.physicsBody.shapes.density;
  82367. };
  82368. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  82369. return impostor.physicsBody.shapes.friction;
  82370. };
  82371. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82372. impostor.physicsBody.shapes.friction = friction;
  82373. };
  82374. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82375. return impostor.physicsBody.shapes.restitution;
  82376. };
  82377. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82378. impostor.physicsBody.shapes.restitution = restitution;
  82379. };
  82380. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  82381. impostor.physicsBody.sleep();
  82382. };
  82383. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  82384. impostor.physicsBody.awake();
  82385. };
  82386. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82387. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  82388. if (minDistance !== void 0) {
  82389. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  82390. }
  82391. };
  82392. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82393. //TODO separate rotational and transational motors.
  82394. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82395. if (motor) {
  82396. motor.setMotor(speed, maxForce);
  82397. }
  82398. };
  82399. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  82400. //TODO separate rotational and transational motors.
  82401. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82402. if (motor) {
  82403. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  82404. }
  82405. };
  82406. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82407. var body = impostor.physicsBody;
  82408. mesh.position.x = body.position.x;
  82409. mesh.position.y = body.position.y;
  82410. mesh.position.z = body.position.z;
  82411. if (mesh.rotationQuaternion) {
  82412. mesh.rotationQuaternion.x = body.orientation.x;
  82413. mesh.rotationQuaternion.y = body.orientation.y;
  82414. mesh.rotationQuaternion.z = body.orientation.z;
  82415. mesh.rotationQuaternion.w = body.orientation.s;
  82416. }
  82417. };
  82418. OimoJSPlugin.prototype.getRadius = function (impostor) {
  82419. return impostor.physicsBody.shapes.radius;
  82420. };
  82421. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82422. var shape = impostor.physicsBody.shapes;
  82423. result.x = shape.halfWidth * 2;
  82424. result.y = shape.halfHeight * 2;
  82425. result.z = shape.halfDepth * 2;
  82426. };
  82427. OimoJSPlugin.prototype.dispose = function () {
  82428. this.world.clear();
  82429. };
  82430. return OimoJSPlugin;
  82431. }());
  82432. BABYLON.OimoJSPlugin = OimoJSPlugin;
  82433. })(BABYLON || (BABYLON = {}));
  82434. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  82435. "use strict";
  82436. var BABYLON;
  82437. (function (BABYLON) {
  82438. /*
  82439. * Based on jsTGALoader - Javascript loader for TGA file
  82440. * By Vincent Thibault
  82441. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  82442. */
  82443. var TGATools = /** @class */ (function () {
  82444. function TGATools() {
  82445. }
  82446. TGATools.GetTGAHeader = function (data) {
  82447. var offset = 0;
  82448. var header = {
  82449. id_length: data[offset++],
  82450. colormap_type: data[offset++],
  82451. image_type: data[offset++],
  82452. colormap_index: data[offset++] | data[offset++] << 8,
  82453. colormap_length: data[offset++] | data[offset++] << 8,
  82454. colormap_size: data[offset++],
  82455. origin: [
  82456. data[offset++] | data[offset++] << 8,
  82457. data[offset++] | data[offset++] << 8
  82458. ],
  82459. width: data[offset++] | data[offset++] << 8,
  82460. height: data[offset++] | data[offset++] << 8,
  82461. pixel_size: data[offset++],
  82462. flags: data[offset++]
  82463. };
  82464. return header;
  82465. };
  82466. TGATools.UploadContent = function (gl, data) {
  82467. // Not enough data to contain header ?
  82468. if (data.length < 19) {
  82469. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  82470. return;
  82471. }
  82472. // Read Header
  82473. var offset = 18;
  82474. var header = TGATools.GetTGAHeader(data);
  82475. // Assume it's a valid Targa file.
  82476. if (header.id_length + offset > data.length) {
  82477. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  82478. return;
  82479. }
  82480. // Skip not needed data
  82481. offset += header.id_length;
  82482. var use_rle = false;
  82483. var use_pal = false;
  82484. var use_grey = false;
  82485. // Get some informations.
  82486. switch (header.image_type) {
  82487. case TGATools._TYPE_RLE_INDEXED:
  82488. use_rle = true;
  82489. case TGATools._TYPE_INDEXED:
  82490. use_pal = true;
  82491. break;
  82492. case TGATools._TYPE_RLE_RGB:
  82493. use_rle = true;
  82494. case TGATools._TYPE_RGB:
  82495. // use_rgb = true;
  82496. break;
  82497. case TGATools._TYPE_RLE_GREY:
  82498. use_rle = true;
  82499. case TGATools._TYPE_GREY:
  82500. use_grey = true;
  82501. break;
  82502. }
  82503. var pixel_data;
  82504. // var numAlphaBits = header.flags & 0xf;
  82505. var pixel_size = header.pixel_size >> 3;
  82506. var pixel_total = header.width * header.height * pixel_size;
  82507. // Read palettes
  82508. var palettes;
  82509. if (use_pal) {
  82510. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  82511. }
  82512. // Read LRE
  82513. if (use_rle) {
  82514. pixel_data = new Uint8Array(pixel_total);
  82515. var c, count, i;
  82516. var localOffset = 0;
  82517. var pixels = new Uint8Array(pixel_size);
  82518. while (offset < pixel_total && localOffset < pixel_total) {
  82519. c = data[offset++];
  82520. count = (c & 0x7f) + 1;
  82521. // RLE pixels
  82522. if (c & 0x80) {
  82523. // Bind pixel tmp array
  82524. for (i = 0; i < pixel_size; ++i) {
  82525. pixels[i] = data[offset++];
  82526. }
  82527. // Copy pixel array
  82528. for (i = 0; i < count; ++i) {
  82529. pixel_data.set(pixels, localOffset + i * pixel_size);
  82530. }
  82531. localOffset += pixel_size * count;
  82532. }
  82533. else {
  82534. count *= pixel_size;
  82535. for (i = 0; i < count; ++i) {
  82536. pixel_data[localOffset + i] = data[offset++];
  82537. }
  82538. localOffset += count;
  82539. }
  82540. }
  82541. }
  82542. else {
  82543. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  82544. }
  82545. // Load to texture
  82546. var x_start, y_start, x_step, y_step, y_end, x_end;
  82547. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  82548. default:
  82549. case TGATools._ORIGIN_UL:
  82550. x_start = 0;
  82551. x_step = 1;
  82552. x_end = header.width;
  82553. y_start = 0;
  82554. y_step = 1;
  82555. y_end = header.height;
  82556. break;
  82557. case TGATools._ORIGIN_BL:
  82558. x_start = 0;
  82559. x_step = 1;
  82560. x_end = header.width;
  82561. y_start = header.height - 1;
  82562. y_step = -1;
  82563. y_end = -1;
  82564. break;
  82565. case TGATools._ORIGIN_UR:
  82566. x_start = header.width - 1;
  82567. x_step = -1;
  82568. x_end = -1;
  82569. y_start = 0;
  82570. y_step = 1;
  82571. y_end = header.height;
  82572. break;
  82573. case TGATools._ORIGIN_BR:
  82574. x_start = header.width - 1;
  82575. x_step = -1;
  82576. x_end = -1;
  82577. y_start = header.height - 1;
  82578. y_step = -1;
  82579. y_end = -1;
  82580. break;
  82581. }
  82582. // Load the specify method
  82583. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  82584. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  82585. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  82586. };
  82587. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82588. var image = pixel_data, colormap = palettes;
  82589. var width = header.width, height = header.height;
  82590. var color, i = 0, x, y;
  82591. var imageData = new Uint8Array(width * height * 4);
  82592. for (y = y_start; y !== y_end; y += y_step) {
  82593. for (x = x_start; x !== x_end; x += x_step, i++) {
  82594. color = image[i];
  82595. imageData[(x + width * y) * 4 + 3] = 255;
  82596. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  82597. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  82598. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  82599. }
  82600. }
  82601. return imageData;
  82602. };
  82603. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82604. var image = pixel_data;
  82605. var width = header.width, height = header.height;
  82606. var color, i = 0, x, y;
  82607. var imageData = new Uint8Array(width * height * 4);
  82608. for (y = y_start; y !== y_end; y += y_step) {
  82609. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82610. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  82611. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  82612. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  82613. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  82614. imageData[(x + width * y) * 4 + 0] = r;
  82615. imageData[(x + width * y) * 4 + 1] = g;
  82616. imageData[(x + width * y) * 4 + 2] = b;
  82617. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  82618. }
  82619. }
  82620. return imageData;
  82621. };
  82622. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82623. var image = pixel_data;
  82624. var width = header.width, height = header.height;
  82625. var i = 0, x, y;
  82626. var imageData = new Uint8Array(width * height * 4);
  82627. for (y = y_start; y !== y_end; y += y_step) {
  82628. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  82629. imageData[(x + width * y) * 4 + 3] = 255;
  82630. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82631. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82632. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82633. }
  82634. }
  82635. return imageData;
  82636. };
  82637. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82638. var image = pixel_data;
  82639. var width = header.width, height = header.height;
  82640. var i = 0, x, y;
  82641. var imageData = new Uint8Array(width * height * 4);
  82642. for (y = y_start; y !== y_end; y += y_step) {
  82643. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  82644. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82645. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82646. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82647. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  82648. }
  82649. }
  82650. return imageData;
  82651. };
  82652. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82653. var image = pixel_data;
  82654. var width = header.width, height = header.height;
  82655. var color, i = 0, x, y;
  82656. var imageData = new Uint8Array(width * height * 4);
  82657. for (y = y_start; y !== y_end; y += y_step) {
  82658. for (x = x_start; x !== x_end; x += x_step, i++) {
  82659. color = image[i];
  82660. imageData[(x + width * y) * 4 + 0] = color;
  82661. imageData[(x + width * y) * 4 + 1] = color;
  82662. imageData[(x + width * y) * 4 + 2] = color;
  82663. imageData[(x + width * y) * 4 + 3] = 255;
  82664. }
  82665. }
  82666. return imageData;
  82667. };
  82668. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82669. var image = pixel_data;
  82670. var width = header.width, height = header.height;
  82671. var i = 0, x, y;
  82672. var imageData = new Uint8Array(width * height * 4);
  82673. for (y = y_start; y !== y_end; y += y_step) {
  82674. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82675. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  82676. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  82677. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82678. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  82679. }
  82680. }
  82681. return imageData;
  82682. };
  82683. //private static _TYPE_NO_DATA = 0;
  82684. TGATools._TYPE_INDEXED = 1;
  82685. TGATools._TYPE_RGB = 2;
  82686. TGATools._TYPE_GREY = 3;
  82687. TGATools._TYPE_RLE_INDEXED = 9;
  82688. TGATools._TYPE_RLE_RGB = 10;
  82689. TGATools._TYPE_RLE_GREY = 11;
  82690. TGATools._ORIGIN_MASK = 0x30;
  82691. TGATools._ORIGIN_SHIFT = 0x04;
  82692. TGATools._ORIGIN_BL = 0x00;
  82693. TGATools._ORIGIN_BR = 0x01;
  82694. TGATools._ORIGIN_UL = 0x02;
  82695. TGATools._ORIGIN_UR = 0x03;
  82696. return TGATools;
  82697. }());
  82698. BABYLON.TGATools = TGATools;
  82699. })(BABYLON || (BABYLON = {}));
  82700. //# sourceMappingURL=babylon.tga.js.map
  82701. "use strict";
  82702. var BABYLON;
  82703. (function (BABYLON) {
  82704. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  82705. // All values and structures referenced from:
  82706. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  82707. var DDS_MAGIC = 0x20534444;
  82708. var
  82709. //DDSD_CAPS = 0x1,
  82710. //DDSD_HEIGHT = 0x2,
  82711. //DDSD_WIDTH = 0x4,
  82712. //DDSD_PITCH = 0x8,
  82713. //DDSD_PIXELFORMAT = 0x1000,
  82714. DDSD_MIPMAPCOUNT = 0x20000;
  82715. //DDSD_LINEARSIZE = 0x80000,
  82716. //DDSD_DEPTH = 0x800000;
  82717. // var DDSCAPS_COMPLEX = 0x8,
  82718. // DDSCAPS_MIPMAP = 0x400000,
  82719. // DDSCAPS_TEXTURE = 0x1000;
  82720. var DDSCAPS2_CUBEMAP = 0x200;
  82721. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  82722. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  82723. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  82724. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  82725. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  82726. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  82727. // DDSCAPS2_VOLUME = 0x200000;
  82728. var
  82729. //DDPF_ALPHAPIXELS = 0x1,
  82730. //DDPF_ALPHA = 0x2,
  82731. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  82732. //DDPF_YUV = 0x200,
  82733. DDPF_LUMINANCE = 0x20000;
  82734. function FourCCToInt32(value) {
  82735. return value.charCodeAt(0) +
  82736. (value.charCodeAt(1) << 8) +
  82737. (value.charCodeAt(2) << 16) +
  82738. (value.charCodeAt(3) << 24);
  82739. }
  82740. function Int32ToFourCC(value) {
  82741. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  82742. }
  82743. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  82744. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  82745. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  82746. var FOURCC_DX10 = FourCCToInt32("DX10");
  82747. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  82748. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  82749. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  82750. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  82751. var headerLengthInt = 31; // The header length in 32 bit ints
  82752. // Offsets into the header array
  82753. var off_magic = 0;
  82754. var off_size = 1;
  82755. var off_flags = 2;
  82756. var off_height = 3;
  82757. var off_width = 4;
  82758. var off_mipmapCount = 7;
  82759. var off_pfFlags = 20;
  82760. var off_pfFourCC = 21;
  82761. var off_RGBbpp = 22;
  82762. var off_RMask = 23;
  82763. var off_GMask = 24;
  82764. var off_BMask = 25;
  82765. var off_AMask = 26;
  82766. // var off_caps1 = 27;
  82767. var off_caps2 = 28;
  82768. // var off_caps3 = 29;
  82769. // var off_caps4 = 30;
  82770. var off_dxgiFormat = 32;
  82771. ;
  82772. var DDSTools = /** @class */ (function () {
  82773. function DDSTools() {
  82774. }
  82775. DDSTools.GetDDSInfo = function (arrayBuffer) {
  82776. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82777. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  82778. var mipmapCount = 1;
  82779. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  82780. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82781. }
  82782. var fourCC = header[off_pfFourCC];
  82783. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  82784. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82785. switch (fourCC) {
  82786. case FOURCC_D3DFMT_R16G16B16A16F:
  82787. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82788. break;
  82789. case FOURCC_D3DFMT_R32G32B32A32F:
  82790. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82791. break;
  82792. case FOURCC_DX10:
  82793. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  82794. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82795. break;
  82796. }
  82797. }
  82798. return {
  82799. width: header[off_width],
  82800. height: header[off_height],
  82801. mipmapCount: mipmapCount,
  82802. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  82803. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  82804. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  82805. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  82806. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  82807. dxgiFormat: dxgiFormat,
  82808. textureType: textureType
  82809. };
  82810. };
  82811. DDSTools._ToHalfFloat = function (value) {
  82812. if (!DDSTools._FloatView) {
  82813. DDSTools._FloatView = new Float32Array(1);
  82814. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  82815. }
  82816. DDSTools._FloatView[0] = value;
  82817. var x = DDSTools._Int32View[0];
  82818. var bits = (x >> 16) & 0x8000; /* Get the sign */
  82819. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  82820. var e = (x >> 23) & 0xff; /* Using int is faster here */
  82821. /* If zero, or denormal, or exponent underflows too much for a denormal
  82822. * half, return signed zero. */
  82823. if (e < 103) {
  82824. return bits;
  82825. }
  82826. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  82827. if (e > 142) {
  82828. bits |= 0x7c00;
  82829. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  82830. * not Inf, so make sure we set one mantissa bit too. */
  82831. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  82832. return bits;
  82833. }
  82834. /* If exponent underflows but not too much, return a denormal */
  82835. if (e < 113) {
  82836. m |= 0x0800;
  82837. /* Extra rounding may overflow and set mantissa to 0 and exponent
  82838. * to 1, which is OK. */
  82839. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  82840. return bits;
  82841. }
  82842. bits |= ((e - 112) << 10) | (m >> 1);
  82843. bits += m & 1;
  82844. return bits;
  82845. };
  82846. DDSTools._FromHalfFloat = function (value) {
  82847. var s = (value & 0x8000) >> 15;
  82848. var e = (value & 0x7C00) >> 10;
  82849. var f = value & 0x03FF;
  82850. if (e === 0) {
  82851. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  82852. }
  82853. else if (e == 0x1F) {
  82854. return f ? NaN : ((s ? -1 : 1) * Infinity);
  82855. }
  82856. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  82857. };
  82858. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82859. var destArray = new Float32Array(dataLength);
  82860. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82861. var index = 0;
  82862. for (var y = 0; y < height; y++) {
  82863. for (var x = 0; x < width; x++) {
  82864. var srcPos = (x + y * width) * 4;
  82865. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  82866. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  82867. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  82868. if (DDSTools.StoreLODInAlphaChannel) {
  82869. destArray[index + 3] = lod;
  82870. }
  82871. else {
  82872. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  82873. }
  82874. index += 4;
  82875. }
  82876. }
  82877. return destArray;
  82878. };
  82879. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82880. if (DDSTools.StoreLODInAlphaChannel) {
  82881. var destArray = new Uint16Array(dataLength);
  82882. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82883. var index = 0;
  82884. for (var y = 0; y < height; y++) {
  82885. for (var x = 0; x < width; x++) {
  82886. var srcPos = (x + y * width) * 4;
  82887. destArray[index] = srcData[srcPos];
  82888. destArray[index + 1] = srcData[srcPos + 1];
  82889. destArray[index + 2] = srcData[srcPos + 2];
  82890. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  82891. index += 4;
  82892. }
  82893. }
  82894. return destArray;
  82895. }
  82896. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  82897. };
  82898. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82899. if (DDSTools.StoreLODInAlphaChannel) {
  82900. var destArray = new Float32Array(dataLength);
  82901. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82902. var index = 0;
  82903. for (var y = 0; y < height; y++) {
  82904. for (var x = 0; x < width; x++) {
  82905. var srcPos = (x + y * width) * 4;
  82906. destArray[index] = srcData[srcPos];
  82907. destArray[index + 1] = srcData[srcPos + 1];
  82908. destArray[index + 2] = srcData[srcPos + 2];
  82909. destArray[index + 3] = lod;
  82910. index += 4;
  82911. }
  82912. }
  82913. return destArray;
  82914. }
  82915. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  82916. };
  82917. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82918. var destArray = new Uint8Array(dataLength);
  82919. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82920. var index = 0;
  82921. for (var y = 0; y < height; y++) {
  82922. for (var x = 0; x < width; x++) {
  82923. var srcPos = (x + y * width) * 4;
  82924. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  82925. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  82926. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  82927. if (DDSTools.StoreLODInAlphaChannel) {
  82928. destArray[index + 3] = lod;
  82929. }
  82930. else {
  82931. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  82932. }
  82933. index += 4;
  82934. }
  82935. }
  82936. return destArray;
  82937. };
  82938. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82939. var destArray = new Uint8Array(dataLength);
  82940. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82941. var index = 0;
  82942. for (var y = 0; y < height; y++) {
  82943. for (var x = 0; x < width; x++) {
  82944. var srcPos = (x + y * width) * 4;
  82945. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  82946. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  82947. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  82948. if (DDSTools.StoreLODInAlphaChannel) {
  82949. destArray[index + 3] = lod;
  82950. }
  82951. else {
  82952. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  82953. }
  82954. index += 4;
  82955. }
  82956. }
  82957. return destArray;
  82958. };
  82959. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  82960. var byteArray = new Uint8Array(dataLength);
  82961. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82962. var index = 0;
  82963. for (var y = 0; y < height; y++) {
  82964. for (var x = 0; x < width; x++) {
  82965. var srcPos = (x + y * width) * 4;
  82966. byteArray[index] = srcData[srcPos + rOffset];
  82967. byteArray[index + 1] = srcData[srcPos + gOffset];
  82968. byteArray[index + 2] = srcData[srcPos + bOffset];
  82969. byteArray[index + 3] = srcData[srcPos + aOffset];
  82970. index += 4;
  82971. }
  82972. }
  82973. return byteArray;
  82974. };
  82975. DDSTools._ExtractLongWordOrder = function (value) {
  82976. if (value === 0 || value === 255 || value === -16777216) {
  82977. return 0;
  82978. }
  82979. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  82980. };
  82981. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  82982. var byteArray = new Uint8Array(dataLength);
  82983. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82984. var index = 0;
  82985. for (var y = 0; y < height; y++) {
  82986. for (var x = 0; x < width; x++) {
  82987. var srcPos = (x + y * width) * 3;
  82988. byteArray[index] = srcData[srcPos + rOffset];
  82989. byteArray[index + 1] = srcData[srcPos + gOffset];
  82990. byteArray[index + 2] = srcData[srcPos + bOffset];
  82991. index += 3;
  82992. }
  82993. }
  82994. return byteArray;
  82995. };
  82996. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  82997. var byteArray = new Uint8Array(dataLength);
  82998. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82999. var index = 0;
  83000. for (var y = 0; y < height; y++) {
  83001. for (var x = 0; x < width; x++) {
  83002. var srcPos = (x + y * width);
  83003. byteArray[index] = srcData[srcPos];
  83004. index++;
  83005. }
  83006. }
  83007. return byteArray;
  83008. };
  83009. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  83010. if (lodIndex === void 0) { lodIndex = -1; }
  83011. var ext = engine.getCaps().s3tc;
  83012. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83013. var fourCC, width, height, dataLength = 0, dataOffset;
  83014. var byteArray, mipmapCount, mip;
  83015. var internalFormat = 0;
  83016. var format = 0;
  83017. var blockBytes = 1;
  83018. if (header[off_magic] !== DDS_MAGIC) {
  83019. BABYLON.Tools.Error("Invalid magic number in DDS header");
  83020. return;
  83021. }
  83022. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  83023. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  83024. return;
  83025. }
  83026. if (info.isCompressed && !ext) {
  83027. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  83028. return;
  83029. }
  83030. var bpp = header[off_RGBbpp];
  83031. dataOffset = header[off_size] + 4;
  83032. var computeFormats = false;
  83033. if (info.isFourCC) {
  83034. fourCC = header[off_pfFourCC];
  83035. switch (fourCC) {
  83036. case FOURCC_DXT1:
  83037. blockBytes = 8;
  83038. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  83039. break;
  83040. case FOURCC_DXT3:
  83041. blockBytes = 16;
  83042. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  83043. break;
  83044. case FOURCC_DXT5:
  83045. blockBytes = 16;
  83046. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  83047. break;
  83048. case FOURCC_D3DFMT_R16G16B16A16F:
  83049. computeFormats = true;
  83050. break;
  83051. case FOURCC_D3DFMT_R32G32B32A32F:
  83052. computeFormats = true;
  83053. break;
  83054. case FOURCC_DX10:
  83055. // There is an additionnal header so dataOffset need to be changed
  83056. dataOffset += 5 * 4; // 5 uints
  83057. var supported = false;
  83058. switch (info.dxgiFormat) {
  83059. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  83060. computeFormats = true;
  83061. supported = true;
  83062. break;
  83063. case DXGI_FORMAT_B8G8R8X8_UNORM:
  83064. info.isRGB = true;
  83065. info.isFourCC = false;
  83066. bpp = 32;
  83067. supported = true;
  83068. break;
  83069. }
  83070. if (supported) {
  83071. break;
  83072. }
  83073. default:
  83074. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  83075. return;
  83076. }
  83077. }
  83078. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  83079. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  83080. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  83081. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  83082. if (computeFormats) {
  83083. format = engine._getWebGLTextureType(info.textureType);
  83084. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83085. }
  83086. mipmapCount = 1;
  83087. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  83088. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83089. }
  83090. for (var face = 0; face < faces; face++) {
  83091. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  83092. width = header[off_width];
  83093. height = header[off_height];
  83094. for (mip = 0; mip < mipmapCount; ++mip) {
  83095. if (lodIndex === -1 || lodIndex === mip) {
  83096. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  83097. var i = (lodIndex === -1) ? mip : 0;
  83098. if (!info.isCompressed && info.isFourCC) {
  83099. dataLength = width * height * 4;
  83100. var floatArray = null;
  83101. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  83102. if (bpp === 128) {
  83103. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83104. }
  83105. else if (bpp === 64) {
  83106. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83107. }
  83108. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83109. format = engine._getWebGLTextureType(info.textureType);
  83110. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83111. }
  83112. else {
  83113. if (bpp === 128) {
  83114. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83115. }
  83116. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  83117. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83118. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83119. format = engine._getWebGLTextureType(info.textureType);
  83120. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83121. }
  83122. else {
  83123. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83124. }
  83125. }
  83126. if (floatArray) {
  83127. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  83128. }
  83129. }
  83130. else if (info.isRGB) {
  83131. if (bpp === 24) {
  83132. dataLength = width * height * 3;
  83133. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  83134. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  83135. }
  83136. else {
  83137. dataLength = width * height * 4;
  83138. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  83139. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  83140. }
  83141. }
  83142. else if (info.isLuminance) {
  83143. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  83144. var unpaddedRowSize = width;
  83145. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  83146. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  83147. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  83148. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  83149. }
  83150. else {
  83151. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  83152. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  83153. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  83154. }
  83155. }
  83156. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  83157. width *= 0.5;
  83158. height *= 0.5;
  83159. width = Math.max(1.0, width);
  83160. height = Math.max(1.0, height);
  83161. }
  83162. if (currentFace !== undefined) {
  83163. // Loading a single face
  83164. break;
  83165. }
  83166. }
  83167. };
  83168. DDSTools.StoreLODInAlphaChannel = false;
  83169. return DDSTools;
  83170. }());
  83171. BABYLON.DDSTools = DDSTools;
  83172. })(BABYLON || (BABYLON = {}));
  83173. //# sourceMappingURL=babylon.dds.js.map
  83174. "use strict";
  83175. var BABYLON;
  83176. (function (BABYLON) {
  83177. /**
  83178. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  83179. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  83180. */
  83181. var KhronosTextureContainer = /** @class */ (function () {
  83182. /**
  83183. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  83184. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  83185. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  83186. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  83187. */
  83188. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  83189. this.arrayBuffer = arrayBuffer;
  83190. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  83191. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  83192. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  83193. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  83194. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  83195. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  83196. BABYLON.Tools.Error("texture missing KTX identifier");
  83197. return;
  83198. }
  83199. // load the reset of the header in native 32 bit int
  83200. var header = new Int32Array(this.arrayBuffer, 12, 13);
  83201. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  83202. var oppositeEndianess = header[0] === 0x01020304;
  83203. // read all the header elements in order they exist in the file, without modification (sans endainness)
  83204. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  83205. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  83206. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  83207. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  83208. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  83209. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  83210. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  83211. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  83212. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  83213. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  83214. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  83215. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  83216. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  83217. if (this.glType !== 0) {
  83218. BABYLON.Tools.Error("only compressed formats currently supported");
  83219. return;
  83220. }
  83221. else {
  83222. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  83223. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  83224. }
  83225. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  83226. BABYLON.Tools.Error("only 2D textures currently supported");
  83227. return;
  83228. }
  83229. if (this.numberOfArrayElements !== 0) {
  83230. BABYLON.Tools.Error("texture arrays not currently supported");
  83231. return;
  83232. }
  83233. if (this.numberOfFaces !== facesExpected) {
  83234. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  83235. return;
  83236. }
  83237. // we now have a completely validated file, so could use existence of loadType as success
  83238. // would need to make this more elaborate & adjust checks above to support more than one load type
  83239. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  83240. }
  83241. // not as fast hardware based, but will probably never need to use
  83242. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  83243. return ((val & 0xFF) << 24)
  83244. | ((val & 0xFF00) << 8)
  83245. | ((val >> 8) & 0xFF00)
  83246. | ((val >> 24) & 0xFF);
  83247. };
  83248. /**
  83249. * It is assumed that the texture has already been created & is currently bound
  83250. */
  83251. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  83252. switch (this.loadType) {
  83253. case KhronosTextureContainer.COMPRESSED_2D:
  83254. this._upload2DCompressedLevels(gl, loadMipmaps);
  83255. break;
  83256. case KhronosTextureContainer.TEX_2D:
  83257. case KhronosTextureContainer.COMPRESSED_3D:
  83258. case KhronosTextureContainer.TEX_3D:
  83259. }
  83260. };
  83261. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  83262. // initialize width & height for level 1
  83263. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  83264. var width = this.pixelWidth;
  83265. var height = this.pixelHeight;
  83266. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  83267. for (var level = 0; level < mipmapCount; level++) {
  83268. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  83269. for (var face = 0; face < this.numberOfFaces; face++) {
  83270. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  83271. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  83272. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  83273. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  83274. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  83275. }
  83276. width = Math.max(1.0, width * 0.5);
  83277. height = Math.max(1.0, height * 0.5);
  83278. }
  83279. };
  83280. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  83281. // load types
  83282. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  83283. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  83284. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  83285. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  83286. return KhronosTextureContainer;
  83287. }());
  83288. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  83289. })(BABYLON || (BABYLON = {}));
  83290. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  83291. "use strict";
  83292. var BABYLON;
  83293. (function (BABYLON) {
  83294. var Debug;
  83295. (function (Debug) {
  83296. /**
  83297. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  83298. */
  83299. var SkeletonViewer = /** @class */ (function () {
  83300. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  83301. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  83302. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  83303. this.skeleton = skeleton;
  83304. this.mesh = mesh;
  83305. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  83306. this.renderingGroupId = renderingGroupId;
  83307. this.color = BABYLON.Color3.White();
  83308. this._debugLines = new Array();
  83309. this._isEnabled = false;
  83310. this._scene = scene;
  83311. this.update();
  83312. this._renderFunction = this.update.bind(this);
  83313. }
  83314. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  83315. get: function () {
  83316. return this._isEnabled;
  83317. },
  83318. set: function (value) {
  83319. if (this._isEnabled === value) {
  83320. return;
  83321. }
  83322. this._isEnabled = value;
  83323. if (value) {
  83324. this._scene.registerBeforeRender(this._renderFunction);
  83325. }
  83326. else {
  83327. this._scene.unregisterBeforeRender(this._renderFunction);
  83328. }
  83329. },
  83330. enumerable: true,
  83331. configurable: true
  83332. });
  83333. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  83334. if (x === void 0) { x = 0; }
  83335. if (y === void 0) { y = 0; }
  83336. if (z === void 0) { z = 0; }
  83337. var tmat = BABYLON.Tmp.Matrix[0];
  83338. var parentBone = bone.getParent();
  83339. tmat.copyFrom(bone.getLocalMatrix());
  83340. if (x !== 0 || y !== 0 || z !== 0) {
  83341. var tmat2 = BABYLON.Tmp.Matrix[1];
  83342. BABYLON.Matrix.IdentityToRef(tmat2);
  83343. tmat2.m[12] = x;
  83344. tmat2.m[13] = y;
  83345. tmat2.m[14] = z;
  83346. tmat2.multiplyToRef(tmat, tmat);
  83347. }
  83348. if (parentBone) {
  83349. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  83350. }
  83351. tmat.multiplyToRef(meshMat, tmat);
  83352. position.x = tmat.m[12];
  83353. position.y = tmat.m[13];
  83354. position.z = tmat.m[14];
  83355. };
  83356. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  83357. var len = bones.length;
  83358. var meshPos = this.mesh.position;
  83359. for (var i = 0; i < len; i++) {
  83360. var bone = bones[i];
  83361. var points = this._debugLines[i];
  83362. if (!points) {
  83363. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83364. this._debugLines[i] = points;
  83365. }
  83366. this._getBonePosition(points[0], bone, meshMat);
  83367. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  83368. points[0].subtractInPlace(meshPos);
  83369. points[1].subtractInPlace(meshPos);
  83370. }
  83371. };
  83372. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  83373. var len = bones.length;
  83374. var boneNum = 0;
  83375. var meshPos = this.mesh.position;
  83376. for (var i = len - 1; i >= 0; i--) {
  83377. var childBone = bones[i];
  83378. var parentBone = childBone.getParent();
  83379. if (!parentBone) {
  83380. continue;
  83381. }
  83382. var points = this._debugLines[boneNum];
  83383. if (!points) {
  83384. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83385. this._debugLines[boneNum] = points;
  83386. }
  83387. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  83388. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  83389. points[0].subtractInPlace(meshPos);
  83390. points[1].subtractInPlace(meshPos);
  83391. boneNum++;
  83392. }
  83393. };
  83394. SkeletonViewer.prototype.update = function () {
  83395. if (this.autoUpdateBonesMatrices) {
  83396. this.skeleton.computeAbsoluteTransforms();
  83397. }
  83398. if (this.skeleton.bones[0].length === undefined) {
  83399. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83400. }
  83401. else {
  83402. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83403. }
  83404. if (!this._debugMesh) {
  83405. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  83406. this._debugMesh.renderingGroupId = this.renderingGroupId;
  83407. }
  83408. else {
  83409. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  83410. }
  83411. this._debugMesh.position.copyFrom(this.mesh.position);
  83412. this._debugMesh.color = this.color;
  83413. };
  83414. SkeletonViewer.prototype.dispose = function () {
  83415. if (this._debugMesh) {
  83416. this.isEnabled = false;
  83417. this._debugMesh.dispose();
  83418. this._debugMesh = null;
  83419. }
  83420. };
  83421. return SkeletonViewer;
  83422. }());
  83423. Debug.SkeletonViewer = SkeletonViewer;
  83424. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83425. })(BABYLON || (BABYLON = {}));
  83426. //# sourceMappingURL=babylon.skeletonViewer.js.map
  83427. "use strict";
  83428. /**
  83429. * Module Debug contains the (visual) components to debug a scene correctly
  83430. */
  83431. var BABYLON;
  83432. (function (BABYLON) {
  83433. var Debug;
  83434. (function (Debug) {
  83435. /**
  83436. * The Axes viewer will show 3 axes in a specific point in space
  83437. */
  83438. var AxesViewer = /** @class */ (function () {
  83439. function AxesViewer(scene, scaleLines) {
  83440. if (scaleLines === void 0) { scaleLines = 1; }
  83441. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83442. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83443. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83444. this.scaleLines = 1;
  83445. this.scaleLines = scaleLines;
  83446. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  83447. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  83448. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  83449. this._xmesh.renderingGroupId = 2;
  83450. this._ymesh.renderingGroupId = 2;
  83451. this._zmesh.renderingGroupId = 2;
  83452. this._xmesh.material.checkReadyOnlyOnce = true;
  83453. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  83454. this._ymesh.material.checkReadyOnlyOnce = true;
  83455. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  83456. this._zmesh.material.checkReadyOnlyOnce = true;
  83457. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  83458. this.scene = scene;
  83459. }
  83460. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  83461. var scaleLines = this.scaleLines;
  83462. if (this._xmesh) {
  83463. this._xmesh.position.copyFrom(position);
  83464. }
  83465. if (this._ymesh) {
  83466. this._ymesh.position.copyFrom(position);
  83467. }
  83468. if (this._zmesh) {
  83469. this._zmesh.position.copyFrom(position);
  83470. }
  83471. var point2 = this._xline[1];
  83472. point2.x = xaxis.x * scaleLines;
  83473. point2.y = xaxis.y * scaleLines;
  83474. point2.z = xaxis.z * scaleLines;
  83475. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  83476. point2 = this._yline[1];
  83477. point2.x = yaxis.x * scaleLines;
  83478. point2.y = yaxis.y * scaleLines;
  83479. point2.z = yaxis.z * scaleLines;
  83480. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  83481. point2 = this._zline[1];
  83482. point2.x = zaxis.x * scaleLines;
  83483. point2.y = zaxis.y * scaleLines;
  83484. point2.z = zaxis.z * scaleLines;
  83485. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  83486. };
  83487. AxesViewer.prototype.dispose = function () {
  83488. if (this._xmesh) {
  83489. this._xmesh.dispose();
  83490. }
  83491. if (this._ymesh) {
  83492. this._ymesh.dispose();
  83493. }
  83494. if (this._zmesh) {
  83495. this._zmesh.dispose();
  83496. }
  83497. this._xmesh = null;
  83498. this._ymesh = null;
  83499. this._zmesh = null;
  83500. this.scene = null;
  83501. };
  83502. return AxesViewer;
  83503. }());
  83504. Debug.AxesViewer = AxesViewer;
  83505. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83506. })(BABYLON || (BABYLON = {}));
  83507. //# sourceMappingURL=babylon.axesViewer.js.map
  83508. "use strict";
  83509. var BABYLON;
  83510. (function (BABYLON) {
  83511. var Debug;
  83512. (function (Debug) {
  83513. /**
  83514. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  83515. */
  83516. var BoneAxesViewer = /** @class */ (function (_super) {
  83517. __extends(BoneAxesViewer, _super);
  83518. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  83519. if (scaleLines === void 0) { scaleLines = 1; }
  83520. var _this = _super.call(this, scene, scaleLines) || this;
  83521. _this.pos = BABYLON.Vector3.Zero();
  83522. _this.xaxis = BABYLON.Vector3.Zero();
  83523. _this.yaxis = BABYLON.Vector3.Zero();
  83524. _this.zaxis = BABYLON.Vector3.Zero();
  83525. _this.mesh = mesh;
  83526. _this.bone = bone;
  83527. return _this;
  83528. }
  83529. BoneAxesViewer.prototype.update = function () {
  83530. if (!this.mesh || !this.bone) {
  83531. return;
  83532. }
  83533. var bone = this.bone;
  83534. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  83535. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  83536. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  83537. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  83538. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  83539. };
  83540. BoneAxesViewer.prototype.dispose = function () {
  83541. if (this.mesh) {
  83542. this.mesh = null;
  83543. this.bone = null;
  83544. _super.prototype.dispose.call(this);
  83545. }
  83546. };
  83547. return BoneAxesViewer;
  83548. }(Debug.AxesViewer));
  83549. Debug.BoneAxesViewer = BoneAxesViewer;
  83550. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83551. })(BABYLON || (BABYLON = {}));
  83552. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  83553. "use strict";
  83554. var BABYLON;
  83555. (function (BABYLON) {
  83556. var RayHelper = /** @class */ (function () {
  83557. function RayHelper(ray) {
  83558. this.ray = ray;
  83559. }
  83560. RayHelper.CreateAndShow = function (ray, scene, color) {
  83561. var helper = new RayHelper(ray);
  83562. helper.show(scene, color);
  83563. return helper;
  83564. };
  83565. RayHelper.prototype.show = function (scene, color) {
  83566. if (!this._renderFunction && this.ray) {
  83567. var ray = this.ray;
  83568. this._renderFunction = this._render.bind(this);
  83569. this._scene = scene;
  83570. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  83571. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  83572. if (this._renderFunction) {
  83573. this._scene.registerBeforeRender(this._renderFunction);
  83574. }
  83575. }
  83576. if (color && this._renderLine) {
  83577. this._renderLine.color.copyFrom(color);
  83578. }
  83579. };
  83580. RayHelper.prototype.hide = function () {
  83581. if (this._renderFunction && this._scene) {
  83582. this._scene.unregisterBeforeRender(this._renderFunction);
  83583. this._scene = null;
  83584. this._renderFunction = null;
  83585. if (this._renderLine) {
  83586. this._renderLine.dispose();
  83587. this._renderLine = null;
  83588. }
  83589. this._renderPoints = [];
  83590. }
  83591. };
  83592. RayHelper.prototype._render = function () {
  83593. var ray = this.ray;
  83594. if (!ray) {
  83595. return;
  83596. }
  83597. var point = this._renderPoints[1];
  83598. var len = Math.min(ray.length, 1000000);
  83599. point.copyFrom(ray.direction);
  83600. point.scaleInPlace(len);
  83601. point.addInPlace(ray.origin);
  83602. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  83603. };
  83604. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  83605. this._attachedToMesh = mesh;
  83606. var ray = this.ray;
  83607. if (!ray) {
  83608. return;
  83609. }
  83610. if (!ray.direction) {
  83611. ray.direction = BABYLON.Vector3.Zero();
  83612. }
  83613. if (!ray.origin) {
  83614. ray.origin = BABYLON.Vector3.Zero();
  83615. }
  83616. if (length) {
  83617. ray.length = length;
  83618. }
  83619. if (!meshSpaceOrigin) {
  83620. meshSpaceOrigin = BABYLON.Vector3.Zero();
  83621. }
  83622. if (!meshSpaceDirection) {
  83623. // -1 so that this will work with Mesh.lookAt
  83624. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  83625. }
  83626. if (!this._meshSpaceDirection) {
  83627. this._meshSpaceDirection = meshSpaceDirection.clone();
  83628. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  83629. }
  83630. else {
  83631. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  83632. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  83633. }
  83634. if (!this._updateToMeshFunction) {
  83635. this._updateToMeshFunction = this._updateToMesh.bind(this);
  83636. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  83637. }
  83638. this._updateToMesh();
  83639. };
  83640. RayHelper.prototype.detachFromMesh = function () {
  83641. if (this._attachedToMesh) {
  83642. if (this._updateToMeshFunction) {
  83643. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  83644. }
  83645. this._attachedToMesh = null;
  83646. this._updateToMeshFunction = null;
  83647. }
  83648. };
  83649. RayHelper.prototype._updateToMesh = function () {
  83650. var ray = this.ray;
  83651. if (!this._attachedToMesh || !ray) {
  83652. return;
  83653. }
  83654. if (this._attachedToMesh._isDisposed) {
  83655. this.detachFromMesh();
  83656. return;
  83657. }
  83658. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  83659. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  83660. };
  83661. RayHelper.prototype.dispose = function () {
  83662. this.hide();
  83663. this.detachFromMesh();
  83664. this.ray = null;
  83665. };
  83666. return RayHelper;
  83667. }());
  83668. BABYLON.RayHelper = RayHelper;
  83669. })(BABYLON || (BABYLON = {}));
  83670. //# sourceMappingURL=babylon.rayHelper.js.map
  83671. "use strict";
  83672. var BABYLON;
  83673. (function (BABYLON) {
  83674. // load the inspector using require, if not present in the global namespace.
  83675. var DebugLayer = /** @class */ (function () {
  83676. function DebugLayer(scene) {
  83677. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83678. this._scene = scene;
  83679. // load inspector using require, if it doesn't exist on the global namespace.
  83680. }
  83681. /** Creates the inspector window. */
  83682. DebugLayer.prototype._createInspector = function (config) {
  83683. if (config === void 0) { config = {}; }
  83684. var popup = config.popup || false;
  83685. var initialTab = config.initialTab || 0;
  83686. var parentElement = config.parentElement || null;
  83687. if (!this._inspector) {
  83688. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83689. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  83690. } // else nothing to do,; instance is already existing
  83691. };
  83692. DebugLayer.prototype.isVisible = function () {
  83693. if (!this._inspector) {
  83694. return false;
  83695. }
  83696. return true;
  83697. };
  83698. DebugLayer.prototype.hide = function () {
  83699. if (this._inspector) {
  83700. try {
  83701. this._inspector.dispose();
  83702. }
  83703. catch (e) {
  83704. // If the inspector has been removed directly from the inspector tool
  83705. }
  83706. this._inspector = null;
  83707. }
  83708. };
  83709. DebugLayer.prototype.show = function (config) {
  83710. if (config === void 0) { config = {}; }
  83711. if (typeof this.BJSINSPECTOR == 'undefined') {
  83712. // Load inspector and add it to the DOM
  83713. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  83714. }
  83715. else {
  83716. // Otherwise creates the inspector
  83717. this._createInspector(config);
  83718. }
  83719. };
  83720. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  83721. return DebugLayer;
  83722. }());
  83723. BABYLON.DebugLayer = DebugLayer;
  83724. })(BABYLON || (BABYLON = {}));
  83725. //# sourceMappingURL=babylon.debugLayer.js.map
  83726. "use strict";
  83727. var BABYLON;
  83728. (function (BABYLON) {
  83729. var Debug;
  83730. (function (Debug) {
  83731. /**
  83732. * Used to show the physics impostor around the specific mesh.
  83733. */
  83734. var PhysicsViewer = /** @class */ (function () {
  83735. function PhysicsViewer(scene) {
  83736. this._impostors = [];
  83737. this._meshes = [];
  83738. this._numMeshes = 0;
  83739. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83740. var physicEngine = this._scene.getPhysicsEngine();
  83741. if (physicEngine) {
  83742. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  83743. }
  83744. }
  83745. PhysicsViewer.prototype._updateDebugMeshes = function () {
  83746. var plugin = this._physicsEnginePlugin;
  83747. for (var i = 0; i < this._numMeshes; i++) {
  83748. var impostor = this._impostors[i];
  83749. if (!impostor) {
  83750. continue;
  83751. }
  83752. if (impostor.isDisposed) {
  83753. this.hideImpostor(this._impostors[i--]);
  83754. }
  83755. else {
  83756. var mesh = this._meshes[i];
  83757. if (mesh && plugin) {
  83758. plugin.syncMeshWithImpostor(mesh, impostor);
  83759. }
  83760. }
  83761. }
  83762. };
  83763. PhysicsViewer.prototype.showImpostor = function (impostor) {
  83764. if (!this._scene) {
  83765. return;
  83766. }
  83767. for (var i = 0; i < this._numMeshes; i++) {
  83768. if (this._impostors[i] == impostor) {
  83769. return;
  83770. }
  83771. }
  83772. var debugMesh = this._getDebugMesh(impostor, this._scene);
  83773. if (debugMesh) {
  83774. this._impostors[this._numMeshes] = impostor;
  83775. this._meshes[this._numMeshes] = debugMesh;
  83776. if (this._numMeshes === 0) {
  83777. this._renderFunction = this._updateDebugMeshes.bind(this);
  83778. this._scene.registerBeforeRender(this._renderFunction);
  83779. }
  83780. this._numMeshes++;
  83781. }
  83782. };
  83783. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  83784. if (!impostor || !this._scene) {
  83785. return;
  83786. }
  83787. var removed = false;
  83788. for (var i = 0; i < this._numMeshes; i++) {
  83789. if (this._impostors[i] == impostor) {
  83790. var mesh = this._meshes[i];
  83791. if (!mesh) {
  83792. continue;
  83793. }
  83794. this._scene.removeMesh(mesh);
  83795. mesh.dispose();
  83796. this._numMeshes--;
  83797. if (this._numMeshes > 0) {
  83798. this._meshes[i] = this._meshes[this._numMeshes];
  83799. this._impostors[i] = this._impostors[this._numMeshes];
  83800. this._meshes[this._numMeshes] = null;
  83801. this._impostors[this._numMeshes] = null;
  83802. }
  83803. else {
  83804. this._meshes[0] = null;
  83805. this._impostors[0] = null;
  83806. }
  83807. removed = true;
  83808. break;
  83809. }
  83810. }
  83811. if (removed && this._numMeshes === 0) {
  83812. this._scene.unregisterBeforeRender(this._renderFunction);
  83813. }
  83814. };
  83815. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  83816. if (!this._debugMaterial) {
  83817. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  83818. this._debugMaterial.wireframe = true;
  83819. }
  83820. return this._debugMaterial;
  83821. };
  83822. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  83823. if (!this._debugBoxMesh) {
  83824. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  83825. this._debugBoxMesh.renderingGroupId = 1;
  83826. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83827. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  83828. scene.removeMesh(this._debugBoxMesh);
  83829. }
  83830. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  83831. };
  83832. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  83833. if (!this._debugSphereMesh) {
  83834. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  83835. this._debugSphereMesh.renderingGroupId = 1;
  83836. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83837. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  83838. scene.removeMesh(this._debugSphereMesh);
  83839. }
  83840. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  83841. };
  83842. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  83843. var mesh = null;
  83844. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  83845. mesh = this._getDebugBoxMesh(scene);
  83846. impostor.getBoxSizeToRef(mesh.scaling);
  83847. }
  83848. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  83849. mesh = this._getDebugSphereMesh(scene);
  83850. var radius = impostor.getRadius();
  83851. mesh.scaling.x = radius * 2;
  83852. mesh.scaling.y = radius * 2;
  83853. mesh.scaling.z = radius * 2;
  83854. }
  83855. return mesh;
  83856. };
  83857. PhysicsViewer.prototype.dispose = function () {
  83858. for (var i = 0; i < this._numMeshes; i++) {
  83859. this.hideImpostor(this._impostors[i]);
  83860. }
  83861. if (this._debugBoxMesh) {
  83862. this._debugBoxMesh.dispose();
  83863. }
  83864. if (this._debugSphereMesh) {
  83865. this._debugSphereMesh.dispose();
  83866. }
  83867. if (this._debugMaterial) {
  83868. this._debugMaterial.dispose();
  83869. }
  83870. this._impostors.length = 0;
  83871. this._scene = null;
  83872. this._physicsEnginePlugin = null;
  83873. };
  83874. return PhysicsViewer;
  83875. }());
  83876. Debug.PhysicsViewer = PhysicsViewer;
  83877. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83878. })(BABYLON || (BABYLON = {}));
  83879. //# sourceMappingURL=babylon.physicsViewer.js.map
  83880. "use strict";
  83881. var BABYLON;
  83882. (function (BABYLON) {
  83883. var BoundingBoxRenderer = /** @class */ (function () {
  83884. function BoundingBoxRenderer(scene) {
  83885. this.frontColor = new BABYLON.Color3(1, 1, 1);
  83886. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  83887. this.showBackLines = true;
  83888. this.renderList = new BABYLON.SmartArray(32);
  83889. this._vertexBuffers = {};
  83890. this._scene = scene;
  83891. }
  83892. BoundingBoxRenderer.prototype._prepareRessources = function () {
  83893. if (this._colorShader) {
  83894. return;
  83895. }
  83896. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  83897. attributes: [BABYLON.VertexBuffer.PositionKind],
  83898. uniforms: ["world", "viewProjection", "color"]
  83899. });
  83900. var engine = this._scene.getEngine();
  83901. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  83902. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  83903. this._createIndexBuffer();
  83904. };
  83905. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  83906. var engine = this._scene.getEngine();
  83907. 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]);
  83908. };
  83909. BoundingBoxRenderer.prototype._rebuild = function () {
  83910. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83911. if (vb) {
  83912. vb._rebuild();
  83913. }
  83914. this._createIndexBuffer();
  83915. };
  83916. BoundingBoxRenderer.prototype.reset = function () {
  83917. this.renderList.reset();
  83918. };
  83919. BoundingBoxRenderer.prototype.render = function () {
  83920. if (this.renderList.length === 0) {
  83921. return;
  83922. }
  83923. this._prepareRessources();
  83924. if (!this._colorShader.isReady()) {
  83925. return;
  83926. }
  83927. var engine = this._scene.getEngine();
  83928. engine.setDepthWrite(false);
  83929. this._colorShader._preBind();
  83930. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  83931. var boundingBox = this.renderList.data[boundingBoxIndex];
  83932. var min = boundingBox.minimum;
  83933. var max = boundingBox.maximum;
  83934. var diff = max.subtract(min);
  83935. var median = min.add(diff.scale(0.5));
  83936. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83937. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83938. .multiply(boundingBox.getWorldMatrix());
  83939. // VBOs
  83940. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83941. if (this.showBackLines) {
  83942. // Back
  83943. engine.setDepthFunctionToGreaterOrEqual();
  83944. this._scene.resetCachedMaterial();
  83945. this._colorShader.setColor4("color", this.backColor.toColor4());
  83946. this._colorShader.bind(worldMatrix);
  83947. // Draw order
  83948. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83949. }
  83950. // Front
  83951. engine.setDepthFunctionToLess();
  83952. this._scene.resetCachedMaterial();
  83953. this._colorShader.setColor4("color", this.frontColor.toColor4());
  83954. this._colorShader.bind(worldMatrix);
  83955. // Draw order
  83956. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83957. }
  83958. this._colorShader.unbind();
  83959. engine.setDepthFunctionToLessOrEqual();
  83960. engine.setDepthWrite(true);
  83961. };
  83962. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  83963. this._prepareRessources();
  83964. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  83965. return;
  83966. }
  83967. var engine = this._scene.getEngine();
  83968. engine.setDepthWrite(false);
  83969. engine.setColorWrite(false);
  83970. this._colorShader._preBind();
  83971. var boundingBox = mesh._boundingInfo.boundingBox;
  83972. var min = boundingBox.minimum;
  83973. var max = boundingBox.maximum;
  83974. var diff = max.subtract(min);
  83975. var median = min.add(diff.scale(0.5));
  83976. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83977. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83978. .multiply(boundingBox.getWorldMatrix());
  83979. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83980. engine.setDepthFunctionToLess();
  83981. this._scene.resetCachedMaterial();
  83982. this._colorShader.bind(worldMatrix);
  83983. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83984. this._colorShader.unbind();
  83985. engine.setDepthFunctionToLessOrEqual();
  83986. engine.setDepthWrite(true);
  83987. engine.setColorWrite(true);
  83988. };
  83989. BoundingBoxRenderer.prototype.dispose = function () {
  83990. if (!this._colorShader) {
  83991. return;
  83992. }
  83993. this.renderList.dispose();
  83994. this._colorShader.dispose();
  83995. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83996. if (buffer) {
  83997. buffer.dispose();
  83998. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83999. }
  84000. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84001. };
  84002. return BoundingBoxRenderer;
  84003. }());
  84004. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  84005. })(BABYLON || (BABYLON = {}));
  84006. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  84007. "use strict";
  84008. var BABYLON;
  84009. (function (BABYLON) {
  84010. /**
  84011. * Defines a target to use with MorphTargetManager
  84012. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84013. */
  84014. var MorphTarget = /** @class */ (function () {
  84015. /**
  84016. * Creates a new MorphTarget
  84017. * @param name defines the name of the target
  84018. * @param influence defines the influence to use
  84019. */
  84020. function MorphTarget(
  84021. /** defines the name of the target */
  84022. name, influence) {
  84023. if (influence === void 0) { influence = 0; }
  84024. this.name = name;
  84025. /**
  84026. * Gets or sets the list of animations
  84027. */
  84028. this.animations = new Array();
  84029. this._positions = null;
  84030. this._normals = null;
  84031. this._tangents = null;
  84032. /**
  84033. * Observable raised when the influence changes
  84034. */
  84035. this.onInfluenceChanged = new BABYLON.Observable();
  84036. this.influence = influence;
  84037. }
  84038. Object.defineProperty(MorphTarget.prototype, "influence", {
  84039. /**
  84040. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  84041. */
  84042. get: function () {
  84043. return this._influence;
  84044. },
  84045. set: function (influence) {
  84046. if (this._influence === influence) {
  84047. return;
  84048. }
  84049. var previous = this._influence;
  84050. this._influence = influence;
  84051. if (this.onInfluenceChanged.hasObservers) {
  84052. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  84053. }
  84054. },
  84055. enumerable: true,
  84056. configurable: true
  84057. });
  84058. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  84059. /**
  84060. * Gets a boolean defining if the target contains position data
  84061. */
  84062. get: function () {
  84063. return !!this._positions;
  84064. },
  84065. enumerable: true,
  84066. configurable: true
  84067. });
  84068. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  84069. /**
  84070. * Gets a boolean defining if the target contains normal data
  84071. */
  84072. get: function () {
  84073. return !!this._normals;
  84074. },
  84075. enumerable: true,
  84076. configurable: true
  84077. });
  84078. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  84079. /**
  84080. * Gets a boolean defining if the target contains tangent data
  84081. */
  84082. get: function () {
  84083. return !!this._tangents;
  84084. },
  84085. enumerable: true,
  84086. configurable: true
  84087. });
  84088. /**
  84089. * Affects position data to this target
  84090. * @param data defines the position data to use
  84091. */
  84092. MorphTarget.prototype.setPositions = function (data) {
  84093. this._positions = data;
  84094. };
  84095. /**
  84096. * Gets the position data stored in this target
  84097. * @returns a FloatArray containing the position data (or null if not present)
  84098. */
  84099. MorphTarget.prototype.getPositions = function () {
  84100. return this._positions;
  84101. };
  84102. /**
  84103. * Affects normal data to this target
  84104. * @param data defines the normal data to use
  84105. */
  84106. MorphTarget.prototype.setNormals = function (data) {
  84107. this._normals = data;
  84108. };
  84109. /**
  84110. * Gets the normal data stored in this target
  84111. * @returns a FloatArray containing the normal data (or null if not present)
  84112. */
  84113. MorphTarget.prototype.getNormals = function () {
  84114. return this._normals;
  84115. };
  84116. /**
  84117. * Affects tangent data to this target
  84118. * @param data defines the tangent data to use
  84119. */
  84120. MorphTarget.prototype.setTangents = function (data) {
  84121. this._tangents = data;
  84122. };
  84123. /**
  84124. * Gets the tangent data stored in this target
  84125. * @returns a FloatArray containing the tangent data (or null if not present)
  84126. */
  84127. MorphTarget.prototype.getTangents = function () {
  84128. return this._tangents;
  84129. };
  84130. /**
  84131. * Serializes the current target into a Serialization object
  84132. * @returns the serialized object
  84133. */
  84134. MorphTarget.prototype.serialize = function () {
  84135. var serializationObject = {};
  84136. serializationObject.name = this.name;
  84137. serializationObject.influence = this.influence;
  84138. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  84139. if (this.hasNormals) {
  84140. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  84141. }
  84142. if (this.hasTangents) {
  84143. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  84144. }
  84145. // Animations
  84146. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  84147. return serializationObject;
  84148. };
  84149. // Statics
  84150. /**
  84151. * Creates a new target from serialized data
  84152. * @param serializationObject defines the serialized data to use
  84153. * @returns a new MorphTarget
  84154. */
  84155. MorphTarget.Parse = function (serializationObject) {
  84156. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  84157. result.setPositions(serializationObject.positions);
  84158. if (serializationObject.normals) {
  84159. result.setNormals(serializationObject.normals);
  84160. }
  84161. if (serializationObject.tangents) {
  84162. result.setTangents(serializationObject.tangents);
  84163. }
  84164. // Animations
  84165. if (serializationObject.animations) {
  84166. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  84167. var parsedAnimation = serializationObject.animations[animationIndex];
  84168. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  84169. }
  84170. }
  84171. return result;
  84172. };
  84173. /**
  84174. * Creates a MorphTarget from mesh data
  84175. * @param mesh defines the source mesh
  84176. * @param name defines the name to use for the new target
  84177. * @param influence defines the influence to attach to the target
  84178. * @returns a new MorphTarget
  84179. */
  84180. MorphTarget.FromMesh = function (mesh, name, influence) {
  84181. if (!name) {
  84182. name = mesh.name;
  84183. }
  84184. var result = new MorphTarget(name, influence);
  84185. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84186. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84187. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  84188. }
  84189. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  84190. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  84191. }
  84192. return result;
  84193. };
  84194. return MorphTarget;
  84195. }());
  84196. BABYLON.MorphTarget = MorphTarget;
  84197. })(BABYLON || (BABYLON = {}));
  84198. //# sourceMappingURL=babylon.morphTarget.js.map
  84199. "use strict";
  84200. var BABYLON;
  84201. (function (BABYLON) {
  84202. /**
  84203. * This class is used to deform meshes using morphing between different targets
  84204. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84205. */
  84206. var MorphTargetManager = /** @class */ (function () {
  84207. /**
  84208. * Creates a new MorphTargetManager
  84209. * @param scene defines the current scene
  84210. */
  84211. function MorphTargetManager(scene) {
  84212. if (scene === void 0) { scene = null; }
  84213. this._targets = new Array();
  84214. this._targetObservable = new Array();
  84215. this._activeTargets = new BABYLON.SmartArray(16);
  84216. this._supportsNormals = false;
  84217. this._supportsTangents = false;
  84218. this._vertexCount = 0;
  84219. this._uniqueId = 0;
  84220. this._tempInfluences = new Array();
  84221. if (!scene) {
  84222. scene = BABYLON.Engine.LastCreatedScene;
  84223. }
  84224. this._scene = scene;
  84225. if (this._scene) {
  84226. this._scene.morphTargetManagers.push(this);
  84227. this._uniqueId = this._scene.getUniqueId();
  84228. }
  84229. }
  84230. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  84231. /**
  84232. * Gets the unique ID of this manager
  84233. */
  84234. get: function () {
  84235. return this._uniqueId;
  84236. },
  84237. enumerable: true,
  84238. configurable: true
  84239. });
  84240. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  84241. /**
  84242. * Gets the number of vertices handled by this manager
  84243. */
  84244. get: function () {
  84245. return this._vertexCount;
  84246. },
  84247. enumerable: true,
  84248. configurable: true
  84249. });
  84250. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  84251. /**
  84252. * Gets a boolean indicating if this manager supports morphing of normals
  84253. */
  84254. get: function () {
  84255. return this._supportsNormals;
  84256. },
  84257. enumerable: true,
  84258. configurable: true
  84259. });
  84260. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  84261. /**
  84262. * Gets a boolean indicating if this manager supports morphing of tangents
  84263. */
  84264. get: function () {
  84265. return this._supportsTangents;
  84266. },
  84267. enumerable: true,
  84268. configurable: true
  84269. });
  84270. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  84271. /**
  84272. * Gets the number of targets stored in this manager
  84273. */
  84274. get: function () {
  84275. return this._targets.length;
  84276. },
  84277. enumerable: true,
  84278. configurable: true
  84279. });
  84280. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  84281. /**
  84282. * Gets the number of influencers (ie. the number of targets with influences > 0)
  84283. */
  84284. get: function () {
  84285. return this._activeTargets.length;
  84286. },
  84287. enumerable: true,
  84288. configurable: true
  84289. });
  84290. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  84291. /**
  84292. * Gets the list of influences (one per target)
  84293. */
  84294. get: function () {
  84295. return this._influences;
  84296. },
  84297. enumerable: true,
  84298. configurable: true
  84299. });
  84300. /**
  84301. * Gets the active target at specified index. An active target is a target with an influence > 0
  84302. * @param index defines the index to check
  84303. * @returns the requested target
  84304. */
  84305. MorphTargetManager.prototype.getActiveTarget = function (index) {
  84306. return this._activeTargets.data[index];
  84307. };
  84308. /**
  84309. * Gets the target at specified index
  84310. * @param index defines the index to check
  84311. * @returns the requested target
  84312. */
  84313. MorphTargetManager.prototype.getTarget = function (index) {
  84314. return this._targets[index];
  84315. };
  84316. /**
  84317. * Add a new target to this manager
  84318. * @param target defines the target to add
  84319. */
  84320. MorphTargetManager.prototype.addTarget = function (target) {
  84321. var _this = this;
  84322. this._targets.push(target);
  84323. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  84324. _this._syncActiveTargets(needUpdate);
  84325. }));
  84326. this._syncActiveTargets(true);
  84327. };
  84328. /**
  84329. * Removes a target from the manager
  84330. * @param target defines the target to remove
  84331. */
  84332. MorphTargetManager.prototype.removeTarget = function (target) {
  84333. var index = this._targets.indexOf(target);
  84334. if (index >= 0) {
  84335. this._targets.splice(index, 1);
  84336. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  84337. this._syncActiveTargets(true);
  84338. }
  84339. };
  84340. /**
  84341. * Serializes the current manager into a Serialization object
  84342. * @returns the serialized object
  84343. */
  84344. MorphTargetManager.prototype.serialize = function () {
  84345. var serializationObject = {};
  84346. serializationObject.id = this.uniqueId;
  84347. serializationObject.targets = [];
  84348. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  84349. var target = _a[_i];
  84350. serializationObject.targets.push(target.serialize());
  84351. }
  84352. return serializationObject;
  84353. };
  84354. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  84355. var influenceCount = 0;
  84356. this._activeTargets.reset();
  84357. this._supportsNormals = true;
  84358. this._supportsTangents = true;
  84359. this._vertexCount = 0;
  84360. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  84361. var target = _a[_i];
  84362. this._activeTargets.push(target);
  84363. this._tempInfluences[influenceCount++] = target.influence;
  84364. var positions = target.getPositions();
  84365. if (positions) {
  84366. this._supportsNormals = this._supportsNormals && target.hasNormals;
  84367. this._supportsTangents = this._supportsTangents && target.hasTangents;
  84368. var vertexCount = positions.length / 3;
  84369. if (this._vertexCount === 0) {
  84370. this._vertexCount = vertexCount;
  84371. }
  84372. else if (this._vertexCount !== vertexCount) {
  84373. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  84374. return;
  84375. }
  84376. }
  84377. }
  84378. if (!this._influences || this._influences.length !== influenceCount) {
  84379. this._influences = new Float32Array(influenceCount);
  84380. }
  84381. for (var index = 0; index < influenceCount; index++) {
  84382. this._influences[index] = this._tempInfluences[index];
  84383. }
  84384. if (needUpdate) {
  84385. this.synchronize();
  84386. }
  84387. };
  84388. /**
  84389. * Syncrhonize the targets with all the meshes using this morph target manager
  84390. */
  84391. MorphTargetManager.prototype.synchronize = function () {
  84392. if (!this._scene) {
  84393. return;
  84394. }
  84395. // Flag meshes as dirty to resync with the active targets
  84396. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  84397. var mesh = _a[_i];
  84398. if (mesh.morphTargetManager === this) {
  84399. mesh._syncGeometryWithMorphTargetManager();
  84400. }
  84401. }
  84402. };
  84403. // Statics
  84404. /**
  84405. * Creates a new MorphTargetManager from serialized data
  84406. * @param serializationObject defines the serialized data
  84407. * @param scene defines the hosting scene
  84408. * @returns the new MorphTargetManager
  84409. */
  84410. MorphTargetManager.Parse = function (serializationObject, scene) {
  84411. var result = new MorphTargetManager(scene);
  84412. result._uniqueId = serializationObject.id;
  84413. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  84414. var targetData = _a[_i];
  84415. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  84416. }
  84417. return result;
  84418. };
  84419. return MorphTargetManager;
  84420. }());
  84421. BABYLON.MorphTargetManager = MorphTargetManager;
  84422. })(BABYLON || (BABYLON = {}));
  84423. //# sourceMappingURL=babylon.morphTargetManager.js.map
  84424. "use strict";
  84425. var BABYLON;
  84426. (function (BABYLON) {
  84427. var Octree = /** @class */ (function () {
  84428. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  84429. if (maxDepth === void 0) { maxDepth = 2; }
  84430. this.maxDepth = maxDepth;
  84431. this.dynamicContent = new Array();
  84432. this._maxBlockCapacity = maxBlockCapacity || 64;
  84433. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  84434. this._creationFunc = creationFunc;
  84435. }
  84436. // Methods
  84437. Octree.prototype.update = function (worldMin, worldMax, entries) {
  84438. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  84439. };
  84440. Octree.prototype.addMesh = function (entry) {
  84441. for (var index = 0; index < this.blocks.length; index++) {
  84442. var block = this.blocks[index];
  84443. block.addEntry(entry);
  84444. }
  84445. };
  84446. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  84447. this._selectionContent.reset();
  84448. for (var index = 0; index < this.blocks.length; index++) {
  84449. var block = this.blocks[index];
  84450. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  84451. }
  84452. if (allowDuplicate) {
  84453. this._selectionContent.concat(this.dynamicContent);
  84454. }
  84455. else {
  84456. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84457. }
  84458. return this._selectionContent;
  84459. };
  84460. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  84461. this._selectionContent.reset();
  84462. for (var index = 0; index < this.blocks.length; index++) {
  84463. var block = this.blocks[index];
  84464. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  84465. }
  84466. if (allowDuplicate) {
  84467. this._selectionContent.concat(this.dynamicContent);
  84468. }
  84469. else {
  84470. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84471. }
  84472. return this._selectionContent;
  84473. };
  84474. Octree.prototype.intersectsRay = function (ray) {
  84475. this._selectionContent.reset();
  84476. for (var index = 0; index < this.blocks.length; index++) {
  84477. var block = this.blocks[index];
  84478. block.intersectsRay(ray, this._selectionContent);
  84479. }
  84480. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84481. return this._selectionContent;
  84482. };
  84483. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  84484. target.blocks = new Array();
  84485. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  84486. // Segmenting space
  84487. for (var x = 0; x < 2; x++) {
  84488. for (var y = 0; y < 2; y++) {
  84489. for (var z = 0; z < 2; z++) {
  84490. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  84491. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  84492. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  84493. block.addEntries(entries);
  84494. target.blocks.push(block);
  84495. }
  84496. }
  84497. }
  84498. };
  84499. Octree.CreationFuncForMeshes = function (entry, block) {
  84500. var boundingInfo = entry.getBoundingInfo();
  84501. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84502. block.entries.push(entry);
  84503. }
  84504. };
  84505. Octree.CreationFuncForSubMeshes = function (entry, block) {
  84506. var boundingInfo = entry.getBoundingInfo();
  84507. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84508. block.entries.push(entry);
  84509. }
  84510. };
  84511. return Octree;
  84512. }());
  84513. BABYLON.Octree = Octree;
  84514. })(BABYLON || (BABYLON = {}));
  84515. //# sourceMappingURL=babylon.octree.js.map
  84516. "use strict";
  84517. var BABYLON;
  84518. (function (BABYLON) {
  84519. var OctreeBlock = /** @class */ (function () {
  84520. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  84521. this.entries = new Array();
  84522. this._boundingVectors = new Array();
  84523. this._capacity = capacity;
  84524. this._depth = depth;
  84525. this._maxDepth = maxDepth;
  84526. this._creationFunc = creationFunc;
  84527. this._minPoint = minPoint;
  84528. this._maxPoint = maxPoint;
  84529. this._boundingVectors.push(minPoint.clone());
  84530. this._boundingVectors.push(maxPoint.clone());
  84531. this._boundingVectors.push(minPoint.clone());
  84532. this._boundingVectors[2].x = maxPoint.x;
  84533. this._boundingVectors.push(minPoint.clone());
  84534. this._boundingVectors[3].y = maxPoint.y;
  84535. this._boundingVectors.push(minPoint.clone());
  84536. this._boundingVectors[4].z = maxPoint.z;
  84537. this._boundingVectors.push(maxPoint.clone());
  84538. this._boundingVectors[5].z = minPoint.z;
  84539. this._boundingVectors.push(maxPoint.clone());
  84540. this._boundingVectors[6].x = minPoint.x;
  84541. this._boundingVectors.push(maxPoint.clone());
  84542. this._boundingVectors[7].y = minPoint.y;
  84543. }
  84544. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  84545. // Property
  84546. get: function () {
  84547. return this._capacity;
  84548. },
  84549. enumerable: true,
  84550. configurable: true
  84551. });
  84552. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  84553. get: function () {
  84554. return this._minPoint;
  84555. },
  84556. enumerable: true,
  84557. configurable: true
  84558. });
  84559. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  84560. get: function () {
  84561. return this._maxPoint;
  84562. },
  84563. enumerable: true,
  84564. configurable: true
  84565. });
  84566. // Methods
  84567. OctreeBlock.prototype.addEntry = function (entry) {
  84568. if (this.blocks) {
  84569. for (var index = 0; index < this.blocks.length; index++) {
  84570. var block = this.blocks[index];
  84571. block.addEntry(entry);
  84572. }
  84573. return;
  84574. }
  84575. this._creationFunc(entry, this);
  84576. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  84577. this.createInnerBlocks();
  84578. }
  84579. };
  84580. OctreeBlock.prototype.addEntries = function (entries) {
  84581. for (var index = 0; index < entries.length; index++) {
  84582. var mesh = entries[index];
  84583. this.addEntry(mesh);
  84584. }
  84585. };
  84586. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  84587. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  84588. if (this.blocks) {
  84589. for (var index = 0; index < this.blocks.length; index++) {
  84590. var block = this.blocks[index];
  84591. block.select(frustumPlanes, selection, allowDuplicate);
  84592. }
  84593. return;
  84594. }
  84595. if (allowDuplicate) {
  84596. selection.concat(this.entries);
  84597. }
  84598. else {
  84599. selection.concatWithNoDuplicate(this.entries);
  84600. }
  84601. }
  84602. };
  84603. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  84604. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  84605. if (this.blocks) {
  84606. for (var index = 0; index < this.blocks.length; index++) {
  84607. var block = this.blocks[index];
  84608. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  84609. }
  84610. return;
  84611. }
  84612. if (allowDuplicate) {
  84613. selection.concat(this.entries);
  84614. }
  84615. else {
  84616. selection.concatWithNoDuplicate(this.entries);
  84617. }
  84618. }
  84619. };
  84620. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  84621. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  84622. if (this.blocks) {
  84623. for (var index = 0; index < this.blocks.length; index++) {
  84624. var block = this.blocks[index];
  84625. block.intersectsRay(ray, selection);
  84626. }
  84627. return;
  84628. }
  84629. selection.concatWithNoDuplicate(this.entries);
  84630. }
  84631. };
  84632. OctreeBlock.prototype.createInnerBlocks = function () {
  84633. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  84634. };
  84635. return OctreeBlock;
  84636. }());
  84637. BABYLON.OctreeBlock = OctreeBlock;
  84638. })(BABYLON || (BABYLON = {}));
  84639. //# sourceMappingURL=babylon.octreeBlock.js.map
  84640. "use strict";
  84641. var BABYLON;
  84642. (function (BABYLON) {
  84643. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  84644. __extends(VRDistortionCorrectionPostProcess, _super);
  84645. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  84646. var _this = _super.call(this, name, "vrDistortionCorrection", [
  84647. 'LensCenter',
  84648. 'Scale',
  84649. 'ScaleIn',
  84650. 'HmdWarpParam'
  84651. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  84652. _this._isRightEye = isRightEye;
  84653. _this._distortionFactors = vrMetrics.distortionK;
  84654. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  84655. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  84656. _this.adaptScaleToCurrentViewport = true;
  84657. _this.onSizeChangedObservable.add(function () {
  84658. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  84659. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  84660. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  84661. });
  84662. _this.onApplyObservable.add(function (effect) {
  84663. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  84664. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  84665. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  84666. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  84667. });
  84668. return _this;
  84669. }
  84670. return VRDistortionCorrectionPostProcess;
  84671. }(BABYLON.PostProcess));
  84672. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  84673. })(BABYLON || (BABYLON = {}));
  84674. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  84675. "use strict";
  84676. var BABYLON;
  84677. (function (BABYLON) {
  84678. var AnaglyphPostProcess = /** @class */ (function (_super) {
  84679. __extends(AnaglyphPostProcess, _super);
  84680. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  84681. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  84682. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84683. _this.onApplyObservable.add(function (effect) {
  84684. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  84685. });
  84686. return _this;
  84687. }
  84688. return AnaglyphPostProcess;
  84689. }(BABYLON.PostProcess));
  84690. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  84691. })(BABYLON || (BABYLON = {}));
  84692. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  84693. "use strict";
  84694. var BABYLON;
  84695. (function (BABYLON) {
  84696. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  84697. __extends(StereoscopicInterlacePostProcess, _super);
  84698. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  84699. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  84700. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84701. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84702. _this.onSizeChangedObservable.add(function () {
  84703. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84704. });
  84705. _this.onApplyObservable.add(function (effect) {
  84706. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  84707. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  84708. });
  84709. return _this;
  84710. }
  84711. return StereoscopicInterlacePostProcess;
  84712. }(BABYLON.PostProcess));
  84713. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  84714. })(BABYLON || (BABYLON = {}));
  84715. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  84716. "use strict";
  84717. var BABYLON;
  84718. (function (BABYLON) {
  84719. /**
  84720. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  84721. * Screen rotation is taken into account.
  84722. */
  84723. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  84724. function FreeCameraDeviceOrientationInput() {
  84725. var _this = this;
  84726. this._screenOrientationAngle = 0;
  84727. this._screenQuaternion = new BABYLON.Quaternion();
  84728. this._alpha = 0;
  84729. this._beta = 0;
  84730. this._gamma = 0;
  84731. this._orientationChanged = function () {
  84732. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  84733. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  84734. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  84735. };
  84736. this._deviceOrientation = function (evt) {
  84737. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  84738. _this._beta = evt.beta !== null ? evt.beta : 0;
  84739. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  84740. };
  84741. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  84742. this._orientationChanged();
  84743. }
  84744. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  84745. get: function () {
  84746. return this._camera;
  84747. },
  84748. set: function (camera) {
  84749. this._camera = camera;
  84750. if (this._camera != null && !this._camera.rotationQuaternion) {
  84751. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  84752. }
  84753. },
  84754. enumerable: true,
  84755. configurable: true
  84756. });
  84757. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  84758. window.addEventListener("orientationchange", this._orientationChanged);
  84759. window.addEventListener("deviceorientation", this._deviceOrientation);
  84760. //In certain cases, the attach control is called AFTER orientation was changed,
  84761. //So this is needed.
  84762. this._orientationChanged();
  84763. };
  84764. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  84765. window.removeEventListener("orientationchange", this._orientationChanged);
  84766. window.removeEventListener("deviceorientation", this._deviceOrientation);
  84767. };
  84768. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  84769. //if no device orientation provided, don't update the rotation.
  84770. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  84771. if (!this._alpha)
  84772. return;
  84773. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  84774. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  84775. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  84776. //Mirror on XY Plane
  84777. this._camera.rotationQuaternion.z *= -1;
  84778. this._camera.rotationQuaternion.w *= -1;
  84779. };
  84780. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  84781. return "FreeCameraDeviceOrientationInput";
  84782. };
  84783. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  84784. return "deviceOrientation";
  84785. };
  84786. return FreeCameraDeviceOrientationInput;
  84787. }());
  84788. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  84789. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  84790. })(BABYLON || (BABYLON = {}));
  84791. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  84792. "use strict";
  84793. var BABYLON;
  84794. (function (BABYLON) {
  84795. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  84796. function ArcRotateCameraVRDeviceOrientationInput() {
  84797. this.alphaCorrection = 1;
  84798. this.betaCorrection = 1;
  84799. this.gammaCorrection = 1;
  84800. this._alpha = 0;
  84801. this._gamma = 0;
  84802. this._dirty = false;
  84803. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  84804. }
  84805. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  84806. this.camera.attachControl(element, noPreventDefault);
  84807. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  84808. };
  84809. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  84810. if (evt.alpha !== null) {
  84811. this._alpha = +evt.alpha | 0;
  84812. }
  84813. if (evt.gamma !== null) {
  84814. this._gamma = +evt.gamma | 0;
  84815. }
  84816. this._dirty = true;
  84817. };
  84818. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  84819. if (this._dirty) {
  84820. this._dirty = false;
  84821. if (this._gamma < 0) {
  84822. this._gamma = 180 + this._gamma;
  84823. }
  84824. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  84825. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  84826. }
  84827. };
  84828. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  84829. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  84830. };
  84831. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  84832. return "ArcRotateCameraVRDeviceOrientationInput";
  84833. };
  84834. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  84835. return "VRDeviceOrientation";
  84836. };
  84837. return ArcRotateCameraVRDeviceOrientationInput;
  84838. }());
  84839. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  84840. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  84841. })(BABYLON || (BABYLON = {}));
  84842. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  84843. "use strict";
  84844. var BABYLON;
  84845. (function (BABYLON) {
  84846. var VRCameraMetrics = /** @class */ (function () {
  84847. function VRCameraMetrics() {
  84848. this.compensateDistortion = true;
  84849. }
  84850. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  84851. get: function () {
  84852. return this.hResolution / (2 * this.vResolution);
  84853. },
  84854. enumerable: true,
  84855. configurable: true
  84856. });
  84857. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  84858. get: function () {
  84859. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  84860. },
  84861. enumerable: true,
  84862. configurable: true
  84863. });
  84864. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  84865. get: function () {
  84866. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84867. var h = (4 * meters) / this.hScreenSize;
  84868. return BABYLON.Matrix.Translation(h, 0, 0);
  84869. },
  84870. enumerable: true,
  84871. configurable: true
  84872. });
  84873. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  84874. get: function () {
  84875. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84876. var h = (4 * meters) / this.hScreenSize;
  84877. return BABYLON.Matrix.Translation(-h, 0, 0);
  84878. },
  84879. enumerable: true,
  84880. configurable: true
  84881. });
  84882. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  84883. get: function () {
  84884. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  84885. },
  84886. enumerable: true,
  84887. configurable: true
  84888. });
  84889. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  84890. get: function () {
  84891. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  84892. },
  84893. enumerable: true,
  84894. configurable: true
  84895. });
  84896. VRCameraMetrics.GetDefault = function () {
  84897. var result = new VRCameraMetrics();
  84898. result.hResolution = 1280;
  84899. result.vResolution = 800;
  84900. result.hScreenSize = 0.149759993;
  84901. result.vScreenSize = 0.0935999975;
  84902. result.vScreenCenter = 0.0467999987;
  84903. result.eyeToScreenDistance = 0.0410000011;
  84904. result.lensSeparationDistance = 0.0635000020;
  84905. result.interpupillaryDistance = 0.0640000030;
  84906. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  84907. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  84908. result.postProcessScaleFactor = 1.714605507808412;
  84909. result.lensCenterOffset = 0.151976421;
  84910. return result;
  84911. };
  84912. return VRCameraMetrics;
  84913. }());
  84914. BABYLON.VRCameraMetrics = VRCameraMetrics;
  84915. })(BABYLON || (BABYLON = {}));
  84916. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  84917. "use strict";
  84918. var BABYLON;
  84919. (function (BABYLON) {
  84920. /**
  84921. * This represents a WebVR camera.
  84922. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  84923. * @example http://doc.babylonjs.com/how_to/webvr_camera
  84924. */
  84925. var WebVRFreeCamera = /** @class */ (function (_super) {
  84926. __extends(WebVRFreeCamera, _super);
  84927. /**
  84928. * Instantiates a WebVRFreeCamera.
  84929. * @param name The name of the WebVRFreeCamera
  84930. * @param position The starting anchor position for the camera
  84931. * @param scene The scene the camera belongs to
  84932. * @param webVROptions a set of customizable options for the webVRCamera
  84933. */
  84934. function WebVRFreeCamera(name, position, scene, webVROptions) {
  84935. if (webVROptions === void 0) { webVROptions = {}; }
  84936. var _this = _super.call(this, name, position, scene) || this;
  84937. _this.webVROptions = webVROptions;
  84938. /**
  84939. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  84940. */
  84941. _this._vrDevice = null;
  84942. /**
  84943. * The rawPose of the vrDevice.
  84944. */
  84945. _this.rawPose = null;
  84946. _this._specsVersion = "1.1";
  84947. _this._attached = false;
  84948. _this._descendants = [];
  84949. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  84950. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  84951. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  84952. _this._standingMatrix = null;
  84953. /**
  84954. * Represents device position in babylon space.
  84955. */
  84956. _this.devicePosition = BABYLON.Vector3.Zero();
  84957. /**
  84958. * Represents device rotation in babylon space.
  84959. */
  84960. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  84961. /**
  84962. * The scale of the device to be used when translating from device space to babylon space.
  84963. */
  84964. _this.deviceScaleFactor = 1;
  84965. _this._deviceToWorld = BABYLON.Matrix.Identity();
  84966. _this._worldToDevice = BABYLON.Matrix.Identity();
  84967. /**
  84968. * References to the webVR controllers for the vrDevice.
  84969. */
  84970. _this.controllers = [];
  84971. /**
  84972. * Emits an event when a controller is attached.
  84973. */
  84974. _this.onControllersAttachedObservable = new BABYLON.Observable();
  84975. /**
  84976. * Emits an event when a controller's mesh has been loaded;
  84977. */
  84978. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  84979. /**
  84980. * If the rig cameras be used as parent instead of this camera.
  84981. */
  84982. _this.rigParenting = true;
  84983. _this._defaultHeight = undefined;
  84984. _this._workingVector = BABYLON.Vector3.Zero();
  84985. _this._oneVector = BABYLON.Vector3.One();
  84986. _this._workingMatrix = BABYLON.Matrix.Identity();
  84987. _this._cache.position = BABYLON.Vector3.Zero();
  84988. if (webVROptions.defaultHeight) {
  84989. _this._defaultHeight = webVROptions.defaultHeight;
  84990. _this.position.y = _this._defaultHeight;
  84991. }
  84992. _this.minZ = 0.1;
  84993. //legacy support - the compensation boolean was removed.
  84994. if (arguments.length === 5) {
  84995. _this.webVROptions = arguments[4];
  84996. }
  84997. // default webVR options
  84998. if (_this.webVROptions.trackPosition == undefined) {
  84999. _this.webVROptions.trackPosition = true;
  85000. }
  85001. if (_this.webVROptions.controllerMeshes == undefined) {
  85002. _this.webVROptions.controllerMeshes = true;
  85003. }
  85004. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  85005. _this.webVROptions.defaultLightingOnControllers = true;
  85006. }
  85007. _this.rotationQuaternion = new BABYLON.Quaternion();
  85008. if (_this.webVROptions && _this.webVROptions.positionScale) {
  85009. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  85010. }
  85011. //enable VR
  85012. var engine = _this.getEngine();
  85013. _this._onVREnabled = function (success) { if (success) {
  85014. _this.initControllers();
  85015. } };
  85016. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  85017. engine.initWebVR().add(function (event) {
  85018. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  85019. return;
  85020. }
  85021. _this._vrDevice = event.vrDisplay;
  85022. //reset the rig parameters.
  85023. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  85024. if (_this._attached) {
  85025. _this.getEngine().enableVR();
  85026. }
  85027. });
  85028. if (typeof (VRFrameData) !== "undefined")
  85029. _this._frameData = new VRFrameData();
  85030. /**
  85031. * The idea behind the following lines:
  85032. * objects that have the camera as parent should actually have the rig cameras as a parent.
  85033. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  85034. * the second will not show it correctly.
  85035. *
  85036. * To solve this - each object that has the camera as parent will be added to a protected array.
  85037. * When the rig camera renders, it will take this array and set all of those to be its children.
  85038. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  85039. * Amazing!
  85040. */
  85041. scene.onBeforeCameraRenderObservable.add(function (camera) {
  85042. if (camera.parent === _this && _this.rigParenting) {
  85043. _this._descendants = _this.getDescendants(true, function (n) {
  85044. // don't take the cameras or the controllers!
  85045. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  85046. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  85047. return !isController && !isRigCamera;
  85048. });
  85049. _this._descendants.forEach(function (node) {
  85050. node.parent = camera;
  85051. });
  85052. }
  85053. });
  85054. scene.onAfterCameraRenderObservable.add(function (camera) {
  85055. if (camera.parent === _this && _this.rigParenting) {
  85056. _this._descendants.forEach(function (node) {
  85057. node.parent = _this;
  85058. });
  85059. }
  85060. });
  85061. return _this;
  85062. }
  85063. /**
  85064. * Gets the device distance from the ground in meters.
  85065. * @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.
  85066. */
  85067. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  85068. if (this._standingMatrix) {
  85069. // Add standing matrix offset to get real offset from ground in room
  85070. this._standingMatrix.getTranslationToRef(this._workingVector);
  85071. return this._deviceRoomPosition.y + this._workingVector.y;
  85072. }
  85073. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  85074. return this._defaultHeight || 0;
  85075. };
  85076. /**
  85077. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85078. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  85079. */
  85080. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  85081. var _this = this;
  85082. if (callback === void 0) { callback = function (bool) { }; }
  85083. // Use standing matrix if available
  85084. this.getEngine().initWebVRAsync().then(function (result) {
  85085. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  85086. callback(false);
  85087. }
  85088. else {
  85089. _this._standingMatrix = new BABYLON.Matrix();
  85090. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  85091. if (!_this.getScene().useRightHandedSystem) {
  85092. [2, 6, 8, 9, 14].forEach(function (num) {
  85093. if (_this._standingMatrix) {
  85094. _this._standingMatrix.m[num] *= -1;
  85095. }
  85096. });
  85097. }
  85098. callback(true);
  85099. }
  85100. });
  85101. };
  85102. /**
  85103. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85104. * @returns A promise with a boolean set to if the standing matrix is supported.
  85105. */
  85106. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  85107. var _this = this;
  85108. return new Promise(function (res, rej) {
  85109. _this.useStandingMatrix(function (supported) {
  85110. res(supported);
  85111. });
  85112. });
  85113. };
  85114. /**
  85115. * Disposes the camera
  85116. */
  85117. WebVRFreeCamera.prototype.dispose = function () {
  85118. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  85119. _super.prototype.dispose.call(this);
  85120. };
  85121. /**
  85122. * Gets a vrController by name.
  85123. * @param name The name of the controller to retreive
  85124. * @returns the controller matching the name specified or null if not found
  85125. */
  85126. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  85127. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  85128. var gp = _a[_i];
  85129. if (gp.hand === name) {
  85130. return gp;
  85131. }
  85132. }
  85133. return null;
  85134. };
  85135. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  85136. /**
  85137. * The controller corrisponding to the users left hand.
  85138. */
  85139. get: function () {
  85140. if (!this._leftController) {
  85141. this._leftController = this.getControllerByName("left");
  85142. }
  85143. return this._leftController;
  85144. },
  85145. enumerable: true,
  85146. configurable: true
  85147. });
  85148. ;
  85149. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  85150. /**
  85151. * The controller corrisponding to the users right hand.
  85152. */
  85153. get: function () {
  85154. if (!this._rightController) {
  85155. this._rightController = this.getControllerByName("right");
  85156. }
  85157. return this._rightController;
  85158. },
  85159. enumerable: true,
  85160. configurable: true
  85161. });
  85162. ;
  85163. /**
  85164. * Casts a ray forward from the vrCamera's gaze.
  85165. * @param length Length of the ray (default: 100)
  85166. * @returns the ray corrisponding to the gaze
  85167. */
  85168. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  85169. if (length === void 0) { length = 100; }
  85170. if (this.leftCamera) {
  85171. // Use left eye to avoid computation to compute center on every call
  85172. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  85173. }
  85174. else {
  85175. return _super.prototype.getForwardRay.call(this, length);
  85176. }
  85177. };
  85178. /**
  85179. * Updates the camera based on device's frame data
  85180. */
  85181. WebVRFreeCamera.prototype._checkInputs = function () {
  85182. if (this._vrDevice && this._vrDevice.isPresenting) {
  85183. this._vrDevice.getFrameData(this._frameData);
  85184. this.updateFromDevice(this._frameData.pose);
  85185. }
  85186. _super.prototype._checkInputs.call(this);
  85187. };
  85188. /**
  85189. * Updates the poseControlled values based on the input device pose.
  85190. * @param poseData Pose coming from the device
  85191. */
  85192. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  85193. if (poseData && poseData.orientation) {
  85194. this.rawPose = poseData;
  85195. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  85196. if (this.getScene().useRightHandedSystem) {
  85197. this._deviceRoomRotationQuaternion.z *= -1;
  85198. this._deviceRoomRotationQuaternion.w *= -1;
  85199. }
  85200. if (this.webVROptions.trackPosition && this.rawPose.position) {
  85201. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  85202. if (this.getScene().useRightHandedSystem) {
  85203. this._deviceRoomPosition.z *= -1;
  85204. }
  85205. }
  85206. }
  85207. };
  85208. /**
  85209. * WebVR's attach control will start broadcasting frames to the device.
  85210. * Note that in certain browsers (chrome for example) this function must be called
  85211. * within a user-interaction callback. Example:
  85212. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  85213. *
  85214. * @param element html element to attach the vrDevice to
  85215. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  85216. */
  85217. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  85218. _super.prototype.attachControl.call(this, element, noPreventDefault);
  85219. this._attached = true;
  85220. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  85221. if (this._vrDevice) {
  85222. this.getEngine().enableVR();
  85223. }
  85224. };
  85225. /**
  85226. * Detaches the camera from the html element and disables VR
  85227. *
  85228. * @param element html element to detach from
  85229. */
  85230. WebVRFreeCamera.prototype.detachControl = function (element) {
  85231. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  85232. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  85233. _super.prototype.detachControl.call(this, element);
  85234. this._attached = false;
  85235. this.getEngine().disableVR();
  85236. };
  85237. /**
  85238. * @returns the name of this class
  85239. */
  85240. WebVRFreeCamera.prototype.getClassName = function () {
  85241. return "WebVRFreeCamera";
  85242. };
  85243. /**
  85244. * Calls resetPose on the vrDisplay
  85245. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  85246. */
  85247. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  85248. //uses the vrDisplay's "resetPose()".
  85249. //pitch and roll won't be affected.
  85250. this._vrDevice.resetPose();
  85251. };
  85252. /**
  85253. * Updates the rig cameras (left and right eye)
  85254. */
  85255. WebVRFreeCamera.prototype._updateRigCameras = function () {
  85256. var camLeft = this._rigCameras[0];
  85257. var camRight = this._rigCameras[1];
  85258. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  85259. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  85260. camLeft.position.copyFrom(this._deviceRoomPosition);
  85261. camRight.position.copyFrom(this._deviceRoomPosition);
  85262. };
  85263. /**
  85264. * Updates the cached values of the camera
  85265. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  85266. */
  85267. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  85268. var _this = this;
  85269. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  85270. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  85271. if (!this.updateCacheCalled) {
  85272. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  85273. this.updateCacheCalled = true;
  85274. this.update();
  85275. }
  85276. // Set working vector to the device position in room space rotated by the new rotation
  85277. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  85278. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  85279. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  85280. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  85281. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  85282. // Add translation from anchor position
  85283. this._deviceToWorld.getTranslationToRef(this._workingVector);
  85284. this._workingVector.addInPlace(this.position);
  85285. this._workingVector.subtractInPlace(this._cache.position);
  85286. this._deviceToWorld.setTranslation(this._workingVector);
  85287. // Set an inverted matrix to be used when updating the camera
  85288. this._deviceToWorld.invertToRef(this._worldToDevice);
  85289. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  85290. this.controllers.forEach(function (controller) {
  85291. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  85292. controller.update();
  85293. });
  85294. }
  85295. if (!ignoreParentClass) {
  85296. _super.prototype._updateCache.call(this);
  85297. }
  85298. this.updateCacheCalled = false;
  85299. };
  85300. /**
  85301. * Updates the current device position and rotation in the babylon world
  85302. */
  85303. WebVRFreeCamera.prototype.update = function () {
  85304. // Get current device position in babylon world
  85305. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  85306. // Get current device rotation in babylon world
  85307. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  85308. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  85309. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  85310. _super.prototype.update.call(this);
  85311. };
  85312. /**
  85313. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  85314. * @returns an identity matrix
  85315. */
  85316. WebVRFreeCamera.prototype._getViewMatrix = function () {
  85317. return BABYLON.Matrix.Identity();
  85318. };
  85319. /**
  85320. * This function is called by the two RIG cameras.
  85321. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  85322. */
  85323. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  85324. var _this = this;
  85325. // Update the parent camera prior to using a child camera to avoid desynchronization
  85326. var parentCamera = this._cameraRigParams["parentCamera"];
  85327. parentCamera._updateCache();
  85328. //WebVR 1.1
  85329. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  85330. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  85331. if (!this.getScene().useRightHandedSystem) {
  85332. [2, 6, 8, 9, 14].forEach(function (num) {
  85333. _this._webvrViewMatrix.m[num] *= -1;
  85334. });
  85335. }
  85336. // update the camera rotation matrix
  85337. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  85338. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  85339. // Computing target and final matrix
  85340. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  85341. // should the view matrix be updated with scale and position offset?
  85342. if (parentCamera.deviceScaleFactor !== 1) {
  85343. this._webvrViewMatrix.invert();
  85344. // scale the position, if set
  85345. if (parentCamera.deviceScaleFactor) {
  85346. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  85347. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  85348. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  85349. }
  85350. this._webvrViewMatrix.invert();
  85351. }
  85352. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  85353. return this._webvrViewMatrix;
  85354. };
  85355. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  85356. var _this = this;
  85357. var parentCamera = this.parent;
  85358. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  85359. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  85360. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  85361. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  85362. //babylon compatible matrix
  85363. if (!this.getScene().useRightHandedSystem) {
  85364. [8, 9, 10, 11].forEach(function (num) {
  85365. _this._projectionMatrix.m[num] *= -1;
  85366. });
  85367. }
  85368. return this._projectionMatrix;
  85369. };
  85370. /**
  85371. * Initializes the controllers and their meshes
  85372. */
  85373. WebVRFreeCamera.prototype.initControllers = function () {
  85374. var _this = this;
  85375. this.controllers = [];
  85376. var manager = this.getScene().gamepadManager;
  85377. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  85378. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85379. var webVrController = gamepad;
  85380. if (webVrController.defaultModel) {
  85381. webVrController.defaultModel.setEnabled(false);
  85382. }
  85383. if (webVrController.hand === "right") {
  85384. _this._rightController = null;
  85385. }
  85386. if (webVrController.hand === "left") {
  85387. _this._leftController = null;
  85388. }
  85389. var controllerIndex = _this.controllers.indexOf(webVrController);
  85390. if (controllerIndex !== -1) {
  85391. _this.controllers.splice(controllerIndex, 1);
  85392. }
  85393. }
  85394. });
  85395. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  85396. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85397. var webVrController_1 = gamepad;
  85398. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  85399. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  85400. if (_this.webVROptions.controllerMeshes) {
  85401. if (webVrController_1.defaultModel) {
  85402. webVrController_1.defaultModel.setEnabled(true);
  85403. }
  85404. else {
  85405. // Load the meshes
  85406. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  85407. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  85408. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  85409. if (_this.webVROptions.defaultLightingOnControllers) {
  85410. if (!_this._lightOnControllers) {
  85411. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  85412. }
  85413. var activateLightOnSubMeshes_1 = function (mesh, light) {
  85414. var children = mesh.getChildren();
  85415. if (children.length !== 0) {
  85416. children.forEach(function (mesh) {
  85417. light.includedOnlyMeshes.push(mesh);
  85418. activateLightOnSubMeshes_1(mesh, light);
  85419. });
  85420. }
  85421. };
  85422. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  85423. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  85424. }
  85425. });
  85426. }
  85427. }
  85428. webVrController_1.attachToPoseControlledCamera(_this);
  85429. // since this is async - sanity check. Is the controller already stored?
  85430. if (_this.controllers.indexOf(webVrController_1) === -1) {
  85431. //add to the controllers array
  85432. _this.controllers.push(webVrController_1);
  85433. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  85434. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  85435. // So we're overriding setting left & right manually to be sure
  85436. var firstViveWandDetected = false;
  85437. for (var i = 0; i < _this.controllers.length; i++) {
  85438. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  85439. if (!firstViveWandDetected) {
  85440. firstViveWandDetected = true;
  85441. _this.controllers[i].hand = "left";
  85442. }
  85443. else {
  85444. _this.controllers[i].hand = "right";
  85445. }
  85446. }
  85447. }
  85448. //did we find enough controllers? Great! let the developer know.
  85449. if (_this.controllers.length >= 2) {
  85450. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  85451. }
  85452. }
  85453. }
  85454. });
  85455. };
  85456. return WebVRFreeCamera;
  85457. }(BABYLON.FreeCamera));
  85458. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  85459. })(BABYLON || (BABYLON = {}));
  85460. //# sourceMappingURL=babylon.webVRCamera.js.map
  85461. "use strict";
  85462. var BABYLON;
  85463. (function (BABYLON) {
  85464. // We're mainly based on the logic defined into the FreeCamera code
  85465. /**
  85466. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  85467. * being tilted forward or back and left or right.
  85468. */
  85469. var DeviceOrientationCamera = /** @class */ (function (_super) {
  85470. __extends(DeviceOrientationCamera, _super);
  85471. /**
  85472. * Creates a new device orientation camera
  85473. * @param name The name of the camera
  85474. * @param position The start position camera
  85475. * @param scene The scene the camera belongs to
  85476. */
  85477. function DeviceOrientationCamera(name, position, scene) {
  85478. var _this = _super.call(this, name, position, scene) || this;
  85479. _this._quaternionCache = new BABYLON.Quaternion();
  85480. _this.inputs.addDeviceOrientation();
  85481. return _this;
  85482. }
  85483. /**
  85484. * Gets the current instance class name ("DeviceOrientationCamera").
  85485. * This helps avoiding instanceof at run time.
  85486. * @returns the class name
  85487. */
  85488. DeviceOrientationCamera.prototype.getClassName = function () {
  85489. return "DeviceOrientationCamera";
  85490. };
  85491. /**
  85492. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  85493. */
  85494. DeviceOrientationCamera.prototype._checkInputs = function () {
  85495. _super.prototype._checkInputs.call(this);
  85496. this._quaternionCache.copyFrom(this.rotationQuaternion);
  85497. if (this._initialQuaternion) {
  85498. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85499. }
  85500. };
  85501. /**
  85502. * Reset the camera to its default orientation on the specified axis only.
  85503. * @param axis The axis to reset
  85504. */
  85505. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  85506. var _this = this;
  85507. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  85508. //can only work if this camera has a rotation quaternion already.
  85509. if (!this.rotationQuaternion)
  85510. return;
  85511. if (!this._initialQuaternion) {
  85512. this._initialQuaternion = new BABYLON.Quaternion();
  85513. }
  85514. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  85515. ['x', 'y', 'z'].forEach(function (axisName) {
  85516. if (!axis[axisName]) {
  85517. _this._initialQuaternion[axisName] = 0;
  85518. }
  85519. else {
  85520. _this._initialQuaternion[axisName] *= -1;
  85521. }
  85522. });
  85523. this._initialQuaternion.normalize();
  85524. //force rotation update
  85525. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85526. };
  85527. return DeviceOrientationCamera;
  85528. }(BABYLON.FreeCamera));
  85529. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  85530. })(BABYLON || (BABYLON = {}));
  85531. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  85532. "use strict";
  85533. var BABYLON;
  85534. (function (BABYLON) {
  85535. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  85536. __extends(VRDeviceOrientationFreeCamera, _super);
  85537. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85538. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85539. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85540. var _this = _super.call(this, name, position, scene) || this;
  85541. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85542. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85543. return _this;
  85544. }
  85545. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  85546. return "VRDeviceOrientationFreeCamera";
  85547. };
  85548. return VRDeviceOrientationFreeCamera;
  85549. }(BABYLON.DeviceOrientationCamera));
  85550. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  85551. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  85552. __extends(VRDeviceOrientationGamepadCamera, _super);
  85553. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85554. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85555. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85556. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  85557. _this.inputs.addGamepad();
  85558. return _this;
  85559. }
  85560. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  85561. return "VRDeviceOrientationGamepadCamera";
  85562. };
  85563. return VRDeviceOrientationGamepadCamera;
  85564. }(VRDeviceOrientationFreeCamera));
  85565. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  85566. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  85567. __extends(VRDeviceOrientationArcRotateCamera, _super);
  85568. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  85569. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85570. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85571. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85572. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85573. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85574. _this.inputs.addVRDeviceOrientation();
  85575. return _this;
  85576. }
  85577. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  85578. return "VRDeviceOrientationArcRotateCamera";
  85579. };
  85580. return VRDeviceOrientationArcRotateCamera;
  85581. }(BABYLON.ArcRotateCamera));
  85582. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  85583. })(BABYLON || (BABYLON = {}));
  85584. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  85585. "use strict";
  85586. var BABYLON;
  85587. (function (BABYLON) {
  85588. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  85589. __extends(AnaglyphFreeCamera, _super);
  85590. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  85591. var _this = _super.call(this, name, position, scene) || this;
  85592. _this.interaxialDistance = interaxialDistance;
  85593. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85594. return _this;
  85595. }
  85596. AnaglyphFreeCamera.prototype.getClassName = function () {
  85597. return "AnaglyphFreeCamera";
  85598. };
  85599. return AnaglyphFreeCamera;
  85600. }(BABYLON.FreeCamera));
  85601. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  85602. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  85603. __extends(AnaglyphArcRotateCamera, _super);
  85604. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  85605. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85606. _this.interaxialDistance = interaxialDistance;
  85607. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85608. return _this;
  85609. }
  85610. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  85611. return "AnaglyphArcRotateCamera";
  85612. };
  85613. return AnaglyphArcRotateCamera;
  85614. }(BABYLON.ArcRotateCamera));
  85615. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  85616. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  85617. __extends(AnaglyphGamepadCamera, _super);
  85618. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  85619. var _this = _super.call(this, name, position, scene) || this;
  85620. _this.interaxialDistance = interaxialDistance;
  85621. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85622. return _this;
  85623. }
  85624. AnaglyphGamepadCamera.prototype.getClassName = function () {
  85625. return "AnaglyphGamepadCamera";
  85626. };
  85627. return AnaglyphGamepadCamera;
  85628. }(BABYLON.GamepadCamera));
  85629. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  85630. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  85631. __extends(AnaglyphUniversalCamera, _super);
  85632. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  85633. var _this = _super.call(this, name, position, scene) || this;
  85634. _this.interaxialDistance = interaxialDistance;
  85635. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85636. return _this;
  85637. }
  85638. AnaglyphUniversalCamera.prototype.getClassName = function () {
  85639. return "AnaglyphUniversalCamera";
  85640. };
  85641. return AnaglyphUniversalCamera;
  85642. }(BABYLON.UniversalCamera));
  85643. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  85644. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  85645. __extends(StereoscopicFreeCamera, _super);
  85646. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85647. var _this = _super.call(this, name, position, scene) || this;
  85648. _this.interaxialDistance = interaxialDistance;
  85649. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85650. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85651. return _this;
  85652. }
  85653. StereoscopicFreeCamera.prototype.getClassName = function () {
  85654. return "StereoscopicFreeCamera";
  85655. };
  85656. return StereoscopicFreeCamera;
  85657. }(BABYLON.FreeCamera));
  85658. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  85659. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  85660. __extends(StereoscopicArcRotateCamera, _super);
  85661. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  85662. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85663. _this.interaxialDistance = interaxialDistance;
  85664. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85665. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85666. return _this;
  85667. }
  85668. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  85669. return "StereoscopicArcRotateCamera";
  85670. };
  85671. return StereoscopicArcRotateCamera;
  85672. }(BABYLON.ArcRotateCamera));
  85673. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  85674. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  85675. __extends(StereoscopicGamepadCamera, _super);
  85676. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85677. var _this = _super.call(this, name, position, scene) || this;
  85678. _this.interaxialDistance = interaxialDistance;
  85679. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85680. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85681. return _this;
  85682. }
  85683. StereoscopicGamepadCamera.prototype.getClassName = function () {
  85684. return "StereoscopicGamepadCamera";
  85685. };
  85686. return StereoscopicGamepadCamera;
  85687. }(BABYLON.GamepadCamera));
  85688. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  85689. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  85690. __extends(StereoscopicUniversalCamera, _super);
  85691. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85692. var _this = _super.call(this, name, position, scene) || this;
  85693. _this.interaxialDistance = interaxialDistance;
  85694. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85695. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85696. return _this;
  85697. }
  85698. StereoscopicUniversalCamera.prototype.getClassName = function () {
  85699. return "StereoscopicUniversalCamera";
  85700. };
  85701. return StereoscopicUniversalCamera;
  85702. }(BABYLON.UniversalCamera));
  85703. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  85704. })(BABYLON || (BABYLON = {}));
  85705. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  85706. "use strict";
  85707. var BABYLON;
  85708. (function (BABYLON) {
  85709. var VRExperienceHelperGazer = /** @class */ (function () {
  85710. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  85711. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  85712. this.scene = scene;
  85713. this._pointerDownOnMeshAsked = false;
  85714. this._isActionableMesh = false;
  85715. this._teleportationRequestInitiated = false;
  85716. this._teleportationBackRequestInitiated = false;
  85717. this._dpadPressed = true;
  85718. this._activePointer = false;
  85719. this._id = VRExperienceHelperGazer._idCounter++;
  85720. // Gaze tracker
  85721. if (!gazeTrackerToClone) {
  85722. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  85723. this._gazeTracker.bakeCurrentTransformIntoVertices();
  85724. this._gazeTracker.isPickable = false;
  85725. this._gazeTracker.isVisible = false;
  85726. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  85727. targetMat.specularColor = BABYLON.Color3.Black();
  85728. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85729. targetMat.backFaceCulling = false;
  85730. this._gazeTracker.material = targetMat;
  85731. }
  85732. else {
  85733. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  85734. }
  85735. }
  85736. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  85737. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  85738. };
  85739. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  85740. this._pointerDownOnMeshAsked = true;
  85741. if (this._currentMeshSelected && this._currentHit) {
  85742. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  85743. }
  85744. };
  85745. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  85746. if (this._currentMeshSelected && this._currentHit) {
  85747. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  85748. }
  85749. this._pointerDownOnMeshAsked = false;
  85750. };
  85751. VRExperienceHelperGazer.prototype._activatePointer = function () {
  85752. this._activePointer = true;
  85753. };
  85754. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  85755. this._activePointer = false;
  85756. };
  85757. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  85758. };
  85759. VRExperienceHelperGazer.prototype.dispose = function () {
  85760. this._interactionsEnabled = false;
  85761. this._teleportationEnabled = false;
  85762. };
  85763. VRExperienceHelperGazer._idCounter = 0;
  85764. return VRExperienceHelperGazer;
  85765. }());
  85766. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  85767. __extends(VRExperienceHelperControllerGazer, _super);
  85768. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  85769. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  85770. _this.webVRController = webVRController;
  85771. // Laser pointer
  85772. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  85773. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  85774. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85775. laserPointerMaterial.alpha = 0.6;
  85776. _this._laserPointer.material = laserPointerMaterial;
  85777. _this._laserPointer.rotation.x = Math.PI / 2;
  85778. _this._laserPointer.position.z = -0.5;
  85779. _this._laserPointer.isVisible = false;
  85780. if (!webVRController.mesh) {
  85781. // Create an empty mesh that is used prior to loading the high quality model
  85782. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  85783. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  85784. preloadPointerPose.rotation.x = -0.7;
  85785. preloadMesh.addChild(preloadPointerPose);
  85786. webVRController.attachToMesh(preloadMesh);
  85787. }
  85788. _this._setLaserPointerParent(webVRController.mesh);
  85789. return _this;
  85790. }
  85791. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  85792. return this.webVRController.getForwardRay(length);
  85793. };
  85794. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  85795. _super.prototype._activatePointer.call(this);
  85796. this._laserPointer.isVisible = true;
  85797. };
  85798. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  85799. _super.prototype._deactivatePointer.call(this);
  85800. this._laserPointer.isVisible = false;
  85801. };
  85802. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  85803. this._laserPointer.material.emissiveColor = color;
  85804. };
  85805. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  85806. var makeNotPick = function (root) {
  85807. root.name += " laserPointer";
  85808. root.getChildMeshes().forEach(function (c) {
  85809. makeNotPick(c);
  85810. });
  85811. };
  85812. makeNotPick(mesh);
  85813. var childMeshes = mesh.getChildMeshes();
  85814. this.webVRController._pointingPoseNode = null;
  85815. for (var i = 0; i < childMeshes.length; i++) {
  85816. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  85817. mesh = childMeshes[i];
  85818. this.webVRController._pointingPoseNode = mesh;
  85819. break;
  85820. }
  85821. }
  85822. this._laserPointer.parent = mesh;
  85823. };
  85824. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  85825. this._laserPointer.scaling.y = distance;
  85826. this._laserPointer.position.z = -distance / 2;
  85827. };
  85828. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  85829. _super.prototype.dispose.call(this);
  85830. this._laserPointer.dispose();
  85831. };
  85832. return VRExperienceHelperControllerGazer;
  85833. }(VRExperienceHelperGazer));
  85834. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  85835. __extends(VRExperienceHelperCameraGazer, _super);
  85836. function VRExperienceHelperCameraGazer(getCamera, scene) {
  85837. var _this = _super.call(this, scene) || this;
  85838. _this.getCamera = getCamera;
  85839. return _this;
  85840. }
  85841. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  85842. var camera = this.getCamera();
  85843. if (camera) {
  85844. return camera.getForwardRay(length);
  85845. }
  85846. else {
  85847. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  85848. }
  85849. };
  85850. return VRExperienceHelperCameraGazer;
  85851. }(VRExperienceHelperGazer));
  85852. /**
  85853. * Helps to quickly add VR support to an existing scene.
  85854. * See http://doc.babylonjs.com/how_to/webvr_helper
  85855. */
  85856. var VRExperienceHelper = /** @class */ (function () {
  85857. /**
  85858. * Instantiates a VRExperienceHelper.
  85859. * Helps to quickly add VR support to an existing scene.
  85860. * @param scene The scene the VRExperienceHelper belongs to.
  85861. * @param webVROptions Options to modify the vr experience helper's behavior.
  85862. */
  85863. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  85864. if (webVROptions === void 0) { webVROptions = {}; }
  85865. var _this = this;
  85866. this.webVROptions = webVROptions;
  85867. // Can the system support WebVR, even if a headset isn't plugged in?
  85868. this._webVRsupported = false;
  85869. // If WebVR is supported, is a headset plugged in and are we ready to present?
  85870. this._webVRready = false;
  85871. // Are we waiting for the requestPresent callback to complete?
  85872. this._webVRrequesting = false;
  85873. // Are we presenting to the headset right now?
  85874. this._webVRpresenting = false;
  85875. // Are we presenting in the fullscreen fallback?
  85876. this._fullscreenVRpresenting = false;
  85877. /**
  85878. * Observable raised when entering VR.
  85879. */
  85880. this.onEnteringVRObservable = new BABYLON.Observable();
  85881. /**
  85882. * Observable raised when exiting VR.
  85883. */
  85884. this.onExitingVRObservable = new BABYLON.Observable();
  85885. /**
  85886. * Observable raised when controller mesh is loaded.
  85887. */
  85888. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85889. this._useCustomVRButton = false;
  85890. this._teleportationRequested = false;
  85891. this._teleportActive = false;
  85892. this._floorMeshesCollection = [];
  85893. this._rotationAllowed = true;
  85894. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  85895. this._rotationRightAsked = false;
  85896. this._rotationLeftAsked = false;
  85897. this._isDefaultTeleportationTarget = true;
  85898. this._teleportationFillColor = "#444444";
  85899. this._teleportationBorderColor = "#FFFFFF";
  85900. this._rotationAngle = 0;
  85901. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  85902. this._padSensibilityUp = 0.65;
  85903. this._padSensibilityDown = 0.35;
  85904. this.leftController = null;
  85905. this.rightController = null;
  85906. /**
  85907. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  85908. */
  85909. this.onNewMeshSelected = new BABYLON.Observable();
  85910. /**
  85911. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  85912. */
  85913. this.onNewMeshPicked = new BABYLON.Observable();
  85914. /**
  85915. * Observable raised before camera teleportation
  85916. */
  85917. this.onBeforeCameraTeleport = new BABYLON.Observable();
  85918. /**
  85919. * Observable raised after camera teleportation
  85920. */
  85921. this.onAfterCameraTeleport = new BABYLON.Observable();
  85922. /**
  85923. * Observable raised when current selected mesh gets unselected
  85924. */
  85925. this.onSelectedMeshUnselected = new BABYLON.Observable();
  85926. /**
  85927. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  85928. */
  85929. this.teleportationEnabled = true;
  85930. this._teleportationInitialized = false;
  85931. this._interactionsEnabled = false;
  85932. this._interactionsRequested = false;
  85933. this._displayGaze = true;
  85934. this._displayLaserPointer = true;
  85935. this._onResize = function () {
  85936. _this.moveButtonToBottomRight();
  85937. if (_this._fullscreenVRpresenting && _this._webVRready) {
  85938. _this.exitVR();
  85939. }
  85940. };
  85941. this._onFullscreenChange = function () {
  85942. if (document.fullscreen !== undefined) {
  85943. _this._fullscreenVRpresenting = document.fullscreen;
  85944. }
  85945. else if (document.mozFullScreen !== undefined) {
  85946. _this._fullscreenVRpresenting = document.mozFullScreen;
  85947. }
  85948. else if (document.webkitIsFullScreen !== undefined) {
  85949. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  85950. }
  85951. else if (document.msIsFullScreen !== undefined) {
  85952. _this._fullscreenVRpresenting = document.msIsFullScreen;
  85953. }
  85954. if (!_this._fullscreenVRpresenting && _this._canvas) {
  85955. _this.exitVR();
  85956. if (!_this._useCustomVRButton) {
  85957. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  85958. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  85959. }
  85960. }
  85961. };
  85962. this.beforeRender = function () {
  85963. if (_this.leftController && _this.leftController._activePointer) {
  85964. _this._castRayAndSelectObject(_this.leftController);
  85965. }
  85966. if (_this.rightController && _this.rightController._activePointer) {
  85967. _this._castRayAndSelectObject(_this.rightController);
  85968. }
  85969. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  85970. _this._castRayAndSelectObject(_this._cameraGazer);
  85971. }
  85972. else {
  85973. _this._cameraGazer._gazeTracker.isVisible = false;
  85974. }
  85975. };
  85976. this._onNewGamepadConnected = function (gamepad) {
  85977. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  85978. if (gamepad.leftStick) {
  85979. gamepad.onleftstickchanged(function (stickValues) {
  85980. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  85981. // Listening to classic/xbox gamepad only if no VR controller is active
  85982. if ((!_this.leftController && !_this.rightController) ||
  85983. ((_this.leftController && !_this.leftController._activePointer) &&
  85984. (_this.rightController && !_this.rightController._activePointer))) {
  85985. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  85986. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  85987. }
  85988. }
  85989. });
  85990. }
  85991. if (gamepad.rightStick) {
  85992. gamepad.onrightstickchanged(function (stickValues) {
  85993. if (_this._teleportationInitialized) {
  85994. _this._checkRotate(stickValues, _this._cameraGazer);
  85995. }
  85996. });
  85997. }
  85998. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  85999. gamepad.onbuttondown(function (buttonPressed) {
  86000. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86001. _this._cameraGazer._selectionPointerDown();
  86002. }
  86003. });
  86004. gamepad.onbuttonup(function (buttonPressed) {
  86005. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86006. _this._cameraGazer._selectionPointerUp();
  86007. }
  86008. });
  86009. }
  86010. }
  86011. else {
  86012. var webVRController = gamepad;
  86013. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  86014. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  86015. _this.rightController = controller;
  86016. }
  86017. else {
  86018. _this.leftController = controller;
  86019. }
  86020. _this._tryEnableInteractionOnController(controller);
  86021. }
  86022. };
  86023. // 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
  86024. this._tryEnableInteractionOnController = function (controller) {
  86025. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  86026. _this._enableInteractionOnController(controller);
  86027. }
  86028. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  86029. _this._enableTeleportationOnController(controller);
  86030. }
  86031. };
  86032. this._onNewGamepadDisconnected = function (gamepad) {
  86033. if (gamepad instanceof BABYLON.WebVRController) {
  86034. if (gamepad.hand === "left" && _this.leftController != null) {
  86035. _this.leftController.dispose();
  86036. _this.leftController = null;
  86037. }
  86038. if (gamepad.hand === "right" && _this.rightController != null) {
  86039. _this.rightController.dispose();
  86040. _this.rightController = null;
  86041. }
  86042. }
  86043. };
  86044. this._workingVector = BABYLON.Vector3.Zero();
  86045. this._workingQuaternion = BABYLON.Quaternion.Identity();
  86046. this._workingMatrix = BABYLON.Matrix.Identity();
  86047. this._scene = scene;
  86048. this._canvas = scene.getEngine().getRenderingCanvas();
  86049. // Parse options
  86050. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  86051. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  86052. }
  86053. if (webVROptions.createDeviceOrientationCamera === undefined) {
  86054. webVROptions.createDeviceOrientationCamera = true;
  86055. }
  86056. if (webVROptions.defaultHeight === undefined) {
  86057. webVROptions.defaultHeight = 1.7;
  86058. }
  86059. if (webVROptions.useCustomVRButton) {
  86060. this._useCustomVRButton = true;
  86061. if (webVROptions.customVRButton) {
  86062. this._btnVR = webVROptions.customVRButton;
  86063. }
  86064. }
  86065. if (webVROptions.rayLength) {
  86066. this._rayLength = webVROptions.rayLength;
  86067. }
  86068. this._defaultHeight = webVROptions.defaultHeight;
  86069. if (webVROptions.positionScale) {
  86070. this._rayLength *= webVROptions.positionScale;
  86071. this._defaultHeight *= webVROptions.positionScale;
  86072. }
  86073. // Set position
  86074. if (this._scene.activeCamera) {
  86075. this._position = this._scene.activeCamera.position.clone();
  86076. }
  86077. else {
  86078. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  86079. }
  86080. // Set non-vr camera
  86081. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  86082. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  86083. // Copy data from existing camera
  86084. if (this._scene.activeCamera) {
  86085. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  86086. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  86087. // Set rotation from previous camera
  86088. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  86089. var targetCamera = this._scene.activeCamera;
  86090. if (targetCamera.rotationQuaternion) {
  86091. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  86092. }
  86093. else {
  86094. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  86095. }
  86096. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  86097. }
  86098. }
  86099. this._scene.activeCamera = this._deviceOrientationCamera;
  86100. if (this._canvas) {
  86101. this._scene.activeCamera.attachControl(this._canvas);
  86102. }
  86103. }
  86104. else {
  86105. this._existingCamera = this._scene.activeCamera;
  86106. }
  86107. // Create VR cameras
  86108. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86109. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  86110. }
  86111. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  86112. this._webVRCamera.useStandingMatrix();
  86113. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  86114. // Create default button
  86115. if (!this._useCustomVRButton) {
  86116. this._btnVR = document.createElement("BUTTON");
  86117. this._btnVR.className = "babylonVRicon";
  86118. this._btnVR.id = "babylonVRiconbtn";
  86119. this._btnVR.title = "Click to switch to VR";
  86120. 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) }";
  86121. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  86122. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  86123. // css += ".babylonVRicon.vrdisplaysupported { }";
  86124. // css += ".babylonVRicon.vrdisplayready { }";
  86125. // css += ".babylonVRicon.vrdisplayrequesting { }";
  86126. var style = document.createElement('style');
  86127. style.appendChild(document.createTextNode(css));
  86128. document.getElementsByTagName('head')[0].appendChild(style);
  86129. this.moveButtonToBottomRight();
  86130. }
  86131. // VR button click event
  86132. if (this._btnVR) {
  86133. this._btnVR.addEventListener("click", function () {
  86134. if (!_this.isInVRMode) {
  86135. _this.enterVR();
  86136. }
  86137. else {
  86138. _this.exitVR();
  86139. }
  86140. });
  86141. }
  86142. // Window events
  86143. window.addEventListener("resize", this._onResize);
  86144. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  86145. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  86146. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  86147. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  86148. // Display vr button when headset is connected
  86149. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86150. this.displayVRButton();
  86151. }
  86152. else {
  86153. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  86154. if (e.vrDisplay) {
  86155. _this.displayVRButton();
  86156. }
  86157. });
  86158. }
  86159. // Exiting VR mode using 'ESC' key on desktop
  86160. this._onKeyDown = function (event) {
  86161. if (event.keyCode === 27 && _this.isInVRMode) {
  86162. _this.exitVR();
  86163. }
  86164. };
  86165. document.addEventListener("keydown", this._onKeyDown);
  86166. // Exiting VR mode double tapping the touch screen
  86167. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  86168. if (_this.isInVRMode) {
  86169. _this.exitVR();
  86170. if (_this._fullscreenVRpresenting) {
  86171. _this._scene.getEngine().switchFullscreen(true);
  86172. }
  86173. }
  86174. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  86175. // Listen for WebVR display changes
  86176. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  86177. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  86178. this._onVRRequestPresentStart = function () {
  86179. _this._webVRrequesting = true;
  86180. _this.updateButtonVisibility();
  86181. };
  86182. this._onVRRequestPresentComplete = function (success) {
  86183. _this._webVRrequesting = false;
  86184. _this.updateButtonVisibility();
  86185. };
  86186. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  86187. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  86188. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  86189. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86190. scene.onDisposeObservable.add(function () {
  86191. _this.dispose();
  86192. });
  86193. // Gamepad connection events
  86194. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  86195. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  86196. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  86197. this.updateButtonVisibility();
  86198. //create easing functions
  86199. this._circleEase = new BABYLON.CircleEase();
  86200. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  86201. }
  86202. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  86203. /** Return this.onEnteringVRObservable
  86204. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  86205. */
  86206. get: function () {
  86207. return this.onEnteringVRObservable;
  86208. },
  86209. enumerable: true,
  86210. configurable: true
  86211. });
  86212. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  86213. /** Return this.onExitingVRObservable
  86214. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  86215. */
  86216. get: function () {
  86217. return this.onExitingVRObservable;
  86218. },
  86219. enumerable: true,
  86220. configurable: true
  86221. });
  86222. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  86223. /** Return this.onControllerMeshLoadedObservable
  86224. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  86225. */
  86226. get: function () {
  86227. return this.onControllerMeshLoadedObservable;
  86228. },
  86229. enumerable: true,
  86230. configurable: true
  86231. });
  86232. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  86233. /**
  86234. * The mesh used to display where the user is going to teleport.
  86235. */
  86236. get: function () {
  86237. return this._teleportationTarget;
  86238. },
  86239. /**
  86240. * Sets the mesh to be used to display where the user is going to teleport.
  86241. */
  86242. set: function (value) {
  86243. if (value) {
  86244. value.name = "teleportationTarget";
  86245. this._isDefaultTeleportationTarget = false;
  86246. this._teleportationTarget = value;
  86247. }
  86248. },
  86249. enumerable: true,
  86250. configurable: true
  86251. });
  86252. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  86253. /**
  86254. * The mesh used to display where the user is selecting,
  86255. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  86256. * See http://doc.babylonjs.com/resources/baking_transformations
  86257. */
  86258. get: function () {
  86259. return this._cameraGazer._gazeTracker;
  86260. },
  86261. set: function (value) {
  86262. if (value) {
  86263. this._cameraGazer._gazeTracker = value;
  86264. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  86265. this._cameraGazer._gazeTracker.isPickable = false;
  86266. this._cameraGazer._gazeTracker.isVisible = false;
  86267. this._cameraGazer._gazeTracker.name = "gazeTracker";
  86268. if (this.leftController) {
  86269. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  86270. }
  86271. if (this.rightController) {
  86272. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  86273. }
  86274. }
  86275. },
  86276. enumerable: true,
  86277. configurable: true
  86278. });
  86279. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  86280. /**
  86281. * If the ray of the gaze should be displayed.
  86282. */
  86283. get: function () {
  86284. return this._displayGaze;
  86285. },
  86286. /**
  86287. * Sets if the ray of the gaze should be displayed.
  86288. */
  86289. set: function (value) {
  86290. this._displayGaze = value;
  86291. if (!value) {
  86292. this._cameraGazer._gazeTracker.isVisible = false;
  86293. if (this.leftController) {
  86294. this.leftController._gazeTracker.isVisible = false;
  86295. }
  86296. if (this.rightController) {
  86297. this.rightController._gazeTracker.isVisible = false;
  86298. }
  86299. }
  86300. },
  86301. enumerable: true,
  86302. configurable: true
  86303. });
  86304. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  86305. /**
  86306. * If the ray of the LaserPointer should be displayed.
  86307. */
  86308. get: function () {
  86309. return this._displayLaserPointer;
  86310. },
  86311. /**
  86312. * Sets if the ray of the LaserPointer should be displayed.
  86313. */
  86314. set: function (value) {
  86315. this._displayLaserPointer = value;
  86316. if (!value) {
  86317. if (this.rightController) {
  86318. this.rightController._deactivatePointer();
  86319. this.rightController._gazeTracker.isVisible = false;
  86320. }
  86321. if (this.leftController) {
  86322. this.leftController._deactivatePointer();
  86323. this.leftController._gazeTracker.isVisible = false;
  86324. }
  86325. }
  86326. else {
  86327. if (this.rightController) {
  86328. this.rightController._activatePointer();
  86329. }
  86330. else if (this.leftController) {
  86331. this.leftController._activatePointer();
  86332. }
  86333. }
  86334. },
  86335. enumerable: true,
  86336. configurable: true
  86337. });
  86338. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  86339. /**
  86340. * The deviceOrientationCamera used as the camera when not in VR.
  86341. */
  86342. get: function () {
  86343. return this._deviceOrientationCamera;
  86344. },
  86345. enumerable: true,
  86346. configurable: true
  86347. });
  86348. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  86349. /**
  86350. * Based on the current WebVR support, returns the current VR camera used.
  86351. */
  86352. get: function () {
  86353. if (this._webVRready) {
  86354. return this._webVRCamera;
  86355. }
  86356. else {
  86357. return this._scene.activeCamera;
  86358. }
  86359. },
  86360. enumerable: true,
  86361. configurable: true
  86362. });
  86363. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  86364. /**
  86365. * The webVRCamera which is used when in VR.
  86366. */
  86367. get: function () {
  86368. return this._webVRCamera;
  86369. },
  86370. enumerable: true,
  86371. configurable: true
  86372. });
  86373. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  86374. /**
  86375. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  86376. */
  86377. get: function () {
  86378. return this._vrDeviceOrientationCamera;
  86379. },
  86380. enumerable: true,
  86381. configurable: true
  86382. });
  86383. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  86384. get: function () {
  86385. var result = this._cameraGazer._teleportationRequestInitiated
  86386. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  86387. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  86388. return result;
  86389. },
  86390. enumerable: true,
  86391. configurable: true
  86392. });
  86393. // Raised when one of the controller has loaded successfully its associated default mesh
  86394. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  86395. if (this.leftController && this.leftController.webVRController == webVRController) {
  86396. if (webVRController.mesh) {
  86397. this.leftController._setLaserPointerParent(webVRController.mesh);
  86398. }
  86399. }
  86400. if (this.rightController && this.rightController.webVRController == webVRController) {
  86401. if (webVRController.mesh) {
  86402. this.rightController._setLaserPointerParent(webVRController.mesh);
  86403. }
  86404. }
  86405. try {
  86406. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  86407. }
  86408. catch (err) {
  86409. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  86410. }
  86411. };
  86412. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  86413. /**
  86414. * Gets a value indicating if we are currently in VR mode.
  86415. */
  86416. get: function () {
  86417. return this._webVRpresenting || this._fullscreenVRpresenting;
  86418. },
  86419. enumerable: true,
  86420. configurable: true
  86421. });
  86422. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  86423. var vrDisplay = this._scene.getEngine().getVRDevice();
  86424. if (vrDisplay) {
  86425. var wasPresenting = this._webVRpresenting;
  86426. // A VR display is connected
  86427. this._webVRpresenting = vrDisplay.isPresenting;
  86428. if (wasPresenting && !this._webVRpresenting)
  86429. this.exitVR();
  86430. }
  86431. else {
  86432. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  86433. }
  86434. this.updateButtonVisibility();
  86435. };
  86436. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  86437. this._webVRsupported = eventArgs.vrSupported;
  86438. this._webVRready = !!eventArgs.vrDisplay;
  86439. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  86440. this.updateButtonVisibility();
  86441. };
  86442. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  86443. if (this._canvas && !this._useCustomVRButton) {
  86444. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  86445. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  86446. }
  86447. };
  86448. VRExperienceHelper.prototype.displayVRButton = function () {
  86449. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  86450. document.body.appendChild(this._btnVR);
  86451. this._btnVRDisplayed = true;
  86452. }
  86453. };
  86454. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  86455. if (!this._btnVR || this._useCustomVRButton) {
  86456. return;
  86457. }
  86458. this._btnVR.className = "babylonVRicon";
  86459. if (this.isInVRMode) {
  86460. this._btnVR.className += " vrdisplaypresenting";
  86461. }
  86462. else {
  86463. if (this._webVRready)
  86464. this._btnVR.className += " vrdisplayready";
  86465. if (this._webVRsupported)
  86466. this._btnVR.className += " vrdisplaysupported";
  86467. if (this._webVRrequesting)
  86468. this._btnVR.className += " vrdisplayrequesting";
  86469. }
  86470. };
  86471. /**
  86472. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  86473. * Otherwise, will use the fullscreen API.
  86474. */
  86475. VRExperienceHelper.prototype.enterVR = function () {
  86476. if (this.onEnteringVRObservable) {
  86477. try {
  86478. this.onEnteringVRObservable.notifyObservers(this);
  86479. }
  86480. catch (err) {
  86481. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  86482. }
  86483. }
  86484. if (this._scene.activeCamera) {
  86485. this._position = this._scene.activeCamera.position.clone();
  86486. // make sure that we return to the last active camera
  86487. this._existingCamera = this._scene.activeCamera;
  86488. }
  86489. if (this._webVRrequesting)
  86490. return;
  86491. // If WebVR is supported and a headset is connected
  86492. if (this._webVRready) {
  86493. if (!this._webVRpresenting) {
  86494. this._webVRCamera.position = this._position;
  86495. this._scene.activeCamera = this._webVRCamera;
  86496. }
  86497. }
  86498. else if (this._vrDeviceOrientationCamera) {
  86499. this._vrDeviceOrientationCamera.position = this._position;
  86500. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  86501. this._scene.getEngine().switchFullscreen(true);
  86502. this.updateButtonVisibility();
  86503. }
  86504. if (this._scene.activeCamera && this._canvas) {
  86505. this._scene.activeCamera.attachControl(this._canvas);
  86506. }
  86507. if (this._interactionsEnabled) {
  86508. this._scene.registerBeforeRender(this.beforeRender);
  86509. }
  86510. };
  86511. /**
  86512. * Attempt to exit VR, or fullscreen.
  86513. */
  86514. VRExperienceHelper.prototype.exitVR = function () {
  86515. if (this.onExitingVRObservable) {
  86516. try {
  86517. this.onExitingVRObservable.notifyObservers(this);
  86518. }
  86519. catch (err) {
  86520. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  86521. }
  86522. }
  86523. if (this._webVRpresenting) {
  86524. this._scene.getEngine().disableVR();
  86525. }
  86526. if (this._scene.activeCamera) {
  86527. this._position = this._scene.activeCamera.position.clone();
  86528. }
  86529. if (this._deviceOrientationCamera) {
  86530. this._deviceOrientationCamera.position = this._position;
  86531. this._scene.activeCamera = this._deviceOrientationCamera;
  86532. if (this._canvas) {
  86533. this._scene.activeCamera.attachControl(this._canvas);
  86534. }
  86535. }
  86536. else if (this._existingCamera) {
  86537. this._existingCamera.position = this._position;
  86538. this._scene.activeCamera = this._existingCamera;
  86539. }
  86540. this.updateButtonVisibility();
  86541. if (this._interactionsEnabled) {
  86542. this._scene.unregisterBeforeRender(this.beforeRender);
  86543. }
  86544. };
  86545. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  86546. /**
  86547. * The position of the vr experience helper.
  86548. */
  86549. get: function () {
  86550. return this._position;
  86551. },
  86552. /**
  86553. * Sets the position of the vr experience helper.
  86554. */
  86555. set: function (value) {
  86556. this._position = value;
  86557. if (this._scene.activeCamera) {
  86558. this._scene.activeCamera.position = value;
  86559. }
  86560. },
  86561. enumerable: true,
  86562. configurable: true
  86563. });
  86564. /**
  86565. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  86566. */
  86567. VRExperienceHelper.prototype.enableInteractions = function () {
  86568. var _this = this;
  86569. if (!this._interactionsEnabled) {
  86570. this._interactionsRequested = true;
  86571. if (this.leftController) {
  86572. this._enableInteractionOnController(this.leftController);
  86573. }
  86574. if (this.rightController) {
  86575. this._enableInteractionOnController(this.rightController);
  86576. }
  86577. this.raySelectionPredicate = function (mesh) {
  86578. return mesh.isVisible;
  86579. };
  86580. this.meshSelectionPredicate = function (mesh) {
  86581. return true;
  86582. };
  86583. this._raySelectionPredicate = function (mesh) {
  86584. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  86585. && mesh.name.indexOf("teleportationTarget") === -1
  86586. && mesh.name.indexOf("torusTeleportation") === -1
  86587. && mesh.name.indexOf("laserPointer") === -1)) {
  86588. return _this.raySelectionPredicate(mesh);
  86589. }
  86590. return false;
  86591. };
  86592. this._interactionsEnabled = true;
  86593. }
  86594. };
  86595. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  86596. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  86597. if (this._floorMeshesCollection[i].id === mesh.id) {
  86598. return true;
  86599. }
  86600. }
  86601. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  86602. return true;
  86603. }
  86604. return false;
  86605. };
  86606. /**
  86607. * Adds a floor mesh to be used for teleportation.
  86608. * @param floorMesh the mesh to be used for teleportation.
  86609. */
  86610. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  86611. if (!this._floorMeshesCollection) {
  86612. return;
  86613. }
  86614. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  86615. return;
  86616. }
  86617. this._floorMeshesCollection.push(floorMesh);
  86618. };
  86619. /**
  86620. * Removes a floor mesh from being used for teleportation.
  86621. * @param floorMesh the mesh to be removed.
  86622. */
  86623. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  86624. if (!this._floorMeshesCollection) {
  86625. return;
  86626. }
  86627. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  86628. if (meshIndex !== -1) {
  86629. this._floorMeshesCollection.splice(meshIndex, 1);
  86630. }
  86631. };
  86632. /**
  86633. * Enables interactions and teleportation using the VR controllers and gaze.
  86634. * @param vrTeleportationOptions options to modify teleportation behavior.
  86635. */
  86636. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  86637. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  86638. if (!this._teleportationInitialized) {
  86639. this._teleportationRequested = true;
  86640. this.enableInteractions();
  86641. if (vrTeleportationOptions.floorMeshName) {
  86642. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  86643. }
  86644. if (vrTeleportationOptions.floorMeshes) {
  86645. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  86646. }
  86647. if (this.leftController != null) {
  86648. this._enableTeleportationOnController(this.leftController);
  86649. }
  86650. if (this.rightController != null) {
  86651. this._enableTeleportationOnController(this.rightController);
  86652. }
  86653. // Creates an image processing post process for the vignette not relying
  86654. // on the main scene configuration for image processing to reduce setup and spaces
  86655. // (gamma/linear) conflicts.
  86656. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  86657. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86658. imageProcessingConfiguration.vignetteEnabled = true;
  86659. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  86660. this._webVRCamera.detachPostProcess(this._postProcessMove);
  86661. this._teleportationInitialized = true;
  86662. if (this._isDefaultTeleportationTarget) {
  86663. this._createTeleportationCircles();
  86664. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  86665. }
  86666. }
  86667. };
  86668. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  86669. var _this = this;
  86670. var controllerMesh = controller.webVRController.mesh;
  86671. if (controllerMesh) {
  86672. controller._interactionsEnabled = true;
  86673. controller._activatePointer();
  86674. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  86675. // Enabling / disabling laserPointer
  86676. if (_this._displayLaserPointer && stateObject.value === 1) {
  86677. if (controller._activePointer) {
  86678. controller._deactivatePointer();
  86679. }
  86680. else {
  86681. controller._activatePointer();
  86682. }
  86683. if (_this.displayGaze) {
  86684. controller._gazeTracker.isVisible = controller._activePointer;
  86685. }
  86686. }
  86687. });
  86688. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  86689. if (!controller._pointerDownOnMeshAsked) {
  86690. if (stateObject.value > _this._padSensibilityUp) {
  86691. controller._selectionPointerDown();
  86692. }
  86693. }
  86694. else if (stateObject.value < _this._padSensibilityDown) {
  86695. controller._selectionPointerUp();
  86696. }
  86697. });
  86698. }
  86699. };
  86700. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  86701. // Dont teleport if another gaze already requested teleportation
  86702. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  86703. return;
  86704. }
  86705. if (!gazer._teleportationRequestInitiated) {
  86706. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  86707. gazer._activatePointer();
  86708. gazer._teleportationRequestInitiated = true;
  86709. }
  86710. }
  86711. else {
  86712. // Listening to the proper controller values changes to confirm teleportation
  86713. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  86714. if (this._teleportActive) {
  86715. this._teleportCamera(this._haloCenter);
  86716. }
  86717. gazer._teleportationRequestInitiated = false;
  86718. }
  86719. }
  86720. };
  86721. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  86722. // Only rotate when user is not currently selecting a teleportation location
  86723. if (gazer._teleportationRequestInitiated) {
  86724. return;
  86725. }
  86726. if (!this._rotationLeftAsked) {
  86727. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  86728. this._rotationLeftAsked = true;
  86729. if (this._rotationAllowed) {
  86730. this._rotateCamera(false);
  86731. }
  86732. }
  86733. }
  86734. else {
  86735. if (stateObject.x > -this._padSensibilityDown) {
  86736. this._rotationLeftAsked = false;
  86737. }
  86738. }
  86739. if (!this._rotationRightAsked) {
  86740. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  86741. this._rotationRightAsked = true;
  86742. if (this._rotationAllowed) {
  86743. this._rotateCamera(true);
  86744. }
  86745. }
  86746. }
  86747. else {
  86748. if (stateObject.x < this._padSensibilityDown) {
  86749. this._rotationRightAsked = false;
  86750. }
  86751. }
  86752. };
  86753. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  86754. // Only teleport backwards when user is not currently selecting a teleportation location
  86755. if (gazer._teleportationRequestInitiated) {
  86756. return;
  86757. }
  86758. // Teleport backwards
  86759. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  86760. if (!gazer._teleportationBackRequestInitiated) {
  86761. if (!this.currentVRCamera) {
  86762. return;
  86763. }
  86764. // Get rotation and position of the current camera
  86765. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  86766. var position = this.currentVRCamera.position;
  86767. // If the camera has device position, use that instead
  86768. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  86769. rotation = this.currentVRCamera.deviceRotationQuaternion;
  86770. position = this.currentVRCamera.devicePosition;
  86771. }
  86772. // Get matrix with only the y rotation of the device rotation
  86773. rotation.toEulerAnglesToRef(this._workingVector);
  86774. this._workingVector.z = 0;
  86775. this._workingVector.x = 0;
  86776. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  86777. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  86778. // Rotate backwards ray by device rotation to cast at the ground behind the user
  86779. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  86780. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  86781. var ray = new BABYLON.Ray(position, this._workingVector);
  86782. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  86783. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  86784. this._teleportCamera(hit.pickedPoint);
  86785. }
  86786. gazer._teleportationBackRequestInitiated = true;
  86787. }
  86788. }
  86789. else {
  86790. gazer._teleportationBackRequestInitiated = false;
  86791. }
  86792. };
  86793. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  86794. var _this = this;
  86795. var controllerMesh = controller.webVRController.mesh;
  86796. if (controllerMesh) {
  86797. if (!controller._interactionsEnabled) {
  86798. this._enableInteractionOnController(controller);
  86799. }
  86800. controller._interactionsEnabled = true;
  86801. controller._teleportationEnabled = true;
  86802. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86803. controller._dpadPressed = false;
  86804. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  86805. controller._dpadPressed = stateObject.pressed;
  86806. if (!controller._dpadPressed) {
  86807. _this._rotationLeftAsked = false;
  86808. _this._rotationRightAsked = false;
  86809. controller._teleportationBackRequestInitiated = false;
  86810. }
  86811. });
  86812. }
  86813. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  86814. if (_this.teleportationEnabled) {
  86815. _this._checkTeleportBackwards(stateObject, controller);
  86816. _this._checkTeleportWithRay(stateObject, controller);
  86817. }
  86818. _this._checkRotate(stateObject, controller);
  86819. });
  86820. }
  86821. };
  86822. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  86823. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  86824. this._teleportationTarget.isPickable = false;
  86825. var length = 512;
  86826. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  86827. dynamicTexture.hasAlpha = true;
  86828. var context = dynamicTexture.getContext();
  86829. var centerX = length / 2;
  86830. var centerY = length / 2;
  86831. var radius = 200;
  86832. context.beginPath();
  86833. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  86834. context.fillStyle = this._teleportationFillColor;
  86835. context.fill();
  86836. context.lineWidth = 10;
  86837. context.strokeStyle = this._teleportationBorderColor;
  86838. context.stroke();
  86839. context.closePath();
  86840. dynamicTexture.update();
  86841. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  86842. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  86843. this._teleportationTarget.material = teleportationCircleMaterial;
  86844. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  86845. torus.isPickable = false;
  86846. torus.parent = this._teleportationTarget;
  86847. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  86848. var keys = [];
  86849. keys.push({
  86850. frame: 0,
  86851. value: 0
  86852. });
  86853. keys.push({
  86854. frame: 30,
  86855. value: 0.4
  86856. });
  86857. keys.push({
  86858. frame: 60,
  86859. value: 0
  86860. });
  86861. animationInnerCircle.setKeys(keys);
  86862. var easingFunction = new BABYLON.SineEase();
  86863. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  86864. animationInnerCircle.setEasingFunction(easingFunction);
  86865. torus.animations = [];
  86866. torus.animations.push(animationInnerCircle);
  86867. this._scene.beginAnimation(torus, 0, 60, true);
  86868. this._hideTeleportationTarget();
  86869. };
  86870. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  86871. this._teleportActive = true;
  86872. if (this._teleportationInitialized) {
  86873. this._teleportationTarget.isVisible = true;
  86874. if (this._isDefaultTeleportationTarget) {
  86875. this._teleportationTarget.getChildren()[0].isVisible = true;
  86876. }
  86877. }
  86878. };
  86879. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  86880. this._teleportActive = false;
  86881. if (this._teleportationInitialized) {
  86882. this._teleportationTarget.isVisible = false;
  86883. if (this._isDefaultTeleportationTarget) {
  86884. this._teleportationTarget.getChildren()[0].isVisible = false;
  86885. }
  86886. }
  86887. };
  86888. VRExperienceHelper.prototype._rotateCamera = function (right) {
  86889. var _this = this;
  86890. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86891. return;
  86892. }
  86893. if (right) {
  86894. this._rotationAngle++;
  86895. }
  86896. else {
  86897. this._rotationAngle--;
  86898. }
  86899. this.currentVRCamera.animations = [];
  86900. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  86901. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86902. var animationRotationKeys = [];
  86903. animationRotationKeys.push({
  86904. frame: 0,
  86905. value: this.currentVRCamera.rotationQuaternion
  86906. });
  86907. animationRotationKeys.push({
  86908. frame: 6,
  86909. value: target
  86910. });
  86911. animationRotation.setKeys(animationRotationKeys);
  86912. animationRotation.setEasingFunction(this._circleEase);
  86913. this.currentVRCamera.animations.push(animationRotation);
  86914. this._postProcessMove.animations = [];
  86915. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86916. var vignetteWeightKeys = [];
  86917. vignetteWeightKeys.push({
  86918. frame: 0,
  86919. value: 0
  86920. });
  86921. vignetteWeightKeys.push({
  86922. frame: 3,
  86923. value: 4
  86924. });
  86925. vignetteWeightKeys.push({
  86926. frame: 6,
  86927. value: 0
  86928. });
  86929. animationPP.setKeys(vignetteWeightKeys);
  86930. animationPP.setEasingFunction(this._circleEase);
  86931. this._postProcessMove.animations.push(animationPP);
  86932. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86933. var vignetteStretchKeys = [];
  86934. vignetteStretchKeys.push({
  86935. frame: 0,
  86936. value: 0
  86937. });
  86938. vignetteStretchKeys.push({
  86939. frame: 3,
  86940. value: 10
  86941. });
  86942. vignetteStretchKeys.push({
  86943. frame: 6,
  86944. value: 0
  86945. });
  86946. animationPP2.setKeys(vignetteStretchKeys);
  86947. animationPP2.setEasingFunction(this._circleEase);
  86948. this._postProcessMove.animations.push(animationPP2);
  86949. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86950. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86951. this._postProcessMove.samples = 4;
  86952. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86953. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  86954. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86955. });
  86956. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  86957. };
  86958. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  86959. if (hit.pickedPoint) {
  86960. if (gazer._teleportationRequestInitiated) {
  86961. this._displayTeleportationTarget();
  86962. this._haloCenter.copyFrom(hit.pickedPoint);
  86963. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  86964. }
  86965. var pickNormal = hit.getNormal(true, false);
  86966. if (pickNormal) {
  86967. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86968. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86969. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  86970. }
  86971. this._teleportationTarget.position.y += 0.1;
  86972. }
  86973. };
  86974. VRExperienceHelper.prototype._teleportCamera = function (location) {
  86975. var _this = this;
  86976. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86977. return;
  86978. }
  86979. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  86980. // offset of the headset from the anchor.
  86981. if (this.webVRCamera.leftCamera) {
  86982. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  86983. this._workingVector.subtractInPlace(this.webVRCamera.position);
  86984. location.subtractToRef(this._workingVector, this._workingVector);
  86985. }
  86986. else {
  86987. this._workingVector.copyFrom(location);
  86988. }
  86989. // Add height to account for user's height offset
  86990. if (this.isInVRMode) {
  86991. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  86992. }
  86993. else {
  86994. this._workingVector.y += this._defaultHeight;
  86995. }
  86996. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  86997. // Create animation from the camera's position to the new location
  86998. this.currentVRCamera.animations = [];
  86999. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87000. var animationCameraTeleportationKeys = [{
  87001. frame: 0,
  87002. value: this.currentVRCamera.position
  87003. },
  87004. {
  87005. frame: 11,
  87006. value: this._workingVector
  87007. }
  87008. ];
  87009. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  87010. animationCameraTeleportation.setEasingFunction(this._circleEase);
  87011. this.currentVRCamera.animations.push(animationCameraTeleportation);
  87012. this._postProcessMove.animations = [];
  87013. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87014. var vignetteWeightKeys = [];
  87015. vignetteWeightKeys.push({
  87016. frame: 0,
  87017. value: 0
  87018. });
  87019. vignetteWeightKeys.push({
  87020. frame: 5,
  87021. value: 8
  87022. });
  87023. vignetteWeightKeys.push({
  87024. frame: 11,
  87025. value: 0
  87026. });
  87027. animationPP.setKeys(vignetteWeightKeys);
  87028. this._postProcessMove.animations.push(animationPP);
  87029. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87030. var vignetteStretchKeys = [];
  87031. vignetteStretchKeys.push({
  87032. frame: 0,
  87033. value: 0
  87034. });
  87035. vignetteStretchKeys.push({
  87036. frame: 5,
  87037. value: 10
  87038. });
  87039. vignetteStretchKeys.push({
  87040. frame: 11,
  87041. value: 0
  87042. });
  87043. animationPP2.setKeys(vignetteStretchKeys);
  87044. this._postProcessMove.animations.push(animationPP2);
  87045. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87046. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87047. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87048. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  87049. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87050. });
  87051. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  87052. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  87053. });
  87054. this._hideTeleportationTarget();
  87055. };
  87056. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  87057. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87058. return;
  87059. }
  87060. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  87061. // Moving the gazeTracker on the mesh face targetted
  87062. if (hit && hit.pickedPoint) {
  87063. if (this._displayGaze) {
  87064. var multiplier = 1;
  87065. gazer._gazeTracker.isVisible = true;
  87066. if (gazer._isActionableMesh) {
  87067. multiplier = 3;
  87068. }
  87069. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  87070. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  87071. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  87072. var pickNormal = hit.getNormal();
  87073. // To avoid z-fighting
  87074. var deltaFighting = 0.002;
  87075. if (pickNormal) {
  87076. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87077. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87078. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  87079. }
  87080. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  87081. if (gazer._gazeTracker.position.x < 0) {
  87082. gazer._gazeTracker.position.x += deltaFighting;
  87083. }
  87084. else {
  87085. gazer._gazeTracker.position.x -= deltaFighting;
  87086. }
  87087. if (gazer._gazeTracker.position.y < 0) {
  87088. gazer._gazeTracker.position.y += deltaFighting;
  87089. }
  87090. else {
  87091. gazer._gazeTracker.position.y -= deltaFighting;
  87092. }
  87093. if (gazer._gazeTracker.position.z < 0) {
  87094. gazer._gazeTracker.position.z += deltaFighting;
  87095. }
  87096. else {
  87097. gazer._gazeTracker.position.z -= deltaFighting;
  87098. }
  87099. }
  87100. // Changing the size of the laser pointer based on the distance from the targetted point
  87101. gazer._updatePointerDistance(hit.distance);
  87102. }
  87103. else {
  87104. gazer._gazeTracker.isVisible = false;
  87105. }
  87106. if (hit && hit.pickedMesh) {
  87107. gazer._currentHit = hit;
  87108. if (gazer._pointerDownOnMeshAsked) {
  87109. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  87110. }
  87111. // The object selected is the floor, we're in a teleportation scenario
  87112. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  87113. // Moving the teleportation area to this targetted point
  87114. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  87115. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  87116. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87117. }
  87118. gazer._currentMeshSelected = null;
  87119. if (gazer._teleportationRequestInitiated) {
  87120. this._moveTeleportationSelectorTo(hit, gazer);
  87121. }
  87122. return;
  87123. }
  87124. // If not, we're in a selection scenario
  87125. //this._teleportationAllowed = false;
  87126. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  87127. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  87128. this.onNewMeshPicked.notifyObservers(hit);
  87129. gazer._currentMeshSelected = hit.pickedMesh;
  87130. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  87131. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  87132. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  87133. gazer._isActionableMesh = true;
  87134. }
  87135. else {
  87136. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87137. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87138. gazer._isActionableMesh = false;
  87139. }
  87140. try {
  87141. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  87142. }
  87143. catch (err) {
  87144. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  87145. }
  87146. }
  87147. else {
  87148. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87149. gazer._currentMeshSelected = null;
  87150. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87151. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87152. }
  87153. }
  87154. }
  87155. else {
  87156. gazer._currentHit = null;
  87157. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87158. gazer._currentMeshSelected = null;
  87159. //this._teleportationAllowed = false;
  87160. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87161. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87162. }
  87163. };
  87164. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  87165. if (mesh) {
  87166. this.onSelectedMeshUnselected.notifyObservers(mesh);
  87167. }
  87168. };
  87169. /**
  87170. * Sets the color of the laser ray from the vr controllers.
  87171. * @param color new color for the ray.
  87172. */
  87173. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  87174. if (this.leftController) {
  87175. this.leftController._setLaserPointerColor(color);
  87176. }
  87177. if (this.rightController) {
  87178. this.rightController._setLaserPointerColor(color);
  87179. }
  87180. };
  87181. /**
  87182. * Sets the color of the ray from the vr headsets gaze.
  87183. * @param color new color for the ray.
  87184. */
  87185. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  87186. if (!this._cameraGazer._gazeTracker.material) {
  87187. return;
  87188. }
  87189. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  87190. if (this.leftController) {
  87191. this.leftController._gazeTracker.material.emissiveColor = color;
  87192. }
  87193. if (this.rightController) {
  87194. this.rightController._gazeTracker.material.emissiveColor = color;
  87195. }
  87196. };
  87197. /**
  87198. * Exits VR and disposes of the vr experience helper
  87199. */
  87200. VRExperienceHelper.prototype.dispose = function () {
  87201. if (this.isInVRMode) {
  87202. this.exitVR();
  87203. }
  87204. if (this._postProcessMove) {
  87205. this._postProcessMove.dispose();
  87206. }
  87207. if (this._webVRCamera) {
  87208. this._webVRCamera.dispose();
  87209. }
  87210. if (this._vrDeviceOrientationCamera) {
  87211. this._vrDeviceOrientationCamera.dispose();
  87212. }
  87213. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  87214. document.body.removeChild(this._btnVR);
  87215. }
  87216. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  87217. this._deviceOrientationCamera.dispose();
  87218. }
  87219. if (this._cameraGazer) {
  87220. this._cameraGazer.dispose();
  87221. }
  87222. if (this.leftController) {
  87223. this.leftController.dispose();
  87224. }
  87225. if (this.rightController) {
  87226. this.rightController.dispose();
  87227. }
  87228. if (this._teleportationTarget) {
  87229. this._teleportationTarget.dispose();
  87230. }
  87231. this._floorMeshesCollection = [];
  87232. document.removeEventListener("keydown", this._onKeyDown);
  87233. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87234. window.removeEventListener("resize", this._onResize);
  87235. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  87236. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  87237. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  87238. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  87239. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  87240. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  87241. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  87242. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87243. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  87244. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  87245. this._scene.unregisterBeforeRender(this.beforeRender);
  87246. };
  87247. /**
  87248. * Gets the name of the VRExperienceHelper class
  87249. * @returns "VRExperienceHelper"
  87250. */
  87251. VRExperienceHelper.prototype.getClassName = function () {
  87252. return "VRExperienceHelper";
  87253. };
  87254. return VRExperienceHelper;
  87255. }());
  87256. BABYLON.VRExperienceHelper = VRExperienceHelper;
  87257. })(BABYLON || (BABYLON = {}));
  87258. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  87259. "use strict";
  87260. // Mainly based on these 2 articles :
  87261. // 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
  87262. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  87263. var BABYLON;
  87264. (function (BABYLON) {
  87265. var JoystickAxis;
  87266. (function (JoystickAxis) {
  87267. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  87268. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  87269. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  87270. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  87271. var VirtualJoystick = /** @class */ (function () {
  87272. function VirtualJoystick(leftJoystick) {
  87273. var _this = this;
  87274. if (leftJoystick) {
  87275. this._leftJoystick = true;
  87276. }
  87277. else {
  87278. this._leftJoystick = false;
  87279. }
  87280. VirtualJoystick._globalJoystickIndex++;
  87281. // By default left & right arrow keys are moving the X
  87282. // and up & down keys are moving the Y
  87283. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87284. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87285. this.reverseLeftRight = false;
  87286. this.reverseUpDown = false;
  87287. // collections of pointers
  87288. this._touches = new BABYLON.StringDictionary();
  87289. this.deltaPosition = BABYLON.Vector3.Zero();
  87290. this._joystickSensibility = 25;
  87291. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  87292. this._onResize = function (evt) {
  87293. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  87294. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  87295. if (VirtualJoystick.vjCanvas) {
  87296. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  87297. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  87298. }
  87299. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  87300. };
  87301. // injecting a canvas element on top of the canvas 3D game
  87302. if (!VirtualJoystick.vjCanvas) {
  87303. window.addEventListener("resize", this._onResize, false);
  87304. VirtualJoystick.vjCanvas = document.createElement("canvas");
  87305. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  87306. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  87307. VirtualJoystick.vjCanvas.width = window.innerWidth;
  87308. VirtualJoystick.vjCanvas.height = window.innerHeight;
  87309. VirtualJoystick.vjCanvas.style.width = "100%";
  87310. VirtualJoystick.vjCanvas.style.height = "100%";
  87311. VirtualJoystick.vjCanvas.style.position = "absolute";
  87312. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  87313. VirtualJoystick.vjCanvas.style.top = "0px";
  87314. VirtualJoystick.vjCanvas.style.left = "0px";
  87315. VirtualJoystick.vjCanvas.style.zIndex = "5";
  87316. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  87317. // Support for jQuery PEP polyfill
  87318. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  87319. var context = VirtualJoystick.vjCanvas.getContext('2d');
  87320. if (!context) {
  87321. throw new Error("Unable to create canvas for virtual joystick");
  87322. }
  87323. VirtualJoystick.vjCanvasContext = context;
  87324. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  87325. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87326. document.body.appendChild(VirtualJoystick.vjCanvas);
  87327. }
  87328. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  87329. this.pressed = false;
  87330. // default joystick color
  87331. this._joystickColor = "cyan";
  87332. this._joystickPointerID = -1;
  87333. // current joystick position
  87334. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  87335. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  87336. // origin joystick position
  87337. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  87338. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  87339. this._onPointerDownHandlerRef = function (evt) {
  87340. _this._onPointerDown(evt);
  87341. };
  87342. this._onPointerMoveHandlerRef = function (evt) {
  87343. _this._onPointerMove(evt);
  87344. };
  87345. this._onPointerUpHandlerRef = function (evt) {
  87346. _this._onPointerUp(evt);
  87347. };
  87348. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  87349. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  87350. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  87351. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  87352. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  87353. evt.preventDefault(); // Disables system menu
  87354. }, false);
  87355. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87356. }
  87357. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  87358. this._joystickSensibility = newJoystickSensibility;
  87359. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  87360. };
  87361. VirtualJoystick.prototype._onPointerDown = function (e) {
  87362. var positionOnScreenCondition;
  87363. e.preventDefault();
  87364. if (this._leftJoystick === true) {
  87365. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  87366. }
  87367. else {
  87368. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  87369. }
  87370. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  87371. // First contact will be dedicated to the virtual joystick
  87372. this._joystickPointerID = e.pointerId;
  87373. this._joystickPointerStartPos.x = e.clientX;
  87374. this._joystickPointerStartPos.y = e.clientY;
  87375. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  87376. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  87377. this._deltaJoystickVector.x = 0;
  87378. this._deltaJoystickVector.y = 0;
  87379. this.pressed = true;
  87380. this._touches.add(e.pointerId.toString(), e);
  87381. }
  87382. else {
  87383. // You can only trigger the action buttons with a joystick declared
  87384. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  87385. this._action();
  87386. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  87387. }
  87388. }
  87389. };
  87390. VirtualJoystick.prototype._onPointerMove = function (e) {
  87391. // If the current pointer is the one associated to the joystick (first touch contact)
  87392. if (this._joystickPointerID == e.pointerId) {
  87393. this._joystickPointerPos.x = e.clientX;
  87394. this._joystickPointerPos.y = e.clientY;
  87395. this._deltaJoystickVector = this._joystickPointerPos.clone();
  87396. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  87397. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  87398. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  87399. switch (this._axisTargetedByLeftAndRight) {
  87400. case JoystickAxis.X:
  87401. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  87402. break;
  87403. case JoystickAxis.Y:
  87404. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  87405. break;
  87406. case JoystickAxis.Z:
  87407. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  87408. break;
  87409. }
  87410. var directionUpDown = this.reverseUpDown ? 1 : -1;
  87411. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  87412. switch (this._axisTargetedByUpAndDown) {
  87413. case JoystickAxis.X:
  87414. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  87415. break;
  87416. case JoystickAxis.Y:
  87417. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  87418. break;
  87419. case JoystickAxis.Z:
  87420. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  87421. break;
  87422. }
  87423. }
  87424. else {
  87425. var data = this._touches.get(e.pointerId.toString());
  87426. if (data) {
  87427. data.x = e.clientX;
  87428. data.y = e.clientY;
  87429. }
  87430. }
  87431. };
  87432. VirtualJoystick.prototype._onPointerUp = function (e) {
  87433. if (this._joystickPointerID == e.pointerId) {
  87434. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  87435. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  87436. this._joystickPointerID = -1;
  87437. this.pressed = false;
  87438. }
  87439. else {
  87440. var touch = this._touches.get(e.pointerId.toString());
  87441. if (touch) {
  87442. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87443. }
  87444. }
  87445. this._deltaJoystickVector.x = 0;
  87446. this._deltaJoystickVector.y = 0;
  87447. this._touches.remove(e.pointerId.toString());
  87448. };
  87449. /**
  87450. * Change the color of the virtual joystick
  87451. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  87452. */
  87453. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  87454. this._joystickColor = newColor;
  87455. };
  87456. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  87457. this._action = action;
  87458. };
  87459. // Define which axis you'd like to control for left & right
  87460. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  87461. switch (axis) {
  87462. case JoystickAxis.X:
  87463. case JoystickAxis.Y:
  87464. case JoystickAxis.Z:
  87465. this._axisTargetedByLeftAndRight = axis;
  87466. break;
  87467. default:
  87468. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87469. break;
  87470. }
  87471. };
  87472. // Define which axis you'd like to control for up & down
  87473. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  87474. switch (axis) {
  87475. case JoystickAxis.X:
  87476. case JoystickAxis.Y:
  87477. case JoystickAxis.Z:
  87478. this._axisTargetedByUpAndDown = axis;
  87479. break;
  87480. default:
  87481. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87482. break;
  87483. }
  87484. };
  87485. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  87486. var _this = this;
  87487. if (this.pressed) {
  87488. this._touches.forEach(function (key, touch) {
  87489. if (touch.pointerId === _this._joystickPointerID) {
  87490. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  87491. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  87492. VirtualJoystick.vjCanvasContext.beginPath();
  87493. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87494. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87495. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  87496. VirtualJoystick.vjCanvasContext.stroke();
  87497. VirtualJoystick.vjCanvasContext.closePath();
  87498. VirtualJoystick.vjCanvasContext.beginPath();
  87499. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87500. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87501. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  87502. VirtualJoystick.vjCanvasContext.stroke();
  87503. VirtualJoystick.vjCanvasContext.closePath();
  87504. VirtualJoystick.vjCanvasContext.beginPath();
  87505. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87506. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  87507. VirtualJoystick.vjCanvasContext.stroke();
  87508. VirtualJoystick.vjCanvasContext.closePath();
  87509. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  87510. }
  87511. else {
  87512. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87513. VirtualJoystick.vjCanvasContext.beginPath();
  87514. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  87515. VirtualJoystick.vjCanvasContext.beginPath();
  87516. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  87517. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87518. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  87519. VirtualJoystick.vjCanvasContext.stroke();
  87520. VirtualJoystick.vjCanvasContext.closePath();
  87521. touch.prevX = touch.x;
  87522. touch.prevY = touch.y;
  87523. }
  87524. ;
  87525. });
  87526. }
  87527. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87528. };
  87529. VirtualJoystick.prototype.releaseCanvas = function () {
  87530. if (VirtualJoystick.vjCanvas) {
  87531. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  87532. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  87533. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  87534. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  87535. window.removeEventListener("resize", this._onResize);
  87536. document.body.removeChild(VirtualJoystick.vjCanvas);
  87537. VirtualJoystick.vjCanvas = null;
  87538. }
  87539. };
  87540. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  87541. VirtualJoystick._globalJoystickIndex = 0;
  87542. return VirtualJoystick;
  87543. }());
  87544. BABYLON.VirtualJoystick = VirtualJoystick;
  87545. })(BABYLON || (BABYLON = {}));
  87546. //# sourceMappingURL=babylon.virtualJoystick.js.map
  87547. "use strict";
  87548. var BABYLON;
  87549. (function (BABYLON) {
  87550. // We're mainly based on the logic defined into the FreeCamera code
  87551. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  87552. __extends(VirtualJoysticksCamera, _super);
  87553. function VirtualJoysticksCamera(name, position, scene) {
  87554. var _this = _super.call(this, name, position, scene) || this;
  87555. _this.inputs.addVirtualJoystick();
  87556. return _this;
  87557. }
  87558. VirtualJoysticksCamera.prototype.getClassName = function () {
  87559. return "VirtualJoysticksCamera";
  87560. };
  87561. return VirtualJoysticksCamera;
  87562. }(BABYLON.FreeCamera));
  87563. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  87564. })(BABYLON || (BABYLON = {}));
  87565. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  87566. "use strict";
  87567. var BABYLON;
  87568. (function (BABYLON) {
  87569. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  87570. function FreeCameraVirtualJoystickInput() {
  87571. }
  87572. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  87573. return this._leftjoystick;
  87574. };
  87575. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  87576. return this._rightjoystick;
  87577. };
  87578. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  87579. if (this._leftjoystick) {
  87580. var camera = this.camera;
  87581. var speed = camera._computeLocalCameraSpeed() * 50;
  87582. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  87583. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  87584. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  87585. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  87586. if (!this._leftjoystick.pressed) {
  87587. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  87588. }
  87589. if (!this._rightjoystick.pressed) {
  87590. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  87591. }
  87592. }
  87593. };
  87594. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  87595. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  87596. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  87597. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  87598. this._leftjoystick.setJoystickSensibility(0.15);
  87599. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  87600. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  87601. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  87602. this._rightjoystick.reverseUpDown = true;
  87603. this._rightjoystick.setJoystickSensibility(0.05);
  87604. this._rightjoystick.setJoystickColor("yellow");
  87605. };
  87606. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  87607. this._leftjoystick.releaseCanvas();
  87608. this._rightjoystick.releaseCanvas();
  87609. };
  87610. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  87611. return "FreeCameraVirtualJoystickInput";
  87612. };
  87613. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  87614. return "virtualJoystick";
  87615. };
  87616. return FreeCameraVirtualJoystickInput;
  87617. }());
  87618. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  87619. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  87620. })(BABYLON || (BABYLON = {}));
  87621. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  87622. "use strict";
  87623. var BABYLON;
  87624. (function (BABYLON) {
  87625. var SimplificationSettings = /** @class */ (function () {
  87626. function SimplificationSettings(quality, distance, optimizeMesh) {
  87627. this.quality = quality;
  87628. this.distance = distance;
  87629. this.optimizeMesh = optimizeMesh;
  87630. }
  87631. return SimplificationSettings;
  87632. }());
  87633. BABYLON.SimplificationSettings = SimplificationSettings;
  87634. var SimplificationQueue = /** @class */ (function () {
  87635. function SimplificationQueue() {
  87636. this.running = false;
  87637. this._simplificationArray = [];
  87638. }
  87639. SimplificationQueue.prototype.addTask = function (task) {
  87640. this._simplificationArray.push(task);
  87641. };
  87642. SimplificationQueue.prototype.executeNext = function () {
  87643. var task = this._simplificationArray.pop();
  87644. if (task) {
  87645. this.running = true;
  87646. this.runSimplification(task);
  87647. }
  87648. else {
  87649. this.running = false;
  87650. }
  87651. };
  87652. SimplificationQueue.prototype.runSimplification = function (task) {
  87653. var _this = this;
  87654. if (task.parallelProcessing) {
  87655. //parallel simplifier
  87656. task.settings.forEach(function (setting) {
  87657. var simplifier = _this.getSimplifier(task);
  87658. simplifier.simplify(setting, function (newMesh) {
  87659. task.mesh.addLODLevel(setting.distance, newMesh);
  87660. newMesh.isVisible = true;
  87661. //check if it is the last
  87662. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  87663. //all done, run the success callback.
  87664. task.successCallback();
  87665. }
  87666. _this.executeNext();
  87667. });
  87668. });
  87669. }
  87670. else {
  87671. //single simplifier.
  87672. var simplifier = this.getSimplifier(task);
  87673. var runDecimation = function (setting, callback) {
  87674. simplifier.simplify(setting, function (newMesh) {
  87675. task.mesh.addLODLevel(setting.distance, newMesh);
  87676. newMesh.isVisible = true;
  87677. //run the next quality level
  87678. callback();
  87679. });
  87680. };
  87681. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  87682. runDecimation(task.settings[loop.index], function () {
  87683. loop.executeNext();
  87684. });
  87685. }, function () {
  87686. //execution ended, run the success callback.
  87687. if (task.successCallback) {
  87688. task.successCallback();
  87689. }
  87690. _this.executeNext();
  87691. });
  87692. }
  87693. };
  87694. SimplificationQueue.prototype.getSimplifier = function (task) {
  87695. switch (task.simplificationType) {
  87696. case SimplificationType.QUADRATIC:
  87697. default:
  87698. return new QuadraticErrorSimplification(task.mesh);
  87699. }
  87700. };
  87701. return SimplificationQueue;
  87702. }());
  87703. BABYLON.SimplificationQueue = SimplificationQueue;
  87704. /**
  87705. * The implemented types of simplification.
  87706. * At the moment only Quadratic Error Decimation is implemented.
  87707. */
  87708. var SimplificationType;
  87709. (function (SimplificationType) {
  87710. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  87711. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  87712. var DecimationTriangle = /** @class */ (function () {
  87713. function DecimationTriangle(vertices) {
  87714. this.vertices = vertices;
  87715. this.error = new Array(4);
  87716. this.deleted = false;
  87717. this.isDirty = false;
  87718. this.deletePending = false;
  87719. this.borderFactor = 0;
  87720. }
  87721. return DecimationTriangle;
  87722. }());
  87723. BABYLON.DecimationTriangle = DecimationTriangle;
  87724. var DecimationVertex = /** @class */ (function () {
  87725. function DecimationVertex(position, id) {
  87726. this.position = position;
  87727. this.id = id;
  87728. this.isBorder = true;
  87729. this.q = new QuadraticMatrix();
  87730. this.triangleCount = 0;
  87731. this.triangleStart = 0;
  87732. this.originalOffsets = [];
  87733. }
  87734. DecimationVertex.prototype.updatePosition = function (newPosition) {
  87735. this.position.copyFrom(newPosition);
  87736. };
  87737. return DecimationVertex;
  87738. }());
  87739. BABYLON.DecimationVertex = DecimationVertex;
  87740. var QuadraticMatrix = /** @class */ (function () {
  87741. function QuadraticMatrix(data) {
  87742. this.data = new Array(10);
  87743. for (var i = 0; i < 10; ++i) {
  87744. if (data && data[i]) {
  87745. this.data[i] = data[i];
  87746. }
  87747. else {
  87748. this.data[i] = 0;
  87749. }
  87750. }
  87751. }
  87752. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  87753. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  87754. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  87755. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  87756. return det;
  87757. };
  87758. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  87759. for (var i = 0; i < 10; ++i) {
  87760. this.data[i] += matrix.data[i];
  87761. }
  87762. };
  87763. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  87764. for (var i = 0; i < 10; ++i) {
  87765. this.data[i] += data[i];
  87766. }
  87767. };
  87768. QuadraticMatrix.prototype.add = function (matrix) {
  87769. var m = new QuadraticMatrix();
  87770. for (var i = 0; i < 10; ++i) {
  87771. m.data[i] = this.data[i] + matrix.data[i];
  87772. }
  87773. return m;
  87774. };
  87775. QuadraticMatrix.FromData = function (a, b, c, d) {
  87776. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  87777. };
  87778. //returning an array to avoid garbage collection
  87779. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  87780. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  87781. };
  87782. return QuadraticMatrix;
  87783. }());
  87784. BABYLON.QuadraticMatrix = QuadraticMatrix;
  87785. var Reference = /** @class */ (function () {
  87786. function Reference(vertexId, triangleId) {
  87787. this.vertexId = vertexId;
  87788. this.triangleId = triangleId;
  87789. }
  87790. return Reference;
  87791. }());
  87792. BABYLON.Reference = Reference;
  87793. /**
  87794. * An implementation of the Quadratic Error simplification algorithm.
  87795. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  87796. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  87797. * @author RaananW
  87798. */
  87799. var QuadraticErrorSimplification = /** @class */ (function () {
  87800. function QuadraticErrorSimplification(_mesh) {
  87801. this._mesh = _mesh;
  87802. this.syncIterations = 5000;
  87803. this.aggressiveness = 7;
  87804. this.decimationIterations = 100;
  87805. this.boundingBoxEpsilon = BABYLON.Epsilon;
  87806. }
  87807. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  87808. var _this = this;
  87809. this.initDecimatedMesh();
  87810. //iterating through the submeshes array, one after the other.
  87811. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  87812. _this.initWithMesh(loop.index, function () {
  87813. _this.runDecimation(settings, loop.index, function () {
  87814. loop.executeNext();
  87815. });
  87816. }, settings.optimizeMesh);
  87817. }, function () {
  87818. setTimeout(function () {
  87819. successCallback(_this._reconstructedMesh);
  87820. }, 0);
  87821. });
  87822. };
  87823. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  87824. var _this = this;
  87825. var targetCount = ~~(this.triangles.length * settings.quality);
  87826. var deletedTriangles = 0;
  87827. var triangleCount = this.triangles.length;
  87828. var iterationFunction = function (iteration, callback) {
  87829. setTimeout(function () {
  87830. if (iteration % 5 === 0) {
  87831. _this.updateMesh(iteration === 0);
  87832. }
  87833. for (var i = 0; i < _this.triangles.length; ++i) {
  87834. _this.triangles[i].isDirty = false;
  87835. }
  87836. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  87837. var trianglesIterator = function (i) {
  87838. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  87839. var t = _this.triangles[tIdx];
  87840. if (!t)
  87841. return;
  87842. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  87843. return;
  87844. }
  87845. for (var j = 0; j < 3; ++j) {
  87846. if (t.error[j] < threshold) {
  87847. var deleted0 = [];
  87848. var deleted1 = [];
  87849. var v0 = t.vertices[j];
  87850. var v1 = t.vertices[(j + 1) % 3];
  87851. if (v0.isBorder || v1.isBorder)
  87852. continue;
  87853. var p = BABYLON.Vector3.Zero();
  87854. var n = BABYLON.Vector3.Zero();
  87855. var uv = BABYLON.Vector2.Zero();
  87856. var color = new BABYLON.Color4(0, 0, 0, 1);
  87857. _this.calculateError(v0, v1, p, n, uv, color);
  87858. var delTr = new Array();
  87859. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  87860. continue;
  87861. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  87862. continue;
  87863. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  87864. continue;
  87865. var uniqueArray = new Array();
  87866. delTr.forEach(function (deletedT) {
  87867. if (uniqueArray.indexOf(deletedT) === -1) {
  87868. deletedT.deletePending = true;
  87869. uniqueArray.push(deletedT);
  87870. }
  87871. });
  87872. if (uniqueArray.length % 2 !== 0) {
  87873. continue;
  87874. }
  87875. v0.q = v1.q.add(v0.q);
  87876. v0.updatePosition(p);
  87877. var tStart = _this.references.length;
  87878. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  87879. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  87880. var tCount = _this.references.length - tStart;
  87881. if (tCount <= v0.triangleCount) {
  87882. if (tCount) {
  87883. for (var c = 0; c < tCount; c++) {
  87884. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  87885. }
  87886. }
  87887. }
  87888. else {
  87889. v0.triangleStart = tStart;
  87890. }
  87891. v0.triangleCount = tCount;
  87892. break;
  87893. }
  87894. }
  87895. };
  87896. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  87897. }, 0);
  87898. };
  87899. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  87900. if (triangleCount - deletedTriangles <= targetCount)
  87901. loop.breakLoop();
  87902. else {
  87903. iterationFunction(loop.index, function () {
  87904. loop.executeNext();
  87905. });
  87906. }
  87907. }, function () {
  87908. setTimeout(function () {
  87909. //reconstruct this part of the mesh
  87910. _this.reconstructMesh(submeshIndex);
  87911. successCallback();
  87912. }, 0);
  87913. });
  87914. };
  87915. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  87916. var _this = this;
  87917. this.vertices = [];
  87918. this.triangles = [];
  87919. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  87920. var indices = this._mesh.getIndices();
  87921. var submesh = this._mesh.subMeshes[submeshIndex];
  87922. var findInVertices = function (positionToSearch) {
  87923. if (optimizeMesh) {
  87924. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  87925. if (_this.vertices[ii].position.equals(positionToSearch)) {
  87926. return _this.vertices[ii];
  87927. }
  87928. }
  87929. }
  87930. return null;
  87931. };
  87932. var vertexReferences = [];
  87933. var vertexInit = function (i) {
  87934. if (!positionData) {
  87935. return;
  87936. }
  87937. var offset = i + submesh.verticesStart;
  87938. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  87939. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  87940. vertex.originalOffsets.push(offset);
  87941. if (vertex.id === _this.vertices.length) {
  87942. _this.vertices.push(vertex);
  87943. }
  87944. vertexReferences.push(vertex.id);
  87945. };
  87946. //var totalVertices = mesh.getTotalVertices();
  87947. var totalVertices = submesh.verticesCount;
  87948. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  87949. var indicesInit = function (i) {
  87950. if (!indices) {
  87951. return;
  87952. }
  87953. var offset = (submesh.indexStart / 3) + i;
  87954. var pos = (offset * 3);
  87955. var i0 = indices[pos + 0];
  87956. var i1 = indices[pos + 1];
  87957. var i2 = indices[pos + 2];
  87958. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  87959. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  87960. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  87961. var triangle = new DecimationTriangle([v0, v1, v2]);
  87962. triangle.originalOffset = pos;
  87963. _this.triangles.push(triangle);
  87964. };
  87965. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  87966. _this.init(callback);
  87967. });
  87968. });
  87969. };
  87970. QuadraticErrorSimplification.prototype.init = function (callback) {
  87971. var _this = this;
  87972. var triangleInit1 = function (i) {
  87973. var t = _this.triangles[i];
  87974. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  87975. for (var j = 0; j < 3; j++) {
  87976. 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))));
  87977. }
  87978. };
  87979. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  87980. var triangleInit2 = function (i) {
  87981. var t = _this.triangles[i];
  87982. for (var j = 0; j < 3; ++j) {
  87983. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  87984. }
  87985. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87986. };
  87987. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  87988. callback();
  87989. });
  87990. });
  87991. };
  87992. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  87993. var newTriangles = [];
  87994. var i;
  87995. for (i = 0; i < this.vertices.length; ++i) {
  87996. this.vertices[i].triangleCount = 0;
  87997. }
  87998. var t;
  87999. var j;
  88000. for (i = 0; i < this.triangles.length; ++i) {
  88001. if (!this.triangles[i].deleted) {
  88002. t = this.triangles[i];
  88003. for (j = 0; j < 3; ++j) {
  88004. t.vertices[j].triangleCount = 1;
  88005. }
  88006. newTriangles.push(t);
  88007. }
  88008. }
  88009. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  88010. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  88011. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  88012. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  88013. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  88014. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  88015. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  88016. var vertexCount = 0;
  88017. for (i = 0; i < this.vertices.length; ++i) {
  88018. var vertex = this.vertices[i];
  88019. vertex.id = vertexCount;
  88020. if (vertex.triangleCount) {
  88021. vertex.originalOffsets.forEach(function (originalOffset) {
  88022. if (!normalData) {
  88023. return;
  88024. }
  88025. newPositionData.push(vertex.position.x);
  88026. newPositionData.push(vertex.position.y);
  88027. newPositionData.push(vertex.position.z);
  88028. newNormalData.push(normalData[originalOffset * 3]);
  88029. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  88030. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  88031. if (uvs && uvs.length) {
  88032. newUVsData.push(uvs[(originalOffset * 2)]);
  88033. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  88034. }
  88035. else if (colorsData && colorsData.length) {
  88036. newColorsData.push(colorsData[(originalOffset * 4)]);
  88037. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  88038. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  88039. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  88040. }
  88041. ++vertexCount;
  88042. });
  88043. }
  88044. }
  88045. var startingIndex = this._reconstructedMesh.getTotalIndices();
  88046. var startingVertex = this._reconstructedMesh.getTotalVertices();
  88047. var submeshesArray = this._reconstructedMesh.subMeshes;
  88048. this._reconstructedMesh.subMeshes = [];
  88049. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  88050. var originalIndices = this._mesh.getIndices();
  88051. for (i = 0; i < newTriangles.length; ++i) {
  88052. t = newTriangles[i]; //now get the new referencing point for each vertex
  88053. [0, 1, 2].forEach(function (idx) {
  88054. var id = originalIndices[t.originalOffset + idx];
  88055. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  88056. if (offset < 0)
  88057. offset = 0;
  88058. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  88059. });
  88060. }
  88061. //overwriting the old vertex buffers and indices.
  88062. this._reconstructedMesh.setIndices(newIndicesArray);
  88063. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  88064. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  88065. if (newUVsData.length > 0)
  88066. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  88067. if (newColorsData.length > 0)
  88068. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  88069. //create submesh
  88070. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  88071. if (submeshIndex > 0) {
  88072. this._reconstructedMesh.subMeshes = [];
  88073. submeshesArray.forEach(function (submesh) {
  88074. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  88075. });
  88076. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  88077. }
  88078. };
  88079. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  88080. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  88081. this._reconstructedMesh.material = this._mesh.material;
  88082. this._reconstructedMesh.parent = this._mesh.parent;
  88083. this._reconstructedMesh.isVisible = false;
  88084. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  88085. };
  88086. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  88087. for (var i = 0; i < vertex1.triangleCount; ++i) {
  88088. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  88089. if (t.deleted)
  88090. continue;
  88091. var s = this.references[vertex1.triangleStart + i].vertexId;
  88092. var v1 = t.vertices[(s + 1) % 3];
  88093. var v2 = t.vertices[(s + 2) % 3];
  88094. if ((v1 === vertex2 || v2 === vertex2)) {
  88095. deletedArray[i] = true;
  88096. delTr.push(t);
  88097. continue;
  88098. }
  88099. var d1 = v1.position.subtract(point);
  88100. d1 = d1.normalize();
  88101. var d2 = v2.position.subtract(point);
  88102. d2 = d2.normalize();
  88103. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  88104. return true;
  88105. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  88106. deletedArray[i] = false;
  88107. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  88108. return true;
  88109. }
  88110. return false;
  88111. };
  88112. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  88113. var newDeleted = deletedTriangles;
  88114. for (var i = 0; i < vertex.triangleCount; ++i) {
  88115. var ref = this.references[vertex.triangleStart + i];
  88116. var t = this.triangles[ref.triangleId];
  88117. if (t.deleted)
  88118. continue;
  88119. if (deletedArray[i] && t.deletePending) {
  88120. t.deleted = true;
  88121. newDeleted++;
  88122. continue;
  88123. }
  88124. t.vertices[ref.vertexId] = origVertex;
  88125. t.isDirty = true;
  88126. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  88127. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  88128. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  88129. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88130. this.references.push(ref);
  88131. }
  88132. return newDeleted;
  88133. };
  88134. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  88135. for (var i = 0; i < this.vertices.length; ++i) {
  88136. var vCount = [];
  88137. var vId = [];
  88138. var v = this.vertices[i];
  88139. var j;
  88140. for (j = 0; j < v.triangleCount; ++j) {
  88141. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  88142. for (var ii = 0; ii < 3; ii++) {
  88143. var ofs = 0;
  88144. var vv = triangle.vertices[ii];
  88145. while (ofs < vCount.length) {
  88146. if (vId[ofs] === vv.id)
  88147. break;
  88148. ++ofs;
  88149. }
  88150. if (ofs === vCount.length) {
  88151. vCount.push(1);
  88152. vId.push(vv.id);
  88153. }
  88154. else {
  88155. vCount[ofs]++;
  88156. }
  88157. }
  88158. }
  88159. for (j = 0; j < vCount.length; ++j) {
  88160. if (vCount[j] === 1) {
  88161. this.vertices[vId[j]].isBorder = true;
  88162. }
  88163. else {
  88164. this.vertices[vId[j]].isBorder = false;
  88165. }
  88166. }
  88167. }
  88168. };
  88169. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  88170. if (identifyBorders === void 0) { identifyBorders = false; }
  88171. var i;
  88172. if (!identifyBorders) {
  88173. var newTrianglesVector = [];
  88174. for (i = 0; i < this.triangles.length; ++i) {
  88175. if (!this.triangles[i].deleted) {
  88176. newTrianglesVector.push(this.triangles[i]);
  88177. }
  88178. }
  88179. this.triangles = newTrianglesVector;
  88180. }
  88181. for (i = 0; i < this.vertices.length; ++i) {
  88182. this.vertices[i].triangleCount = 0;
  88183. this.vertices[i].triangleStart = 0;
  88184. }
  88185. var t;
  88186. var j;
  88187. var v;
  88188. for (i = 0; i < this.triangles.length; ++i) {
  88189. t = this.triangles[i];
  88190. for (j = 0; j < 3; ++j) {
  88191. v = t.vertices[j];
  88192. v.triangleCount++;
  88193. }
  88194. }
  88195. var tStart = 0;
  88196. for (i = 0; i < this.vertices.length; ++i) {
  88197. this.vertices[i].triangleStart = tStart;
  88198. tStart += this.vertices[i].triangleCount;
  88199. this.vertices[i].triangleCount = 0;
  88200. }
  88201. var newReferences = new Array(this.triangles.length * 3);
  88202. for (i = 0; i < this.triangles.length; ++i) {
  88203. t = this.triangles[i];
  88204. for (j = 0; j < 3; ++j) {
  88205. v = t.vertices[j];
  88206. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  88207. v.triangleCount++;
  88208. }
  88209. }
  88210. this.references = newReferences;
  88211. if (identifyBorders) {
  88212. this.identifyBorder();
  88213. }
  88214. };
  88215. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  88216. var x = point.x;
  88217. var y = point.y;
  88218. var z = point.z;
  88219. 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
  88220. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  88221. };
  88222. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  88223. var q = vertex1.q.add(vertex2.q);
  88224. var border = vertex1.isBorder && vertex2.isBorder;
  88225. var error = 0;
  88226. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  88227. if (qDet !== 0 && !border) {
  88228. if (!pointResult) {
  88229. pointResult = BABYLON.Vector3.Zero();
  88230. }
  88231. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  88232. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  88233. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  88234. error = this.vertexError(q, pointResult);
  88235. }
  88236. else {
  88237. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  88238. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  88239. var error1 = this.vertexError(q, vertex1.position);
  88240. var error2 = this.vertexError(q, vertex2.position);
  88241. var error3 = this.vertexError(q, p3);
  88242. error = Math.min(error1, error2, error3);
  88243. if (error === error1) {
  88244. if (pointResult) {
  88245. pointResult.copyFrom(vertex1.position);
  88246. }
  88247. }
  88248. else if (error === error2) {
  88249. if (pointResult) {
  88250. pointResult.copyFrom(vertex2.position);
  88251. }
  88252. }
  88253. else {
  88254. if (pointResult) {
  88255. pointResult.copyFrom(p3);
  88256. }
  88257. }
  88258. }
  88259. return error;
  88260. };
  88261. return QuadraticErrorSimplification;
  88262. }());
  88263. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  88264. })(BABYLON || (BABYLON = {}));
  88265. //# sourceMappingURL=babylon.meshSimplification.js.map
  88266. "use strict";
  88267. var BABYLON;
  88268. (function (BABYLON) {
  88269. var MeshLODLevel = /** @class */ (function () {
  88270. function MeshLODLevel(distance, mesh) {
  88271. this.distance = distance;
  88272. this.mesh = mesh;
  88273. }
  88274. return MeshLODLevel;
  88275. }());
  88276. BABYLON.MeshLODLevel = MeshLODLevel;
  88277. })(BABYLON || (BABYLON = {}));
  88278. //# sourceMappingURL=babylon.meshLODLevel.js.map
  88279. "use strict";
  88280. var BABYLON;
  88281. (function (BABYLON) {
  88282. /**
  88283. * Defines the root class used to create scene optimization to use with SceneOptimizer
  88284. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88285. */
  88286. var SceneOptimization = /** @class */ (function () {
  88287. /**
  88288. * Creates the SceneOptimization object
  88289. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88290. * @param desc defines the description associated with the optimization
  88291. */
  88292. function SceneOptimization(
  88293. /**
  88294. * Defines the priority of this optimization (0 by default which means first in the list)
  88295. */
  88296. priority) {
  88297. if (priority === void 0) { priority = 0; }
  88298. this.priority = priority;
  88299. }
  88300. /**
  88301. * Gets a string describing the action executed by the current optimization
  88302. * @returns description string
  88303. */
  88304. SceneOptimization.prototype.getDescription = function () {
  88305. return "";
  88306. };
  88307. /**
  88308. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88309. * @param scene defines the current scene where to apply this optimization
  88310. * @param optimizer defines the current optimizer
  88311. * @returns true if everything that can be done was applied
  88312. */
  88313. SceneOptimization.prototype.apply = function (scene, optimizer) {
  88314. return true;
  88315. };
  88316. ;
  88317. return SceneOptimization;
  88318. }());
  88319. BABYLON.SceneOptimization = SceneOptimization;
  88320. /**
  88321. * Defines an optimization used to reduce the size of render target textures
  88322. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88323. */
  88324. var TextureOptimization = /** @class */ (function (_super) {
  88325. __extends(TextureOptimization, _super);
  88326. /**
  88327. * Creates the TextureOptimization object
  88328. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88329. * @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
  88330. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  88331. */
  88332. function TextureOptimization(
  88333. /**
  88334. * Defines the priority of this optimization (0 by default which means first in the list)
  88335. */
  88336. priority,
  88337. /**
  88338. * 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
  88339. */
  88340. maximumSize,
  88341. /**
  88342. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  88343. */
  88344. step) {
  88345. if (priority === void 0) { priority = 0; }
  88346. if (maximumSize === void 0) { maximumSize = 1024; }
  88347. if (step === void 0) { step = 0.5; }
  88348. var _this = _super.call(this, priority) || this;
  88349. _this.priority = priority;
  88350. _this.maximumSize = maximumSize;
  88351. _this.step = step;
  88352. return _this;
  88353. }
  88354. /**
  88355. * Gets a string describing the action executed by the current optimization
  88356. * @returns description string
  88357. */
  88358. TextureOptimization.prototype.getDescription = function () {
  88359. return "Reducing render target texture size to " + this.maximumSize;
  88360. };
  88361. /**
  88362. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88363. * @param scene defines the current scene where to apply this optimization
  88364. * @param optimizer defines the current optimizer
  88365. * @returns true if everything that can be done was applied
  88366. */
  88367. TextureOptimization.prototype.apply = function (scene, optimizer) {
  88368. var allDone = true;
  88369. for (var index = 0; index < scene.textures.length; index++) {
  88370. var texture = scene.textures[index];
  88371. if (!texture.canRescale || texture.getContext) {
  88372. continue;
  88373. }
  88374. var currentSize = texture.getSize();
  88375. var maxDimension = Math.max(currentSize.width, currentSize.height);
  88376. if (maxDimension > this.maximumSize) {
  88377. texture.scale(this.step);
  88378. allDone = false;
  88379. }
  88380. }
  88381. return allDone;
  88382. };
  88383. return TextureOptimization;
  88384. }(SceneOptimization));
  88385. BABYLON.TextureOptimization = TextureOptimization;
  88386. /**
  88387. * Defines an optimization used to increase or decrease the rendering resolution
  88388. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88389. */
  88390. var HardwareScalingOptimization = /** @class */ (function (_super) {
  88391. __extends(HardwareScalingOptimization, _super);
  88392. /**
  88393. * Creates the HardwareScalingOptimization object
  88394. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88395. * @param maximumScale defines the maximum scale to use (2 by default)
  88396. * @param step defines the step to use between two passes (0.5 by default)
  88397. */
  88398. function HardwareScalingOptimization(
  88399. /**
  88400. * Defines the priority of this optimization (0 by default which means first in the list)
  88401. */
  88402. priority,
  88403. /**
  88404. * Defines the maximum scale to use (2 by default)
  88405. */
  88406. maximumScale,
  88407. /**
  88408. * Defines the step to use between two passes (0.5 by default)
  88409. */
  88410. step) {
  88411. if (priority === void 0) { priority = 0; }
  88412. if (maximumScale === void 0) { maximumScale = 2; }
  88413. if (step === void 0) { step = 0.25; }
  88414. var _this = _super.call(this, priority) || this;
  88415. _this.priority = priority;
  88416. _this.maximumScale = maximumScale;
  88417. _this.step = step;
  88418. _this._currentScale = -1;
  88419. _this._directionOffset = 1;
  88420. return _this;
  88421. }
  88422. /**
  88423. * Gets a string describing the action executed by the current optimization
  88424. * @return description string
  88425. */
  88426. HardwareScalingOptimization.prototype.getDescription = function () {
  88427. return "Setting hardware scaling level to " + this._currentScale;
  88428. };
  88429. /**
  88430. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88431. * @param scene defines the current scene where to apply this optimization
  88432. * @param optimizer defines the current optimizer
  88433. * @returns true if everything that can be done was applied
  88434. */
  88435. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  88436. if (this._currentScale === -1) {
  88437. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  88438. if (this._currentScale > this.maximumScale) {
  88439. this._directionOffset = -1;
  88440. }
  88441. }
  88442. this._currentScale += this._directionOffset * this.step;
  88443. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  88444. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  88445. };
  88446. ;
  88447. return HardwareScalingOptimization;
  88448. }(SceneOptimization));
  88449. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  88450. /**
  88451. * Defines an optimization used to remove shadows
  88452. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88453. */
  88454. var ShadowsOptimization = /** @class */ (function (_super) {
  88455. __extends(ShadowsOptimization, _super);
  88456. function ShadowsOptimization() {
  88457. return _super !== null && _super.apply(this, arguments) || this;
  88458. }
  88459. /**
  88460. * Gets a string describing the action executed by the current optimization
  88461. * @return description string
  88462. */
  88463. ShadowsOptimization.prototype.getDescription = function () {
  88464. return "Turning shadows on/off";
  88465. };
  88466. /**
  88467. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88468. * @param scene defines the current scene where to apply this optimization
  88469. * @param optimizer defines the current optimizer
  88470. * @returns true if everything that can be done was applied
  88471. */
  88472. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  88473. scene.shadowsEnabled = optimizer.isInImprovementMode;
  88474. return true;
  88475. };
  88476. ;
  88477. return ShadowsOptimization;
  88478. }(SceneOptimization));
  88479. BABYLON.ShadowsOptimization = ShadowsOptimization;
  88480. /**
  88481. * Defines an optimization used to turn post-processes off
  88482. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88483. */
  88484. var PostProcessesOptimization = /** @class */ (function (_super) {
  88485. __extends(PostProcessesOptimization, _super);
  88486. function PostProcessesOptimization() {
  88487. return _super !== null && _super.apply(this, arguments) || this;
  88488. }
  88489. /**
  88490. * Gets a string describing the action executed by the current optimization
  88491. * @return description string
  88492. */
  88493. PostProcessesOptimization.prototype.getDescription = function () {
  88494. return "Turning post-processes on/off";
  88495. };
  88496. /**
  88497. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88498. * @param scene defines the current scene where to apply this optimization
  88499. * @param optimizer defines the current optimizer
  88500. * @returns true if everything that can be done was applied
  88501. */
  88502. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  88503. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  88504. return true;
  88505. };
  88506. ;
  88507. return PostProcessesOptimization;
  88508. }(SceneOptimization));
  88509. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  88510. /**
  88511. * Defines an optimization used to turn lens flares off
  88512. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88513. */
  88514. var LensFlaresOptimization = /** @class */ (function (_super) {
  88515. __extends(LensFlaresOptimization, _super);
  88516. function LensFlaresOptimization() {
  88517. return _super !== null && _super.apply(this, arguments) || this;
  88518. }
  88519. /**
  88520. * Gets a string describing the action executed by the current optimization
  88521. * @return description string
  88522. */
  88523. LensFlaresOptimization.prototype.getDescription = function () {
  88524. return "Turning lens flares on/off";
  88525. };
  88526. /**
  88527. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88528. * @param scene defines the current scene where to apply this optimization
  88529. * @param optimizer defines the current optimizer
  88530. * @returns true if everything that can be done was applied
  88531. */
  88532. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  88533. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  88534. return true;
  88535. };
  88536. ;
  88537. return LensFlaresOptimization;
  88538. }(SceneOptimization));
  88539. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  88540. /**
  88541. * Defines an optimization based on user defined callback.
  88542. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88543. */
  88544. var CustomOptimization = /** @class */ (function (_super) {
  88545. __extends(CustomOptimization, _super);
  88546. function CustomOptimization() {
  88547. return _super !== null && _super.apply(this, arguments) || this;
  88548. }
  88549. /**
  88550. * Gets a string describing the action executed by the current optimization
  88551. * @returns description string
  88552. */
  88553. CustomOptimization.prototype.getDescription = function () {
  88554. if (this.onGetDescription) {
  88555. return this.onGetDescription();
  88556. }
  88557. return "Running user defined callback";
  88558. };
  88559. /**
  88560. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88561. * @param scene defines the current scene where to apply this optimization
  88562. * @param optimizer defines the current optimizer
  88563. * @returns true if everything that can be done was applied
  88564. */
  88565. CustomOptimization.prototype.apply = function (scene, optimizer) {
  88566. if (this.onApply) {
  88567. return this.onApply(scene, optimizer);
  88568. }
  88569. return true;
  88570. };
  88571. ;
  88572. return CustomOptimization;
  88573. }(SceneOptimization));
  88574. BABYLON.CustomOptimization = CustomOptimization;
  88575. /**
  88576. * Defines an optimization used to turn particles off
  88577. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88578. */
  88579. var ParticlesOptimization = /** @class */ (function (_super) {
  88580. __extends(ParticlesOptimization, _super);
  88581. function ParticlesOptimization() {
  88582. return _super !== null && _super.apply(this, arguments) || this;
  88583. }
  88584. /**
  88585. * Gets a string describing the action executed by the current optimization
  88586. * @return description string
  88587. */
  88588. ParticlesOptimization.prototype.getDescription = function () {
  88589. return "Turning particles on/off";
  88590. };
  88591. /**
  88592. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88593. * @param scene defines the current scene where to apply this optimization
  88594. * @param optimizer defines the current optimizer
  88595. * @returns true if everything that can be done was applied
  88596. */
  88597. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  88598. scene.particlesEnabled = optimizer.isInImprovementMode;
  88599. return true;
  88600. };
  88601. ;
  88602. return ParticlesOptimization;
  88603. }(SceneOptimization));
  88604. BABYLON.ParticlesOptimization = ParticlesOptimization;
  88605. /**
  88606. * Defines an optimization used to turn render targets off
  88607. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88608. */
  88609. var RenderTargetsOptimization = /** @class */ (function (_super) {
  88610. __extends(RenderTargetsOptimization, _super);
  88611. function RenderTargetsOptimization() {
  88612. return _super !== null && _super.apply(this, arguments) || this;
  88613. }
  88614. /**
  88615. * Gets a string describing the action executed by the current optimization
  88616. * @return description string
  88617. */
  88618. RenderTargetsOptimization.prototype.getDescription = function () {
  88619. return "Turning render targets off";
  88620. };
  88621. /**
  88622. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88623. * @param scene defines the current scene where to apply this optimization
  88624. * @param optimizer defines the current optimizer
  88625. * @returns true if everything that can be done was applied
  88626. */
  88627. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  88628. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  88629. return true;
  88630. };
  88631. ;
  88632. return RenderTargetsOptimization;
  88633. }(SceneOptimization));
  88634. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  88635. /**
  88636. * Defines an optimization used to merge meshes with compatible materials
  88637. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88638. */
  88639. var MergeMeshesOptimization = /** @class */ (function (_super) {
  88640. __extends(MergeMeshesOptimization, _super);
  88641. function MergeMeshesOptimization() {
  88642. var _this = _super !== null && _super.apply(this, arguments) || this;
  88643. _this._canBeMerged = function (abstractMesh) {
  88644. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  88645. return false;
  88646. }
  88647. var mesh = abstractMesh;
  88648. if (!mesh.isVisible || !mesh.isEnabled()) {
  88649. return false;
  88650. }
  88651. if (mesh.instances.length > 0) {
  88652. return false;
  88653. }
  88654. if (mesh.skeleton || mesh.hasLODLevels) {
  88655. return false;
  88656. }
  88657. if (mesh.parent) {
  88658. return false;
  88659. }
  88660. return true;
  88661. };
  88662. return _this;
  88663. }
  88664. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  88665. /**
  88666. * Gets or sets a boolean which defines if optimization octree has to be updated
  88667. */
  88668. get: function () {
  88669. return MergeMeshesOptimization._UpdateSelectionTree;
  88670. },
  88671. /**
  88672. * Gets or sets a boolean which defines if optimization octree has to be updated
  88673. */
  88674. set: function (value) {
  88675. MergeMeshesOptimization._UpdateSelectionTree = value;
  88676. },
  88677. enumerable: true,
  88678. configurable: true
  88679. });
  88680. /**
  88681. * Gets a string describing the action executed by the current optimization
  88682. * @return description string
  88683. */
  88684. MergeMeshesOptimization.prototype.getDescription = function () {
  88685. return "Merging similar meshes together";
  88686. };
  88687. /**
  88688. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88689. * @param scene defines the current scene where to apply this optimization
  88690. * @param optimizer defines the current optimizer
  88691. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  88692. * @returns true if everything that can be done was applied
  88693. */
  88694. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  88695. var globalPool = scene.meshes.slice(0);
  88696. var globalLength = globalPool.length;
  88697. for (var index = 0; index < globalLength; index++) {
  88698. var currentPool = new Array();
  88699. var current = globalPool[index];
  88700. // Checks
  88701. if (!this._canBeMerged(current)) {
  88702. continue;
  88703. }
  88704. currentPool.push(current);
  88705. // Find compatible meshes
  88706. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  88707. var otherMesh = globalPool[subIndex];
  88708. if (!this._canBeMerged(otherMesh)) {
  88709. continue;
  88710. }
  88711. if (otherMesh.material !== current.material) {
  88712. continue;
  88713. }
  88714. if (otherMesh.checkCollisions !== current.checkCollisions) {
  88715. continue;
  88716. }
  88717. currentPool.push(otherMesh);
  88718. globalLength--;
  88719. globalPool.splice(subIndex, 1);
  88720. subIndex--;
  88721. }
  88722. if (currentPool.length < 2) {
  88723. continue;
  88724. }
  88725. // Merge meshes
  88726. BABYLON.Mesh.MergeMeshes(currentPool);
  88727. }
  88728. if (updateSelectionTree != undefined) {
  88729. if (updateSelectionTree) {
  88730. scene.createOrUpdateSelectionOctree();
  88731. }
  88732. }
  88733. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  88734. scene.createOrUpdateSelectionOctree();
  88735. }
  88736. return true;
  88737. };
  88738. ;
  88739. MergeMeshesOptimization._UpdateSelectionTree = false;
  88740. return MergeMeshesOptimization;
  88741. }(SceneOptimization));
  88742. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  88743. /**
  88744. * Defines a list of options used by SceneOptimizer
  88745. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88746. */
  88747. var SceneOptimizerOptions = /** @class */ (function () {
  88748. /**
  88749. * Creates a new list of options used by SceneOptimizer
  88750. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  88751. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  88752. */
  88753. function SceneOptimizerOptions(
  88754. /**
  88755. * Defines the target frame rate to reach (60 by default)
  88756. */
  88757. targetFrameRate,
  88758. /**
  88759. * Defines the interval between two checkes (2000ms by default)
  88760. */
  88761. trackerDuration) {
  88762. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  88763. if (trackerDuration === void 0) { trackerDuration = 2000; }
  88764. this.targetFrameRate = targetFrameRate;
  88765. this.trackerDuration = trackerDuration;
  88766. /**
  88767. * Gets the list of optimizations to apply
  88768. */
  88769. this.optimizations = new Array();
  88770. }
  88771. /**
  88772. * Add a new optimization
  88773. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  88774. * @returns the current SceneOptimizerOptions
  88775. */
  88776. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  88777. this.optimizations.push(optimization);
  88778. return this;
  88779. };
  88780. /**
  88781. * Add a new custom optimization
  88782. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  88783. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  88784. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88785. * @returns the current SceneOptimizerOptions
  88786. */
  88787. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  88788. if (priority === void 0) { priority = 0; }
  88789. var optimization = new CustomOptimization(priority);
  88790. optimization.onApply = onApply;
  88791. optimization.onGetDescription = onGetDescription;
  88792. this.optimizations.push(optimization);
  88793. return this;
  88794. };
  88795. /**
  88796. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  88797. * @param targetFrameRate defines the target frame rate (60 by default)
  88798. * @returns a SceneOptimizerOptions object
  88799. */
  88800. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  88801. var result = new SceneOptimizerOptions(targetFrameRate);
  88802. var priority = 0;
  88803. result.addOptimization(new MergeMeshesOptimization(priority));
  88804. result.addOptimization(new ShadowsOptimization(priority));
  88805. result.addOptimization(new LensFlaresOptimization(priority));
  88806. // Next priority
  88807. priority++;
  88808. result.addOptimization(new PostProcessesOptimization(priority));
  88809. result.addOptimization(new ParticlesOptimization(priority));
  88810. // Next priority
  88811. priority++;
  88812. result.addOptimization(new TextureOptimization(priority, 1024));
  88813. return result;
  88814. };
  88815. /**
  88816. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  88817. * @param targetFrameRate defines the target frame rate (60 by default)
  88818. * @returns a SceneOptimizerOptions object
  88819. */
  88820. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  88821. var result = new SceneOptimizerOptions(targetFrameRate);
  88822. var priority = 0;
  88823. result.addOptimization(new MergeMeshesOptimization(priority));
  88824. result.addOptimization(new ShadowsOptimization(priority));
  88825. result.addOptimization(new LensFlaresOptimization(priority));
  88826. // Next priority
  88827. priority++;
  88828. result.addOptimization(new PostProcessesOptimization(priority));
  88829. result.addOptimization(new ParticlesOptimization(priority));
  88830. // Next priority
  88831. priority++;
  88832. result.addOptimization(new TextureOptimization(priority, 512));
  88833. // Next priority
  88834. priority++;
  88835. result.addOptimization(new RenderTargetsOptimization(priority));
  88836. // Next priority
  88837. priority++;
  88838. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  88839. return result;
  88840. };
  88841. /**
  88842. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  88843. * @param targetFrameRate defines the target frame rate (60 by default)
  88844. * @returns a SceneOptimizerOptions object
  88845. */
  88846. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  88847. var result = new SceneOptimizerOptions(targetFrameRate);
  88848. var priority = 0;
  88849. result.addOptimization(new MergeMeshesOptimization(priority));
  88850. result.addOptimization(new ShadowsOptimization(priority));
  88851. result.addOptimization(new LensFlaresOptimization(priority));
  88852. // Next priority
  88853. priority++;
  88854. result.addOptimization(new PostProcessesOptimization(priority));
  88855. result.addOptimization(new ParticlesOptimization(priority));
  88856. // Next priority
  88857. priority++;
  88858. result.addOptimization(new TextureOptimization(priority, 256));
  88859. // Next priority
  88860. priority++;
  88861. result.addOptimization(new RenderTargetsOptimization(priority));
  88862. // Next priority
  88863. priority++;
  88864. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  88865. return result;
  88866. };
  88867. return SceneOptimizerOptions;
  88868. }());
  88869. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  88870. /**
  88871. * Class used to run optimizations in order to reach a target frame rate
  88872. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88873. */
  88874. var SceneOptimizer = /** @class */ (function () {
  88875. /**
  88876. * Creates a new SceneOptimizer
  88877. * @param scene defines the scene to work on
  88878. * @param options defines the options to use with the SceneOptimizer
  88879. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  88880. * @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)
  88881. */
  88882. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  88883. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  88884. if (improvementMode === void 0) { improvementMode = false; }
  88885. var _this = this;
  88886. this._isRunning = false;
  88887. this._currentPriorityLevel = 0;
  88888. this._targetFrameRate = 60;
  88889. this._trackerDuration = 2000;
  88890. this._currentFrameRate = 0;
  88891. this._improvementMode = false;
  88892. /**
  88893. * Defines an observable called when the optimizer reaches the target frame rate
  88894. */
  88895. this.onSuccessObservable = new BABYLON.Observable();
  88896. /**
  88897. * Defines an observable called when the optimizer enables an optimization
  88898. */
  88899. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  88900. /**
  88901. * Defines an observable called when the optimizer is not able to reach the target frame rate
  88902. */
  88903. this.onFailureObservable = new BABYLON.Observable();
  88904. if (!options) {
  88905. this._options = new SceneOptimizerOptions();
  88906. }
  88907. else {
  88908. this._options = options;
  88909. }
  88910. if (this._options.targetFrameRate) {
  88911. this._targetFrameRate = this._options.targetFrameRate;
  88912. }
  88913. if (this._options.trackerDuration) {
  88914. this._trackerDuration = this._options.trackerDuration;
  88915. }
  88916. if (autoGeneratePriorities) {
  88917. var priority = 0;
  88918. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  88919. var optim = _a[_i];
  88920. optim.priority = priority++;
  88921. }
  88922. }
  88923. this._improvementMode = improvementMode;
  88924. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88925. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  88926. _this._sceneDisposeObserver = null;
  88927. _this.dispose();
  88928. });
  88929. }
  88930. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  88931. /**
  88932. * Gets a boolean indicating if the optimizer is in improvement mode
  88933. */
  88934. get: function () {
  88935. return this._improvementMode;
  88936. },
  88937. enumerable: true,
  88938. configurable: true
  88939. });
  88940. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  88941. /**
  88942. * Gets the current priority level (0 at start)
  88943. */
  88944. get: function () {
  88945. return this._currentPriorityLevel;
  88946. },
  88947. enumerable: true,
  88948. configurable: true
  88949. });
  88950. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  88951. /**
  88952. * Gets the current frame rate checked by the SceneOptimizer
  88953. */
  88954. get: function () {
  88955. return this._currentFrameRate;
  88956. },
  88957. enumerable: true,
  88958. configurable: true
  88959. });
  88960. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  88961. /**
  88962. * Gets or sets the current target frame rate (60 by default)
  88963. */
  88964. get: function () {
  88965. return this._targetFrameRate;
  88966. },
  88967. /**
  88968. * Gets or sets the current target frame rate (60 by default)
  88969. */
  88970. set: function (value) {
  88971. this._targetFrameRate = value;
  88972. },
  88973. enumerable: true,
  88974. configurable: true
  88975. });
  88976. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  88977. /**
  88978. * Gets or sets the current interval between two checks (every 2000ms by default)
  88979. */
  88980. get: function () {
  88981. return this._trackerDuration;
  88982. },
  88983. /**
  88984. * Gets or sets the current interval between two checks (every 2000ms by default)
  88985. */
  88986. set: function (value) {
  88987. this._trackerDuration = value;
  88988. },
  88989. enumerable: true,
  88990. configurable: true
  88991. });
  88992. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  88993. /**
  88994. * Gets the list of active optimizations
  88995. */
  88996. get: function () {
  88997. return this._options.optimizations;
  88998. },
  88999. enumerable: true,
  89000. configurable: true
  89001. });
  89002. /**
  89003. * Stops the current optimizer
  89004. */
  89005. SceneOptimizer.prototype.stop = function () {
  89006. this._isRunning = false;
  89007. };
  89008. /**
  89009. * Reset the optimizer to initial step (current priority level = 0)
  89010. */
  89011. SceneOptimizer.prototype.reset = function () {
  89012. this._currentPriorityLevel = 0;
  89013. };
  89014. /**
  89015. * Start the optimizer. By default it will try to reach a specific framerate
  89016. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  89017. */
  89018. SceneOptimizer.prototype.start = function () {
  89019. var _this = this;
  89020. if (this._isRunning) {
  89021. return;
  89022. }
  89023. this._isRunning = true;
  89024. // Let's wait for the scene to be ready before running our check
  89025. this._scene.executeWhenReady(function () {
  89026. setTimeout(function () {
  89027. _this._checkCurrentState();
  89028. }, _this._trackerDuration);
  89029. });
  89030. };
  89031. SceneOptimizer.prototype._checkCurrentState = function () {
  89032. var _this = this;
  89033. if (!this._isRunning) {
  89034. return;
  89035. }
  89036. var scene = this._scene;
  89037. var options = this._options;
  89038. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  89039. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  89040. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  89041. this._isRunning = false;
  89042. this.onSuccessObservable.notifyObservers(this);
  89043. return;
  89044. }
  89045. // Apply current level of optimizations
  89046. var allDone = true;
  89047. var noOptimizationApplied = true;
  89048. for (var index = 0; index < options.optimizations.length; index++) {
  89049. var optimization = options.optimizations[index];
  89050. if (optimization.priority === this._currentPriorityLevel) {
  89051. noOptimizationApplied = false;
  89052. allDone = allDone && optimization.apply(scene, this);
  89053. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  89054. }
  89055. }
  89056. // If no optimization was applied, this is a failure :(
  89057. if (noOptimizationApplied) {
  89058. this._isRunning = false;
  89059. this.onFailureObservable.notifyObservers(this);
  89060. return;
  89061. }
  89062. // If all optimizations were done, move to next level
  89063. if (allDone) {
  89064. this._currentPriorityLevel++;
  89065. }
  89066. // Let's the system running for a specific amount of time before checking FPS
  89067. scene.executeWhenReady(function () {
  89068. setTimeout(function () {
  89069. _this._checkCurrentState();
  89070. }, _this._trackerDuration);
  89071. });
  89072. };
  89073. /**
  89074. * Release all resources
  89075. */
  89076. SceneOptimizer.prototype.dispose = function () {
  89077. this.stop();
  89078. this.onSuccessObservable.clear();
  89079. this.onFailureObservable.clear();
  89080. this.onNewOptimizationAppliedObservable.clear();
  89081. if (this._sceneDisposeObserver) {
  89082. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89083. }
  89084. };
  89085. /**
  89086. * Helper function to create a SceneOptimizer with one single line of code
  89087. * @param scene defines the scene to work on
  89088. * @param options defines the options to use with the SceneOptimizer
  89089. * @param onSuccess defines a callback to call on success
  89090. * @param onFailure defines a callback to call on failure
  89091. * @returns the new SceneOptimizer object
  89092. */
  89093. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  89094. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  89095. if (onSuccess) {
  89096. optimizer.onSuccessObservable.add(function () {
  89097. onSuccess();
  89098. });
  89099. }
  89100. if (onFailure) {
  89101. optimizer.onFailureObservable.add(function () {
  89102. onFailure();
  89103. });
  89104. }
  89105. optimizer.start();
  89106. return optimizer;
  89107. };
  89108. return SceneOptimizer;
  89109. }());
  89110. BABYLON.SceneOptimizer = SceneOptimizer;
  89111. })(BABYLON || (BABYLON = {}));
  89112. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  89113. "use strict";
  89114. var BABYLON;
  89115. (function (BABYLON) {
  89116. var OutlineRenderer = /** @class */ (function () {
  89117. function OutlineRenderer(scene) {
  89118. this.zOffset = 1;
  89119. this._scene = scene;
  89120. }
  89121. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  89122. var _this = this;
  89123. if (useOverlay === void 0) { useOverlay = false; }
  89124. var scene = this._scene;
  89125. var engine = this._scene.getEngine();
  89126. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89127. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  89128. return;
  89129. }
  89130. var mesh = subMesh.getRenderingMesh();
  89131. var material = subMesh.getMaterial();
  89132. if (!material || !scene.activeCamera) {
  89133. return;
  89134. }
  89135. engine.enableEffect(this._effect);
  89136. // Logarithmic depth
  89137. if (material.useLogarithmicDepth) {
  89138. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  89139. }
  89140. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  89141. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  89142. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  89143. // Bones
  89144. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89145. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89146. }
  89147. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  89148. // Alpha test
  89149. if (material && material.needAlphaTesting()) {
  89150. var alphaTexture = material.getAlphaTestTexture();
  89151. if (alphaTexture) {
  89152. this._effect.setTexture("diffuseSampler", alphaTexture);
  89153. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89154. }
  89155. }
  89156. engine.setZOffset(-this.zOffset);
  89157. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  89158. engine.setZOffset(0);
  89159. };
  89160. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  89161. var defines = [];
  89162. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89163. var mesh = subMesh.getMesh();
  89164. var material = subMesh.getMaterial();
  89165. if (material) {
  89166. // Alpha test
  89167. if (material.needAlphaTesting()) {
  89168. defines.push("#define ALPHATEST");
  89169. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89170. attribs.push(BABYLON.VertexBuffer.UVKind);
  89171. defines.push("#define UV1");
  89172. }
  89173. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  89174. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89175. defines.push("#define UV2");
  89176. }
  89177. }
  89178. //Logarithmic depth
  89179. if (material.useLogarithmicDepth) {
  89180. defines.push("#define LOGARITHMICDEPTH");
  89181. }
  89182. }
  89183. // Bones
  89184. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89185. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89186. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89187. if (mesh.numBoneInfluencers > 4) {
  89188. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  89189. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  89190. }
  89191. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89192. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  89193. }
  89194. else {
  89195. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89196. }
  89197. // Instances
  89198. if (useInstances) {
  89199. defines.push("#define INSTANCES");
  89200. attribs.push("world0");
  89201. attribs.push("world1");
  89202. attribs.push("world2");
  89203. attribs.push("world3");
  89204. }
  89205. // Get correct effect
  89206. var join = defines.join("\n");
  89207. if (this._cachedDefines !== join) {
  89208. this._cachedDefines = join;
  89209. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  89210. }
  89211. return this._effect.isReady();
  89212. };
  89213. return OutlineRenderer;
  89214. }());
  89215. BABYLON.OutlineRenderer = OutlineRenderer;
  89216. })(BABYLON || (BABYLON = {}));
  89217. //# sourceMappingURL=babylon.outlineRenderer.js.map
  89218. "use strict";
  89219. var BABYLON;
  89220. (function (BABYLON) {
  89221. var FaceAdjacencies = /** @class */ (function () {
  89222. function FaceAdjacencies() {
  89223. this.edges = new Array();
  89224. this.edgesConnectedCount = 0;
  89225. }
  89226. return FaceAdjacencies;
  89227. }());
  89228. var EdgesRenderer = /** @class */ (function () {
  89229. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  89230. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  89231. if (epsilon === void 0) { epsilon = 0.95; }
  89232. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  89233. this.edgesWidthScalerForOrthographic = 1000.0;
  89234. this.edgesWidthScalerForPerspective = 50.0;
  89235. this._linesPositions = new Array();
  89236. this._linesNormals = new Array();
  89237. this._linesIndices = new Array();
  89238. this._buffers = {};
  89239. this._checkVerticesInsteadOfIndices = false;
  89240. this._source = source;
  89241. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  89242. this._epsilon = epsilon;
  89243. this._prepareRessources();
  89244. this._generateEdgesLines();
  89245. }
  89246. EdgesRenderer.prototype._prepareRessources = function () {
  89247. if (this._lineShader) {
  89248. return;
  89249. }
  89250. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  89251. attributes: ["position", "normal"],
  89252. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  89253. });
  89254. this._lineShader.disableDepthWrite = true;
  89255. this._lineShader.backFaceCulling = false;
  89256. };
  89257. EdgesRenderer.prototype._rebuild = function () {
  89258. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  89259. if (buffer) {
  89260. buffer._rebuild();
  89261. }
  89262. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  89263. if (buffer) {
  89264. buffer._rebuild();
  89265. }
  89266. var scene = this._source.getScene();
  89267. var engine = scene.getEngine();
  89268. this._ib = engine.createIndexBuffer(this._linesIndices);
  89269. };
  89270. EdgesRenderer.prototype.dispose = function () {
  89271. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  89272. if (buffer) {
  89273. buffer.dispose();
  89274. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  89275. }
  89276. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  89277. if (buffer) {
  89278. buffer.dispose();
  89279. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  89280. }
  89281. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  89282. this._lineShader.dispose();
  89283. };
  89284. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  89285. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  89286. return 0;
  89287. }
  89288. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  89289. return 1;
  89290. }
  89291. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  89292. return 2;
  89293. }
  89294. return -1;
  89295. };
  89296. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  89297. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  89298. return 0;
  89299. }
  89300. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  89301. return 1;
  89302. }
  89303. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  89304. return 2;
  89305. }
  89306. return -1;
  89307. };
  89308. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  89309. var needToCreateLine;
  89310. if (edge === undefined) {
  89311. needToCreateLine = true;
  89312. }
  89313. else {
  89314. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  89315. needToCreateLine = dotProduct < this._epsilon;
  89316. }
  89317. if (needToCreateLine) {
  89318. var offset = this._linesPositions.length / 3;
  89319. var normal = p0.subtract(p1);
  89320. normal.normalize();
  89321. // Positions
  89322. this._linesPositions.push(p0.x);
  89323. this._linesPositions.push(p0.y);
  89324. this._linesPositions.push(p0.z);
  89325. this._linesPositions.push(p0.x);
  89326. this._linesPositions.push(p0.y);
  89327. this._linesPositions.push(p0.z);
  89328. this._linesPositions.push(p1.x);
  89329. this._linesPositions.push(p1.y);
  89330. this._linesPositions.push(p1.z);
  89331. this._linesPositions.push(p1.x);
  89332. this._linesPositions.push(p1.y);
  89333. this._linesPositions.push(p1.z);
  89334. // Normals
  89335. this._linesNormals.push(p1.x);
  89336. this._linesNormals.push(p1.y);
  89337. this._linesNormals.push(p1.z);
  89338. this._linesNormals.push(-1);
  89339. this._linesNormals.push(p1.x);
  89340. this._linesNormals.push(p1.y);
  89341. this._linesNormals.push(p1.z);
  89342. this._linesNormals.push(1);
  89343. this._linesNormals.push(p0.x);
  89344. this._linesNormals.push(p0.y);
  89345. this._linesNormals.push(p0.z);
  89346. this._linesNormals.push(-1);
  89347. this._linesNormals.push(p0.x);
  89348. this._linesNormals.push(p0.y);
  89349. this._linesNormals.push(p0.z);
  89350. this._linesNormals.push(1);
  89351. // Indices
  89352. this._linesIndices.push(offset);
  89353. this._linesIndices.push(offset + 1);
  89354. this._linesIndices.push(offset + 2);
  89355. this._linesIndices.push(offset);
  89356. this._linesIndices.push(offset + 2);
  89357. this._linesIndices.push(offset + 3);
  89358. }
  89359. };
  89360. EdgesRenderer.prototype._generateEdgesLines = function () {
  89361. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89362. var indices = this._source.getIndices();
  89363. if (!indices || !positions) {
  89364. return;
  89365. }
  89366. // First let's find adjacencies
  89367. var adjacencies = new Array();
  89368. var faceNormals = new Array();
  89369. var index;
  89370. var faceAdjacencies;
  89371. // Prepare faces
  89372. for (index = 0; index < indices.length; index += 3) {
  89373. faceAdjacencies = new FaceAdjacencies();
  89374. var p0Index = indices[index];
  89375. var p1Index = indices[index + 1];
  89376. var p2Index = indices[index + 2];
  89377. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  89378. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  89379. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  89380. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  89381. faceNormal.normalize();
  89382. faceNormals.push(faceNormal);
  89383. adjacencies.push(faceAdjacencies);
  89384. }
  89385. // Scan
  89386. for (index = 0; index < adjacencies.length; index++) {
  89387. faceAdjacencies = adjacencies[index];
  89388. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  89389. var otherFaceAdjacencies = adjacencies[otherIndex];
  89390. if (faceAdjacencies.edgesConnectedCount === 3) {
  89391. break;
  89392. }
  89393. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  89394. continue;
  89395. }
  89396. var otherP0 = indices[otherIndex * 3];
  89397. var otherP1 = indices[otherIndex * 3 + 1];
  89398. var otherP2 = indices[otherIndex * 3 + 2];
  89399. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  89400. var otherEdgeIndex = 0;
  89401. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  89402. continue;
  89403. }
  89404. switch (edgeIndex) {
  89405. case 0:
  89406. if (this._checkVerticesInsteadOfIndices) {
  89407. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89408. }
  89409. else {
  89410. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  89411. }
  89412. break;
  89413. case 1:
  89414. if (this._checkVerticesInsteadOfIndices) {
  89415. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89416. }
  89417. else {
  89418. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  89419. }
  89420. break;
  89421. case 2:
  89422. if (this._checkVerticesInsteadOfIndices) {
  89423. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89424. }
  89425. else {
  89426. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  89427. }
  89428. break;
  89429. }
  89430. if (otherEdgeIndex === -1) {
  89431. continue;
  89432. }
  89433. faceAdjacencies.edges[edgeIndex] = otherIndex;
  89434. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  89435. faceAdjacencies.edgesConnectedCount++;
  89436. otherFaceAdjacencies.edgesConnectedCount++;
  89437. if (faceAdjacencies.edgesConnectedCount === 3) {
  89438. break;
  89439. }
  89440. }
  89441. }
  89442. }
  89443. // Create lines
  89444. for (index = 0; index < adjacencies.length; index++) {
  89445. // 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
  89446. var current = adjacencies[index];
  89447. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  89448. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  89449. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  89450. }
  89451. // Merge into a single mesh
  89452. var engine = this._source.getScene().getEngine();
  89453. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  89454. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  89455. this._ib = engine.createIndexBuffer(this._linesIndices);
  89456. this._indicesCount = this._linesIndices.length;
  89457. };
  89458. EdgesRenderer.prototype.render = function () {
  89459. var scene = this._source.getScene();
  89460. if (!this._lineShader.isReady() || !scene.activeCamera) {
  89461. return;
  89462. }
  89463. var engine = scene.getEngine();
  89464. this._lineShader._preBind();
  89465. // VBOs
  89466. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  89467. scene.resetCachedMaterial();
  89468. this._lineShader.setColor4("color", this._source.edgesColor);
  89469. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  89470. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  89471. }
  89472. else {
  89473. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  89474. }
  89475. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  89476. this._lineShader.bind(this._source.getWorldMatrix());
  89477. // Draw order
  89478. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  89479. this._lineShader.unbind();
  89480. engine.setDepthWrite(true);
  89481. };
  89482. return EdgesRenderer;
  89483. }());
  89484. BABYLON.EdgesRenderer = EdgesRenderer;
  89485. })(BABYLON || (BABYLON = {}));
  89486. //# sourceMappingURL=babylon.edgesRenderer.js.map
  89487. "use strict";
  89488. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89489. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89490. s = arguments[i];
  89491. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89492. t[p] = s[p];
  89493. }
  89494. return t;
  89495. };
  89496. var BABYLON;
  89497. (function (BABYLON) {
  89498. /**
  89499. * The effect layer Helps adding post process effect blended with the main pass.
  89500. *
  89501. * This can be for instance use to generate glow or higlight effects on the scene.
  89502. *
  89503. * The effect layer class can not be used directly and is intented to inherited from to be
  89504. * customized per effects.
  89505. */
  89506. var EffectLayer = /** @class */ (function () {
  89507. /**
  89508. * Instantiates a new effect Layer and references it in the scene.
  89509. * @param name The name of the layer
  89510. * @param scene The scene to use the layer in
  89511. */
  89512. function EffectLayer(
  89513. /** The Friendly of the effect in the scene */
  89514. name, scene) {
  89515. this._vertexBuffers = {};
  89516. this._maxSize = 0;
  89517. this._mainTextureDesiredSize = { width: 0, height: 0 };
  89518. this._shouldRender = true;
  89519. this._postProcesses = [];
  89520. this._textures = [];
  89521. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  89522. /**
  89523. * The clear color of the texture used to generate the glow map.
  89524. */
  89525. this.neutralColor = new BABYLON.Color4();
  89526. /**
  89527. * Specifies wether the highlight layer is enabled or not.
  89528. */
  89529. this.isEnabled = true;
  89530. /**
  89531. * An event triggered when the effect layer has been disposed.
  89532. */
  89533. this.onDisposeObservable = new BABYLON.Observable();
  89534. /**
  89535. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  89536. */
  89537. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  89538. /**
  89539. * An event triggered when the generated texture is being merged in the scene.
  89540. */
  89541. this.onBeforeComposeObservable = new BABYLON.Observable();
  89542. /**
  89543. * An event triggered when the generated texture has been merged in the scene.
  89544. */
  89545. this.onAfterComposeObservable = new BABYLON.Observable();
  89546. /**
  89547. * An event triggered when the efffect layer changes its size.
  89548. */
  89549. this.onSizeChangedObservable = new BABYLON.Observable();
  89550. this.name = name;
  89551. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89552. this._engine = scene.getEngine();
  89553. this._maxSize = this._engine.getCaps().maxTextureSize;
  89554. this._scene.effectLayers.push(this);
  89555. // Generate Buffers
  89556. this._generateIndexBuffer();
  89557. this._genrateVertexBuffer();
  89558. }
  89559. Object.defineProperty(EffectLayer.prototype, "camera", {
  89560. /**
  89561. * Gets the camera attached to the layer.
  89562. */
  89563. get: function () {
  89564. return this._effectLayerOptions.camera;
  89565. },
  89566. enumerable: true,
  89567. configurable: true
  89568. });
  89569. /**
  89570. * Initializes the effect layer with the required options.
  89571. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  89572. */
  89573. EffectLayer.prototype._init = function (options) {
  89574. // Adapt options
  89575. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89576. this._setMainTextureSize();
  89577. this._createMainTexture();
  89578. this._createTextureAndPostProcesses();
  89579. this._mergeEffect = this._createMergeEffect();
  89580. };
  89581. /**
  89582. * Generates the index buffer of the full screen quad blending to the main canvas.
  89583. */
  89584. EffectLayer.prototype._generateIndexBuffer = function () {
  89585. // Indices
  89586. var indices = [];
  89587. indices.push(0);
  89588. indices.push(1);
  89589. indices.push(2);
  89590. indices.push(0);
  89591. indices.push(2);
  89592. indices.push(3);
  89593. this._indexBuffer = this._engine.createIndexBuffer(indices);
  89594. };
  89595. /**
  89596. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  89597. */
  89598. EffectLayer.prototype._genrateVertexBuffer = function () {
  89599. // VBO
  89600. var vertices = [];
  89601. vertices.push(1, 1);
  89602. vertices.push(-1, 1);
  89603. vertices.push(-1, -1);
  89604. vertices.push(1, -1);
  89605. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89606. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89607. };
  89608. /**
  89609. * Sets the main texture desired size which is the closest power of two
  89610. * of the engine canvas size.
  89611. */
  89612. EffectLayer.prototype._setMainTextureSize = function () {
  89613. if (this._effectLayerOptions.mainTextureFixedSize) {
  89614. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  89615. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  89616. }
  89617. else {
  89618. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  89619. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  89620. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  89621. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  89622. }
  89623. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  89624. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  89625. };
  89626. /**
  89627. * Creates the main texture for the effect layer.
  89628. */
  89629. EffectLayer.prototype._createMainTexture = function () {
  89630. var _this = this;
  89631. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  89632. width: this._mainTextureDesiredSize.width,
  89633. height: this._mainTextureDesiredSize.height
  89634. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89635. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  89636. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89637. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89638. this._mainTexture.anisotropicFilteringLevel = 1;
  89639. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89640. this._mainTexture.renderParticles = false;
  89641. this._mainTexture.renderList = null;
  89642. this._mainTexture.ignoreCameraViewport = true;
  89643. // Custom render function
  89644. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89645. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  89646. var index;
  89647. var engine = _this._scene.getEngine();
  89648. if (depthOnlySubMeshes.length) {
  89649. engine.setColorWrite(false);
  89650. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89651. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  89652. }
  89653. engine.setColorWrite(true);
  89654. }
  89655. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89656. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  89657. }
  89658. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89659. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  89660. }
  89661. for (index = 0; index < transparentSubMeshes.length; index++) {
  89662. _this._renderSubMesh(transparentSubMeshes.data[index]);
  89663. }
  89664. };
  89665. this._mainTexture.onClearObservable.add(function (engine) {
  89666. engine.clear(_this.neutralColor, true, true, true);
  89667. });
  89668. };
  89669. /**
  89670. * Checks for the readiness of the element composing the layer.
  89671. * @param subMesh the mesh to check for
  89672. * @param useInstances specify wether or not to use instances to render the mesh
  89673. * @param emissiveTexture the associated emissive texture used to generate the glow
  89674. * @return true if ready otherwise, false
  89675. */
  89676. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  89677. var material = subMesh.getMaterial();
  89678. if (!material) {
  89679. return false;
  89680. }
  89681. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  89682. return false;
  89683. }
  89684. var defines = [];
  89685. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89686. var mesh = subMesh.getMesh();
  89687. var uv1 = false;
  89688. var uv2 = false;
  89689. // Alpha test
  89690. if (material && material.needAlphaTesting()) {
  89691. var alphaTexture = material.getAlphaTestTexture();
  89692. if (alphaTexture) {
  89693. defines.push("#define ALPHATEST");
  89694. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89695. alphaTexture.coordinatesIndex === 1) {
  89696. defines.push("#define DIFFUSEUV2");
  89697. uv2 = true;
  89698. }
  89699. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89700. defines.push("#define DIFFUSEUV1");
  89701. uv1 = true;
  89702. }
  89703. }
  89704. }
  89705. // Emissive
  89706. if (emissiveTexture) {
  89707. defines.push("#define EMISSIVE");
  89708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89709. emissiveTexture.coordinatesIndex === 1) {
  89710. defines.push("#define EMISSIVEUV2");
  89711. uv2 = true;
  89712. }
  89713. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89714. defines.push("#define EMISSIVEUV1");
  89715. uv1 = true;
  89716. }
  89717. }
  89718. if (uv1) {
  89719. attribs.push(BABYLON.VertexBuffer.UVKind);
  89720. defines.push("#define UV1");
  89721. }
  89722. if (uv2) {
  89723. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89724. defines.push("#define UV2");
  89725. }
  89726. // Bones
  89727. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89728. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89729. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89730. if (mesh.numBoneInfluencers > 4) {
  89731. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  89732. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  89733. }
  89734. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89735. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  89736. }
  89737. else {
  89738. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89739. }
  89740. // Morph targets
  89741. var manager = mesh.morphTargetManager;
  89742. var morphInfluencers = 0;
  89743. if (manager) {
  89744. if (manager.numInfluencers > 0) {
  89745. defines.push("#define MORPHTARGETS");
  89746. morphInfluencers = manager.numInfluencers;
  89747. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  89748. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  89749. }
  89750. }
  89751. // Instances
  89752. if (useInstances) {
  89753. defines.push("#define INSTANCES");
  89754. attribs.push("world0");
  89755. attribs.push("world1");
  89756. attribs.push("world2");
  89757. attribs.push("world3");
  89758. }
  89759. // Get correct effect
  89760. var join = defines.join("\n");
  89761. if (this._cachedDefines !== join) {
  89762. this._cachedDefines = join;
  89763. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  89764. }
  89765. return this._effectLayerMapGenerationEffect.isReady();
  89766. };
  89767. /**
  89768. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  89769. */
  89770. EffectLayer.prototype.render = function () {
  89771. var currentEffect = this._mergeEffect;
  89772. // Check
  89773. if (!currentEffect.isReady())
  89774. return;
  89775. for (var i = 0; i < this._postProcesses.length; i++) {
  89776. if (!this._postProcesses[i].isReady()) {
  89777. return;
  89778. }
  89779. }
  89780. var engine = this._scene.getEngine();
  89781. this.onBeforeComposeObservable.notifyObservers(this);
  89782. // Render
  89783. engine.enableEffect(currentEffect);
  89784. engine.setState(false);
  89785. // VBOs
  89786. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89787. // Cache
  89788. var previousAlphaMode = engine.getAlphaMode();
  89789. // Go Blend.
  89790. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  89791. // Blends the map on the main canvas.
  89792. this._internalRender(currentEffect);
  89793. // Restore Alpha
  89794. engine.setAlphaMode(previousAlphaMode);
  89795. this.onAfterComposeObservable.notifyObservers(this);
  89796. // Handle size changes.
  89797. var size = this._mainTexture.getSize();
  89798. this._setMainTextureSize();
  89799. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  89800. // Recreate RTT and post processes on size change.
  89801. this.onSizeChangedObservable.notifyObservers(this);
  89802. this._disposeTextureAndPostProcesses();
  89803. this._createMainTexture();
  89804. this._createTextureAndPostProcesses();
  89805. }
  89806. };
  89807. /**
  89808. * Determine if a given mesh will be used in the current effect.
  89809. * @param mesh mesh to test
  89810. * @returns true if the mesh will be used
  89811. */
  89812. EffectLayer.prototype.hasMesh = function (mesh) {
  89813. return true;
  89814. };
  89815. /**
  89816. * Returns true if the layer contains information to display, otherwise false.
  89817. * @returns true if the glow layer should be rendered
  89818. */
  89819. EffectLayer.prototype.shouldRender = function () {
  89820. return this.isEnabled && this._shouldRender;
  89821. };
  89822. /**
  89823. * Returns true if the mesh should render, otherwise false.
  89824. * @param mesh The mesh to render
  89825. * @returns true if it should render otherwise false
  89826. */
  89827. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  89828. return true;
  89829. };
  89830. /**
  89831. * Returns true if the mesh should render, otherwise false.
  89832. * @param mesh The mesh to render
  89833. * @returns true if it should render otherwise false
  89834. */
  89835. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  89836. return true;
  89837. };
  89838. /**
  89839. * Renders the submesh passed in parameter to the generation map.
  89840. */
  89841. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  89842. var _this = this;
  89843. if (!this.shouldRender()) {
  89844. return;
  89845. }
  89846. var material = subMesh.getMaterial();
  89847. var mesh = subMesh.getRenderingMesh();
  89848. var scene = this._scene;
  89849. var engine = scene.getEngine();
  89850. if (!material) {
  89851. return;
  89852. }
  89853. // Do not block in blend mode.
  89854. if (material.needAlphaBlendingForMesh(mesh)) {
  89855. return;
  89856. }
  89857. // Culling
  89858. engine.setState(material.backFaceCulling);
  89859. // Managing instances
  89860. var batch = mesh._getInstancesRenderList(subMesh._id);
  89861. if (batch.mustReturn) {
  89862. return;
  89863. }
  89864. // Early Exit per mesh
  89865. if (!this._shouldRenderMesh(mesh)) {
  89866. return;
  89867. }
  89868. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89869. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  89870. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  89871. engine.enableEffect(this._effectLayerMapGenerationEffect);
  89872. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  89873. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  89874. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  89875. // Alpha test
  89876. if (material && material.needAlphaTesting()) {
  89877. var alphaTexture = material.getAlphaTestTexture();
  89878. if (alphaTexture) {
  89879. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  89880. var textureMatrix = alphaTexture.getTextureMatrix();
  89881. if (textureMatrix) {
  89882. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  89883. }
  89884. }
  89885. }
  89886. // Glow emissive only
  89887. if (this._emissiveTextureAndColor.texture) {
  89888. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  89889. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  89890. }
  89891. // Bones
  89892. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89893. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89894. }
  89895. // Morph targets
  89896. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  89897. // Draw
  89898. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  89899. }
  89900. else {
  89901. // Need to reset refresh rate of the shadowMap
  89902. this._mainTexture.resetRefreshCounter();
  89903. }
  89904. };
  89905. /**
  89906. * Rebuild the required buffers.
  89907. * @ignore Internal use only.
  89908. */
  89909. EffectLayer.prototype._rebuild = function () {
  89910. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89911. if (vb) {
  89912. vb._rebuild();
  89913. }
  89914. this._generateIndexBuffer();
  89915. };
  89916. /**
  89917. * Dispose only the render target textures and post process.
  89918. */
  89919. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  89920. this._mainTexture.dispose();
  89921. for (var i = 0; i < this._postProcesses.length; i++) {
  89922. if (this._postProcesses[i]) {
  89923. this._postProcesses[i].dispose();
  89924. }
  89925. }
  89926. this._postProcesses = [];
  89927. for (var i = 0; i < this._textures.length; i++) {
  89928. if (this._textures[i]) {
  89929. this._textures[i].dispose();
  89930. }
  89931. }
  89932. this._textures = [];
  89933. };
  89934. /**
  89935. * Dispose the highlight layer and free resources.
  89936. */
  89937. EffectLayer.prototype.dispose = function () {
  89938. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89939. if (vertexBuffer) {
  89940. vertexBuffer.dispose();
  89941. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89942. }
  89943. if (this._indexBuffer) {
  89944. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89945. this._indexBuffer = null;
  89946. }
  89947. // Clean textures and post processes
  89948. this._disposeTextureAndPostProcesses();
  89949. // Remove from scene
  89950. var index = this._scene.effectLayers.indexOf(this, 0);
  89951. if (index > -1) {
  89952. this._scene.effectLayers.splice(index, 1);
  89953. }
  89954. // Callback
  89955. this.onDisposeObservable.notifyObservers(this);
  89956. this.onDisposeObservable.clear();
  89957. this.onBeforeRenderMainTextureObservable.clear();
  89958. this.onBeforeComposeObservable.clear();
  89959. this.onAfterComposeObservable.clear();
  89960. this.onSizeChangedObservable.clear();
  89961. };
  89962. /**
  89963. * Gets the class name of the effect layer
  89964. * @returns the string with the class name of the effect layer
  89965. */
  89966. EffectLayer.prototype.getClassName = function () {
  89967. return "EffectLayer";
  89968. };
  89969. /**
  89970. * Creates an effect layer from parsed effect layer data
  89971. * @param parsedEffectLayer defines effect layer data
  89972. * @param scene defines the current scene
  89973. * @param rootUrl defines the root URL containing the effect layer information
  89974. * @returns a parsed effect Layer
  89975. */
  89976. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  89977. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  89978. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  89979. };
  89980. __decorate([
  89981. BABYLON.serialize()
  89982. ], EffectLayer.prototype, "name", void 0);
  89983. __decorate([
  89984. BABYLON.serializeAsColor4()
  89985. ], EffectLayer.prototype, "neutralColor", void 0);
  89986. __decorate([
  89987. BABYLON.serialize()
  89988. ], EffectLayer.prototype, "isEnabled", void 0);
  89989. __decorate([
  89990. BABYLON.serializeAsCameraReference()
  89991. ], EffectLayer.prototype, "camera", null);
  89992. return EffectLayer;
  89993. }());
  89994. BABYLON.EffectLayer = EffectLayer;
  89995. })(BABYLON || (BABYLON = {}));
  89996. //# sourceMappingURL=babylon.effectLayer.js.map
  89997. "use strict";
  89998. var BABYLON;
  89999. (function (BABYLON) {
  90000. /**
  90001. * Special Glow Blur post process only blurring the alpha channel
  90002. * It enforces keeping the most luminous color in the color channel.
  90003. */
  90004. var GlowBlurPostProcess = /** @class */ (function (_super) {
  90005. __extends(GlowBlurPostProcess, _super);
  90006. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  90007. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90008. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  90009. _this.direction = direction;
  90010. _this.kernel = kernel;
  90011. _this.onApplyObservable.add(function (effect) {
  90012. effect.setFloat2("screenSize", _this.width, _this.height);
  90013. effect.setVector2("direction", _this.direction);
  90014. effect.setFloat("blurWidth", _this.kernel);
  90015. });
  90016. return _this;
  90017. }
  90018. return GlowBlurPostProcess;
  90019. }(BABYLON.PostProcess));
  90020. /**
  90021. * The highlight layer Helps adding a glow effect around a mesh.
  90022. *
  90023. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90024. * glowy meshes to your scene.
  90025. *
  90026. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  90027. */
  90028. var HighlightLayer = /** @class */ (function (_super) {
  90029. __extends(HighlightLayer, _super);
  90030. /**
  90031. * Instantiates a new highlight Layer and references it to the scene..
  90032. * @param name The name of the layer
  90033. * @param scene The scene to use the layer in
  90034. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  90035. */
  90036. function HighlightLayer(name, scene, options) {
  90037. var _this = _super.call(this, name, scene) || this;
  90038. _this.name = name;
  90039. /**
  90040. * Specifies whether or not the inner glow is ACTIVE in the layer.
  90041. */
  90042. _this.innerGlow = true;
  90043. /**
  90044. * Specifies whether or not the outer glow is ACTIVE in the layer.
  90045. */
  90046. _this.outerGlow = true;
  90047. /**
  90048. * An event triggered when the highlight layer is being blurred.
  90049. */
  90050. _this.onBeforeBlurObservable = new BABYLON.Observable();
  90051. /**
  90052. * An event triggered when the highlight layer has been blurred.
  90053. */
  90054. _this.onAfterBlurObservable = new BABYLON.Observable();
  90055. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  90056. _this._meshes = {};
  90057. _this._excludedMeshes = {};
  90058. _this.neutralColor = HighlightLayer.NeutralColor;
  90059. // Warn on stencil
  90060. if (!_this._engine.isStencilEnable) {
  90061. 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 }");
  90062. }
  90063. // Adapt options
  90064. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90065. // Initialize the layer
  90066. _this._init({
  90067. alphaBlendingMode: _this._options.alphaBlendingMode,
  90068. camera: _this._options.camera,
  90069. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90070. mainTextureRatio: _this._options.mainTextureRatio
  90071. });
  90072. // Do not render as long as no meshes have been added
  90073. _this._shouldRender = false;
  90074. return _this;
  90075. }
  90076. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  90077. /**
  90078. * Gets the horizontal size of the blur.
  90079. */
  90080. get: function () {
  90081. return this._horizontalBlurPostprocess.kernel;
  90082. },
  90083. /**
  90084. * Specifies the horizontal size of the blur.
  90085. */
  90086. set: function (value) {
  90087. this._horizontalBlurPostprocess.kernel = value;
  90088. },
  90089. enumerable: true,
  90090. configurable: true
  90091. });
  90092. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  90093. /**
  90094. * Gets the vertical size of the blur.
  90095. */
  90096. get: function () {
  90097. return this._verticalBlurPostprocess.kernel;
  90098. },
  90099. /**
  90100. * Specifies the vertical size of the blur.
  90101. */
  90102. set: function (value) {
  90103. this._verticalBlurPostprocess.kernel = value;
  90104. },
  90105. enumerable: true,
  90106. configurable: true
  90107. });
  90108. /**
  90109. * Get the effect name of the layer.
  90110. * @return The effect name
  90111. */
  90112. HighlightLayer.prototype.getEffectName = function () {
  90113. return HighlightLayer.EffectName;
  90114. };
  90115. /**
  90116. * Create the merge effect. This is the shader use to blit the information back
  90117. * to the main canvas at the end of the scene rendering.
  90118. */
  90119. HighlightLayer.prototype._createMergeEffect = function () {
  90120. // Effect
  90121. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  90122. };
  90123. /**
  90124. * Creates the render target textures and post processes used in the highlight layer.
  90125. */
  90126. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  90127. var _this = this;
  90128. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  90129. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  90130. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90131. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90132. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  90133. width: blurTextureWidth,
  90134. height: blurTextureHeight
  90135. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90136. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90137. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90138. this._blurTexture.anisotropicFilteringLevel = 16;
  90139. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90140. this._blurTexture.renderParticles = false;
  90141. this._blurTexture.ignoreCameraViewport = true;
  90142. this._textures = [this._blurTexture];
  90143. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  90144. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90145. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  90146. effect.setTexture("textureSampler", _this._mainTexture);
  90147. });
  90148. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90149. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  90150. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  90151. });
  90152. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90153. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  90154. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  90155. });
  90156. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  90157. }
  90158. else {
  90159. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  90160. width: blurTextureWidth,
  90161. height: blurTextureHeight
  90162. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90163. this._horizontalBlurPostprocess.width = blurTextureWidth;
  90164. this._horizontalBlurPostprocess.height = blurTextureHeight;
  90165. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  90166. effect.setTexture("textureSampler", _this._mainTexture);
  90167. });
  90168. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  90169. width: blurTextureWidth,
  90170. height: blurTextureHeight
  90171. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90172. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  90173. }
  90174. this._mainTexture.onAfterUnbindObservable.add(function () {
  90175. _this.onBeforeBlurObservable.notifyObservers(_this);
  90176. var internalTexture = _this._blurTexture.getInternalTexture();
  90177. if (internalTexture) {
  90178. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  90179. }
  90180. _this.onAfterBlurObservable.notifyObservers(_this);
  90181. });
  90182. // Prevent autoClear.
  90183. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  90184. };
  90185. /**
  90186. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  90187. */
  90188. HighlightLayer.prototype.needStencil = function () {
  90189. return true;
  90190. };
  90191. /**
  90192. * Checks for the readiness of the element composing the layer.
  90193. * @param subMesh the mesh to check for
  90194. * @param useInstances specify wether or not to use instances to render the mesh
  90195. * @param emissiveTexture the associated emissive texture used to generate the glow
  90196. * @return true if ready otherwise, false
  90197. */
  90198. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  90199. var material = subMesh.getMaterial();
  90200. var mesh = subMesh.getRenderingMesh();
  90201. if (!material || !mesh || !this._meshes) {
  90202. return false;
  90203. }
  90204. var emissiveTexture = null;
  90205. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  90206. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  90207. emissiveTexture = material.emissiveTexture;
  90208. }
  90209. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  90210. };
  90211. /**
  90212. * Implementation specific of rendering the generating effect on the main canvas.
  90213. * @param effect The effect used to render through
  90214. */
  90215. HighlightLayer.prototype._internalRender = function (effect) {
  90216. // Texture
  90217. effect.setTexture("textureSampler", this._blurTexture);
  90218. // Cache
  90219. var engine = this._engine;
  90220. var previousStencilBuffer = engine.getStencilBuffer();
  90221. var previousStencilFunction = engine.getStencilFunction();
  90222. var previousStencilMask = engine.getStencilMask();
  90223. var previousStencilOperationPass = engine.getStencilOperationPass();
  90224. var previousStencilOperationFail = engine.getStencilOperationFail();
  90225. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  90226. var previousStencilReference = engine.getStencilFunctionReference();
  90227. // Stencil operations
  90228. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  90229. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  90230. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  90231. // Draw order
  90232. engine.setStencilMask(0x00);
  90233. engine.setStencilBuffer(true);
  90234. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  90235. // 2 passes inner outer
  90236. if (this.outerGlow) {
  90237. effect.setFloat("offset", 0);
  90238. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  90239. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90240. }
  90241. if (this.innerGlow) {
  90242. effect.setFloat("offset", 1);
  90243. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  90244. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90245. }
  90246. // Restore Cache
  90247. engine.setStencilFunction(previousStencilFunction);
  90248. engine.setStencilMask(previousStencilMask);
  90249. engine.setStencilBuffer(previousStencilBuffer);
  90250. engine.setStencilOperationPass(previousStencilOperationPass);
  90251. engine.setStencilOperationFail(previousStencilOperationFail);
  90252. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  90253. engine.setStencilFunctionReference(previousStencilReference);
  90254. };
  90255. /**
  90256. * Returns true if the layer contains information to display, otherwise false.
  90257. */
  90258. HighlightLayer.prototype.shouldRender = function () {
  90259. if (_super.prototype.shouldRender.call(this)) {
  90260. return this._meshes ? true : false;
  90261. }
  90262. return false;
  90263. };
  90264. /**
  90265. * Returns true if the mesh should render, otherwise false.
  90266. * @param mesh The mesh to render
  90267. * @returns true if it should render otherwise false
  90268. */
  90269. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  90270. // Excluded Mesh
  90271. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  90272. return false;
  90273. }
  90274. ;
  90275. return true;
  90276. };
  90277. /**
  90278. * Sets the required values for both the emissive texture and and the main color.
  90279. */
  90280. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  90281. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  90282. if (highlightLayerMesh) {
  90283. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  90284. }
  90285. else {
  90286. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  90287. }
  90288. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  90289. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  90290. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  90291. }
  90292. else {
  90293. this._emissiveTextureAndColor.texture = null;
  90294. }
  90295. };
  90296. /**
  90297. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  90298. * @param mesh The mesh to exclude from the highlight layer
  90299. */
  90300. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  90301. if (!this._excludedMeshes) {
  90302. return;
  90303. }
  90304. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  90305. if (!meshExcluded) {
  90306. this._excludedMeshes[mesh.uniqueId] = {
  90307. mesh: mesh,
  90308. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  90309. mesh.getEngine().setStencilBuffer(false);
  90310. }),
  90311. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  90312. mesh.getEngine().setStencilBuffer(true);
  90313. }),
  90314. };
  90315. }
  90316. };
  90317. /**
  90318. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  90319. * @param mesh The mesh to highlight
  90320. */
  90321. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  90322. if (!this._excludedMeshes) {
  90323. return;
  90324. }
  90325. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  90326. if (meshExcluded) {
  90327. if (meshExcluded.beforeRender) {
  90328. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  90329. }
  90330. if (meshExcluded.afterRender) {
  90331. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  90332. }
  90333. }
  90334. this._excludedMeshes[mesh.uniqueId] = null;
  90335. };
  90336. /**
  90337. * Determine if a given mesh will be highlighted by the current HighlightLayer
  90338. * @param mesh mesh to test
  90339. * @returns true if the mesh will be highlighted by the current HighlightLayer
  90340. */
  90341. HighlightLayer.prototype.hasMesh = function (mesh) {
  90342. if (!this._meshes) {
  90343. return false;
  90344. }
  90345. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  90346. };
  90347. /**
  90348. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  90349. * @param mesh The mesh to highlight
  90350. * @param color The color of the highlight
  90351. * @param glowEmissiveOnly Extract the glow from the emissive texture
  90352. */
  90353. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  90354. var _this = this;
  90355. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  90356. if (!this._meshes) {
  90357. return;
  90358. }
  90359. var meshHighlight = this._meshes[mesh.uniqueId];
  90360. if (meshHighlight) {
  90361. meshHighlight.color = color;
  90362. }
  90363. else {
  90364. this._meshes[mesh.uniqueId] = {
  90365. mesh: mesh,
  90366. color: color,
  90367. // Lambda required for capture due to Observable this context
  90368. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  90369. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  90370. _this._defaultStencilReference(mesh);
  90371. }
  90372. else {
  90373. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  90374. }
  90375. }),
  90376. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  90377. glowEmissiveOnly: glowEmissiveOnly
  90378. };
  90379. }
  90380. this._shouldRender = true;
  90381. };
  90382. /**
  90383. * Remove a mesh from the highlight layer in order to make it stop glowing.
  90384. * @param mesh The mesh to highlight
  90385. */
  90386. HighlightLayer.prototype.removeMesh = function (mesh) {
  90387. if (!this._meshes) {
  90388. return;
  90389. }
  90390. var meshHighlight = this._meshes[mesh.uniqueId];
  90391. if (meshHighlight) {
  90392. if (meshHighlight.observerHighlight) {
  90393. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90394. }
  90395. if (meshHighlight.observerDefault) {
  90396. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90397. }
  90398. delete this._meshes[mesh.uniqueId];
  90399. }
  90400. this._shouldRender = false;
  90401. for (var meshHighlightToCheck in this._meshes) {
  90402. if (this._meshes[meshHighlightToCheck]) {
  90403. this._shouldRender = true;
  90404. break;
  90405. }
  90406. }
  90407. };
  90408. /**
  90409. * Force the stencil to the normal expected value for none glowing parts
  90410. */
  90411. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  90412. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  90413. };
  90414. /**
  90415. * Free any resources and references associated to a mesh.
  90416. * Internal use
  90417. * @param mesh The mesh to free.
  90418. */
  90419. HighlightLayer.prototype._disposeMesh = function (mesh) {
  90420. this.removeMesh(mesh);
  90421. this.removeExcludedMesh(mesh);
  90422. };
  90423. /**
  90424. * Dispose the highlight layer and free resources.
  90425. */
  90426. HighlightLayer.prototype.dispose = function () {
  90427. if (this._meshes) {
  90428. // Clean mesh references
  90429. for (var id in this._meshes) {
  90430. var meshHighlight = this._meshes[id];
  90431. if (meshHighlight && meshHighlight.mesh) {
  90432. if (meshHighlight.observerHighlight) {
  90433. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90434. }
  90435. if (meshHighlight.observerDefault) {
  90436. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90437. }
  90438. }
  90439. }
  90440. this._meshes = null;
  90441. }
  90442. if (this._excludedMeshes) {
  90443. for (var id in this._excludedMeshes) {
  90444. var meshHighlight = this._excludedMeshes[id];
  90445. if (meshHighlight) {
  90446. if (meshHighlight.beforeRender) {
  90447. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  90448. }
  90449. if (meshHighlight.afterRender) {
  90450. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  90451. }
  90452. }
  90453. }
  90454. this._excludedMeshes = null;
  90455. }
  90456. _super.prototype.dispose.call(this);
  90457. };
  90458. /**
  90459. * Gets the class name of the effect layer
  90460. * @returns the string with the class name of the effect layer
  90461. */
  90462. HighlightLayer.prototype.getClassName = function () {
  90463. return "HighlightLayer";
  90464. };
  90465. /**
  90466. * Serializes this Highlight layer
  90467. * @returns a serialized Highlight layer object
  90468. */
  90469. HighlightLayer.prototype.serialize = function () {
  90470. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90471. serializationObject.customType = "BABYLON.HighlightLayer";
  90472. // Highlighted meshes
  90473. serializationObject.meshes = [];
  90474. if (this._meshes) {
  90475. for (var m in this._meshes) {
  90476. var mesh = this._meshes[m];
  90477. if (mesh) {
  90478. serializationObject.meshes.push({
  90479. glowEmissiveOnly: mesh.glowEmissiveOnly,
  90480. color: mesh.color.asArray(),
  90481. meshId: mesh.mesh.id
  90482. });
  90483. }
  90484. }
  90485. }
  90486. // Excluded meshes
  90487. serializationObject.excludedMeshes = [];
  90488. if (this._excludedMeshes) {
  90489. for (var e in this._excludedMeshes) {
  90490. var excludedMesh = this._excludedMeshes[e];
  90491. if (excludedMesh) {
  90492. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  90493. }
  90494. }
  90495. }
  90496. return serializationObject;
  90497. };
  90498. /**
  90499. * Creates a Highlight layer from parsed Highlight layer data
  90500. * @param parsedHightlightLayer defines the Highlight layer data
  90501. * @param scene defines the current scene
  90502. * @param rootUrl defines the root URL containing the Highlight layer information
  90503. * @returns a parsed Highlight layer
  90504. */
  90505. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  90506. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  90507. var index;
  90508. // Excluded meshes
  90509. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  90510. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  90511. if (mesh) {
  90512. hl.addExcludedMesh(mesh);
  90513. }
  90514. }
  90515. // Included meshes
  90516. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  90517. var highlightedMesh = parsedHightlightLayer.meshes[index];
  90518. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  90519. if (mesh) {
  90520. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  90521. }
  90522. }
  90523. return hl;
  90524. };
  90525. /**
  90526. * Effect Name of the highlight layer.
  90527. */
  90528. HighlightLayer.EffectName = "HighlightLayer";
  90529. /**
  90530. * The neutral color used during the preparation of the glow effect.
  90531. * This is black by default as the blend operation is a blend operation.
  90532. */
  90533. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  90534. /**
  90535. * Stencil value used for glowing meshes.
  90536. */
  90537. HighlightLayer.GlowingMeshStencilReference = 0x02;
  90538. /**
  90539. * Stencil value used for the other meshes in the scene.
  90540. */
  90541. HighlightLayer.NormalMeshStencilReference = 0x01;
  90542. __decorate([
  90543. BABYLON.serialize()
  90544. ], HighlightLayer.prototype, "innerGlow", void 0);
  90545. __decorate([
  90546. BABYLON.serialize()
  90547. ], HighlightLayer.prototype, "outerGlow", void 0);
  90548. __decorate([
  90549. BABYLON.serialize()
  90550. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  90551. __decorate([
  90552. BABYLON.serialize()
  90553. ], HighlightLayer.prototype, "blurVerticalSize", null);
  90554. __decorate([
  90555. BABYLON.serialize("options")
  90556. ], HighlightLayer.prototype, "_options", void 0);
  90557. return HighlightLayer;
  90558. }(BABYLON.EffectLayer));
  90559. BABYLON.HighlightLayer = HighlightLayer;
  90560. })(BABYLON || (BABYLON = {}));
  90561. //# sourceMappingURL=babylon.highlightLayer.js.map
  90562. "use strict";
  90563. var BABYLON;
  90564. (function (BABYLON) {
  90565. /**
  90566. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  90567. *
  90568. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90569. * glowy meshes to your scene.
  90570. *
  90571. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  90572. */
  90573. var GlowLayer = /** @class */ (function (_super) {
  90574. __extends(GlowLayer, _super);
  90575. /**
  90576. * Instantiates a new glow Layer and references it to the scene.
  90577. * @param name The name of the layer
  90578. * @param scene The scene to use the layer in
  90579. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  90580. */
  90581. function GlowLayer(name, scene, options) {
  90582. var _this = _super.call(this, name, scene) || this;
  90583. _this._intensity = 1.0;
  90584. _this._includedOnlyMeshes = [];
  90585. _this._excludedMeshes = [];
  90586. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  90587. // Adapt options
  90588. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  90589. // Initialize the layer
  90590. _this._init({
  90591. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  90592. camera: _this._options.camera,
  90593. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90594. mainTextureRatio: _this._options.mainTextureRatio
  90595. });
  90596. return _this;
  90597. }
  90598. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  90599. /**
  90600. * Gets the kernel size of the blur.
  90601. */
  90602. get: function () {
  90603. return this._horizontalBlurPostprocess1.kernel;
  90604. },
  90605. /**
  90606. * Sets the kernel size of the blur.
  90607. */
  90608. set: function (value) {
  90609. this._horizontalBlurPostprocess1.kernel = value;
  90610. this._verticalBlurPostprocess1.kernel = value;
  90611. this._horizontalBlurPostprocess2.kernel = value;
  90612. this._verticalBlurPostprocess2.kernel = value;
  90613. },
  90614. enumerable: true,
  90615. configurable: true
  90616. });
  90617. Object.defineProperty(GlowLayer.prototype, "intensity", {
  90618. /**
  90619. * Gets the glow intensity.
  90620. */
  90621. get: function () {
  90622. return this._intensity;
  90623. },
  90624. /**
  90625. * Sets the glow intensity.
  90626. */
  90627. set: function (value) {
  90628. this._intensity = value;
  90629. },
  90630. enumerable: true,
  90631. configurable: true
  90632. });
  90633. /**
  90634. * Get the effect name of the layer.
  90635. * @return The effect name
  90636. */
  90637. GlowLayer.prototype.getEffectName = function () {
  90638. return GlowLayer.EffectName;
  90639. };
  90640. /**
  90641. * Create the merge effect. This is the shader use to blit the information back
  90642. * to the main canvas at the end of the scene rendering.
  90643. */
  90644. GlowLayer.prototype._createMergeEffect = function () {
  90645. // Effect
  90646. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  90647. };
  90648. /**
  90649. * Creates the render target textures and post processes used in the glow layer.
  90650. */
  90651. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  90652. var _this = this;
  90653. var blurTextureWidth = this._mainTextureDesiredSize.width;
  90654. var blurTextureHeight = this._mainTextureDesiredSize.height;
  90655. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90656. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90657. var textureType = 0;
  90658. if (this._engine.getCaps().textureHalfFloatRender) {
  90659. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90660. }
  90661. else {
  90662. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90663. }
  90664. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  90665. width: blurTextureWidth,
  90666. height: blurTextureHeight
  90667. }, this._scene, false, true, textureType);
  90668. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90669. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90670. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90671. this._blurTexture1.renderParticles = false;
  90672. this._blurTexture1.ignoreCameraViewport = true;
  90673. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  90674. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  90675. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  90676. width: blurTextureWidth2,
  90677. height: blurTextureHeight2
  90678. }, this._scene, false, true, textureType);
  90679. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90680. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90681. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90682. this._blurTexture2.renderParticles = false;
  90683. this._blurTexture2.ignoreCameraViewport = true;
  90684. this._textures = [this._blurTexture1, this._blurTexture2];
  90685. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90686. width: blurTextureWidth,
  90687. height: blurTextureHeight
  90688. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90689. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  90690. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  90691. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  90692. effect.setTexture("textureSampler", _this._mainTexture);
  90693. });
  90694. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90695. width: blurTextureWidth,
  90696. height: blurTextureHeight
  90697. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90698. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90699. width: blurTextureWidth2,
  90700. height: blurTextureHeight2
  90701. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90702. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  90703. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  90704. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  90705. effect.setTexture("textureSampler", _this._blurTexture1);
  90706. });
  90707. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90708. width: blurTextureWidth2,
  90709. height: blurTextureHeight2
  90710. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90711. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90712. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  90713. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90714. this._mainTexture.samples = this._options.mainTextureSamples;
  90715. this._mainTexture.onAfterUnbindObservable.add(function () {
  90716. var internalTexture = _this._blurTexture1.getInternalTexture();
  90717. if (internalTexture) {
  90718. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  90719. internalTexture = _this._blurTexture2.getInternalTexture();
  90720. if (internalTexture) {
  90721. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  90722. }
  90723. }
  90724. });
  90725. // Prevent autoClear.
  90726. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  90727. };
  90728. /**
  90729. * Checks for the readiness of the element composing the layer.
  90730. * @param subMesh the mesh to check for
  90731. * @param useInstances specify wether or not to use instances to render the mesh
  90732. * @param emissiveTexture the associated emissive texture used to generate the glow
  90733. * @return true if ready otherwise, false
  90734. */
  90735. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  90736. var material = subMesh.getMaterial();
  90737. var mesh = subMesh.getRenderingMesh();
  90738. if (!material || !mesh) {
  90739. return false;
  90740. }
  90741. var emissiveTexture = material.emissiveTexture;
  90742. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  90743. };
  90744. /**
  90745. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  90746. */
  90747. GlowLayer.prototype.needStencil = function () {
  90748. return false;
  90749. };
  90750. /**
  90751. * Implementation specific of rendering the generating effect on the main canvas.
  90752. * @param effect The effect used to render through
  90753. */
  90754. GlowLayer.prototype._internalRender = function (effect) {
  90755. // Texture
  90756. effect.setTexture("textureSampler", this._blurTexture1);
  90757. effect.setTexture("textureSampler2", this._blurTexture2);
  90758. effect.setFloat("offset", this._intensity);
  90759. // Cache
  90760. var engine = this._engine;
  90761. var previousStencilBuffer = engine.getStencilBuffer();
  90762. // Draw order
  90763. engine.setStencilBuffer(false);
  90764. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90765. // Draw order
  90766. engine.setStencilBuffer(previousStencilBuffer);
  90767. };
  90768. /**
  90769. * Sets the required values for both the emissive texture and and the main color.
  90770. */
  90771. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  90772. var textureLevel = 1.0;
  90773. if (this.customEmissiveTextureSelector) {
  90774. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  90775. }
  90776. else {
  90777. if (material) {
  90778. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  90779. if (this._emissiveTextureAndColor.texture) {
  90780. textureLevel = this._emissiveTextureAndColor.texture.level;
  90781. }
  90782. }
  90783. else {
  90784. this._emissiveTextureAndColor.texture = null;
  90785. }
  90786. }
  90787. if (this.customEmissiveColorSelector) {
  90788. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  90789. }
  90790. else {
  90791. if (material.emissiveColor) {
  90792. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  90793. }
  90794. else {
  90795. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  90796. }
  90797. }
  90798. };
  90799. /**
  90800. * Returns true if the mesh should render, otherwise false.
  90801. * @param mesh The mesh to render
  90802. * @returns true if it should render otherwise false
  90803. */
  90804. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  90805. return this.hasMesh(mesh);
  90806. };
  90807. /**
  90808. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  90809. * @param mesh The mesh to exclude from the glow layer
  90810. */
  90811. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  90812. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  90813. this._excludedMeshes.push(mesh.uniqueId);
  90814. }
  90815. };
  90816. /**
  90817. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  90818. * @param mesh The mesh to remove
  90819. */
  90820. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  90821. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  90822. if (index !== -1) {
  90823. this._excludedMeshes.splice(index, 1);
  90824. }
  90825. };
  90826. /**
  90827. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  90828. * @param mesh The mesh to include in the glow layer
  90829. */
  90830. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  90831. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  90832. this._includedOnlyMeshes.push(mesh.uniqueId);
  90833. }
  90834. };
  90835. /**
  90836. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  90837. * @param mesh The mesh to remove
  90838. */
  90839. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  90840. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  90841. if (index !== -1) {
  90842. this._includedOnlyMeshes.splice(index, 1);
  90843. }
  90844. };
  90845. /**
  90846. * Determine if a given mesh will be used in the glow layer
  90847. * @param mesh The mesh to test
  90848. * @returns true if the mesh will be highlighted by the current glow layer
  90849. */
  90850. GlowLayer.prototype.hasMesh = function (mesh) {
  90851. // Included Mesh
  90852. if (this._includedOnlyMeshes.length) {
  90853. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  90854. }
  90855. ;
  90856. // Excluded Mesh
  90857. if (this._excludedMeshes.length) {
  90858. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  90859. }
  90860. ;
  90861. return true;
  90862. };
  90863. /**
  90864. * Free any resources and references associated to a mesh.
  90865. * Internal use
  90866. * @param mesh The mesh to free.
  90867. */
  90868. GlowLayer.prototype._disposeMesh = function (mesh) {
  90869. this.removeIncludedOnlyMesh(mesh);
  90870. this.removeExcludedMesh(mesh);
  90871. };
  90872. /**
  90873. * Gets the class name of the effect layer
  90874. * @returns the string with the class name of the effect layer
  90875. */
  90876. GlowLayer.prototype.getClassName = function () {
  90877. return "GlowLayer";
  90878. };
  90879. /**
  90880. * Serializes this glow layer
  90881. * @returns a serialized glow layer object
  90882. */
  90883. GlowLayer.prototype.serialize = function () {
  90884. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90885. serializationObject.customType = "BABYLON.GlowLayer";
  90886. var index;
  90887. // Included meshes
  90888. serializationObject.includedMeshes = [];
  90889. if (this._includedOnlyMeshes.length) {
  90890. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  90891. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  90892. if (mesh) {
  90893. serializationObject.includedMeshes.push(mesh.id);
  90894. }
  90895. }
  90896. }
  90897. // Excluded meshes
  90898. serializationObject.excludedMeshes = [];
  90899. if (this._excludedMeshes.length) {
  90900. for (index = 0; index < this._excludedMeshes.length; index++) {
  90901. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  90902. if (mesh) {
  90903. serializationObject.excludedMeshes.push(mesh.id);
  90904. }
  90905. }
  90906. }
  90907. return serializationObject;
  90908. };
  90909. /**
  90910. * Creates a Glow Layer from parsed glow layer data
  90911. * @param parsedGlowLayer defines glow layer data
  90912. * @param scene defines the current scene
  90913. * @param rootUrl defines the root URL containing the glow layer information
  90914. * @returns a parsed Glow Layer
  90915. */
  90916. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  90917. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  90918. var index;
  90919. // Excluded meshes
  90920. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  90921. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  90922. if (mesh) {
  90923. gl.addExcludedMesh(mesh);
  90924. }
  90925. }
  90926. // Included meshes
  90927. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  90928. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  90929. if (mesh) {
  90930. gl.addIncludedOnlyMesh(mesh);
  90931. }
  90932. }
  90933. return gl;
  90934. };
  90935. /**
  90936. * Effect Name of the layer.
  90937. */
  90938. GlowLayer.EffectName = "GlowLayer";
  90939. /**
  90940. * The default blur kernel size used for the glow.
  90941. */
  90942. GlowLayer.DefaultBlurKernelSize = 32;
  90943. /**
  90944. * The default texture size ratio used for the glow.
  90945. */
  90946. GlowLayer.DefaultTextureRatio = 0.5;
  90947. __decorate([
  90948. BABYLON.serialize()
  90949. ], GlowLayer.prototype, "blurKernelSize", null);
  90950. __decorate([
  90951. BABYLON.serialize()
  90952. ], GlowLayer.prototype, "intensity", null);
  90953. __decorate([
  90954. BABYLON.serialize("options")
  90955. ], GlowLayer.prototype, "_options", void 0);
  90956. return GlowLayer;
  90957. }(BABYLON.EffectLayer));
  90958. BABYLON.GlowLayer = GlowLayer;
  90959. })(BABYLON || (BABYLON = {}));
  90960. //# sourceMappingURL=babylon.glowLayer.js.map
  90961. "use strict";
  90962. var BABYLON;
  90963. (function (BABYLON) {
  90964. /**
  90965. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  90966. */
  90967. var AssetTaskState;
  90968. (function (AssetTaskState) {
  90969. /**
  90970. * Initialization
  90971. */
  90972. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  90973. /**
  90974. * Running
  90975. */
  90976. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  90977. /**
  90978. * Done
  90979. */
  90980. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  90981. /**
  90982. * Error
  90983. */
  90984. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  90985. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  90986. /**
  90987. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  90988. */
  90989. var AbstractAssetTask = /** @class */ (function () {
  90990. /**
  90991. * Creates a new {BABYLON.AssetsManager}
  90992. * @param name defines the name of the task
  90993. */
  90994. function AbstractAssetTask(
  90995. /**
  90996. * Task name
  90997. */ name) {
  90998. this.name = name;
  90999. this._isCompleted = false;
  91000. this._taskState = AssetTaskState.INIT;
  91001. }
  91002. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  91003. /**
  91004. * Get if the task is completed
  91005. */
  91006. get: function () {
  91007. return this._isCompleted;
  91008. },
  91009. enumerable: true,
  91010. configurable: true
  91011. });
  91012. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  91013. /**
  91014. * Gets the current state of the task
  91015. */
  91016. get: function () {
  91017. return this._taskState;
  91018. },
  91019. enumerable: true,
  91020. configurable: true
  91021. });
  91022. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  91023. /**
  91024. * Gets the current error object (if task is in error)
  91025. */
  91026. get: function () {
  91027. return this._errorObject;
  91028. },
  91029. enumerable: true,
  91030. configurable: true
  91031. });
  91032. /**
  91033. * Internal only
  91034. * @ignore
  91035. */
  91036. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  91037. if (this._errorObject) {
  91038. return;
  91039. }
  91040. this._errorObject = {
  91041. message: message,
  91042. exception: exception
  91043. };
  91044. };
  91045. /**
  91046. * Execute the current task
  91047. * @param scene defines the scene where you want your assets to be loaded
  91048. * @param onSuccess is a callback called when the task is successfully executed
  91049. * @param onError is a callback called if an error occurs
  91050. */
  91051. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91052. var _this = this;
  91053. this._taskState = AssetTaskState.RUNNING;
  91054. this.runTask(scene, function () {
  91055. _this.onDoneCallback(onSuccess, onError);
  91056. }, function (msg, exception) {
  91057. _this.onErrorCallback(onError, msg, exception);
  91058. });
  91059. };
  91060. /**
  91061. * Execute the current task
  91062. * @param scene defines the scene where you want your assets to be loaded
  91063. * @param onSuccess is a callback called when the task is successfully executed
  91064. * @param onError is a callback called if an error occurs
  91065. */
  91066. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91067. throw new Error("runTask is not implemented");
  91068. };
  91069. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  91070. this._taskState = AssetTaskState.ERROR;
  91071. this._errorObject = {
  91072. message: message,
  91073. exception: exception
  91074. };
  91075. if (this.onError) {
  91076. this.onError(this, message, exception);
  91077. }
  91078. onError();
  91079. };
  91080. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  91081. try {
  91082. this._taskState = AssetTaskState.DONE;
  91083. this._isCompleted = true;
  91084. if (this.onSuccess) {
  91085. this.onSuccess(this);
  91086. }
  91087. onSuccess();
  91088. }
  91089. catch (e) {
  91090. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  91091. }
  91092. };
  91093. return AbstractAssetTask;
  91094. }());
  91095. BABYLON.AbstractAssetTask = AbstractAssetTask;
  91096. /**
  91097. * Class used to share progress information about assets loading
  91098. */
  91099. var AssetsProgressEvent = /** @class */ (function () {
  91100. /**
  91101. * Creates a {BABYLON.AssetsProgressEvent}
  91102. * @param remainingCount defines the number of remaining tasks to process
  91103. * @param totalCount defines the total number of tasks
  91104. * @param task defines the task that was just processed
  91105. */
  91106. function AssetsProgressEvent(remainingCount, totalCount, task) {
  91107. this.remainingCount = remainingCount;
  91108. this.totalCount = totalCount;
  91109. this.task = task;
  91110. }
  91111. return AssetsProgressEvent;
  91112. }());
  91113. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  91114. /**
  91115. * Define a task used by {BABYLON.AssetsManager} to load meshes
  91116. */
  91117. var MeshAssetTask = /** @class */ (function (_super) {
  91118. __extends(MeshAssetTask, _super);
  91119. /**
  91120. * Creates a new {BABYLON.MeshAssetTask}
  91121. * @param name defines the name of the task
  91122. * @param meshesNames defines the list of mesh's names you want to load
  91123. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  91124. * @param sceneFilename defines the filename of the scene to load from
  91125. */
  91126. function MeshAssetTask(
  91127. /**
  91128. * Defines the name of the task
  91129. */
  91130. name,
  91131. /**
  91132. * Defines the list of mesh's names you want to load
  91133. */
  91134. meshesNames,
  91135. /**
  91136. * Defines the root url to use as a base to load your meshes and associated resources
  91137. */
  91138. rootUrl,
  91139. /**
  91140. * Defines the filename of the scene to load from
  91141. */
  91142. sceneFilename) {
  91143. var _this = _super.call(this, name) || this;
  91144. _this.name = name;
  91145. _this.meshesNames = meshesNames;
  91146. _this.rootUrl = rootUrl;
  91147. _this.sceneFilename = sceneFilename;
  91148. return _this;
  91149. }
  91150. /**
  91151. * Execute the current task
  91152. * @param scene defines the scene where you want your assets to be loaded
  91153. * @param onSuccess is a callback called when the task is successfully executed
  91154. * @param onError is a callback called if an error occurs
  91155. */
  91156. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91157. var _this = this;
  91158. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  91159. _this.loadedMeshes = meshes;
  91160. _this.loadedParticleSystems = particleSystems;
  91161. _this.loadedSkeletons = skeletons;
  91162. onSuccess();
  91163. }, null, function (scene, message, exception) {
  91164. onError(message, exception);
  91165. });
  91166. };
  91167. return MeshAssetTask;
  91168. }(AbstractAssetTask));
  91169. BABYLON.MeshAssetTask = MeshAssetTask;
  91170. /**
  91171. * Define a task used by {BABYLON.AssetsManager} to load text content
  91172. */
  91173. var TextFileAssetTask = /** @class */ (function (_super) {
  91174. __extends(TextFileAssetTask, _super);
  91175. /**
  91176. * Creates a new TextFileAssetTask object
  91177. * @param name defines the name of the task
  91178. * @param url defines the location of the file to load
  91179. */
  91180. function TextFileAssetTask(
  91181. /**
  91182. * Defines the name of the task
  91183. */
  91184. name,
  91185. /**
  91186. * Defines the location of the file to load
  91187. */
  91188. url) {
  91189. var _this = _super.call(this, name) || this;
  91190. _this.name = name;
  91191. _this.url = url;
  91192. return _this;
  91193. }
  91194. /**
  91195. * Execute the current task
  91196. * @param scene defines the scene where you want your assets to be loaded
  91197. * @param onSuccess is a callback called when the task is successfully executed
  91198. * @param onError is a callback called if an error occurs
  91199. */
  91200. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91201. var _this = this;
  91202. scene._loadFile(this.url, function (data) {
  91203. _this.text = data;
  91204. onSuccess();
  91205. }, undefined, false, false, function (request, exception) {
  91206. if (request) {
  91207. onError(request.status + " " + request.statusText, exception);
  91208. }
  91209. });
  91210. };
  91211. return TextFileAssetTask;
  91212. }(AbstractAssetTask));
  91213. BABYLON.TextFileAssetTask = TextFileAssetTask;
  91214. /**
  91215. * Define a task used by {BABYLON.AssetsManager} to load binary data
  91216. */
  91217. var BinaryFileAssetTask = /** @class */ (function (_super) {
  91218. __extends(BinaryFileAssetTask, _super);
  91219. /**
  91220. * Creates a new BinaryFileAssetTask object
  91221. * @param name defines the name of the new task
  91222. * @param url defines the location of the file to load
  91223. */
  91224. function BinaryFileAssetTask(
  91225. /**
  91226. * Defines the name of the task
  91227. */
  91228. name,
  91229. /**
  91230. * Defines the location of the file to load
  91231. */
  91232. url) {
  91233. var _this = _super.call(this, name) || this;
  91234. _this.name = name;
  91235. _this.url = url;
  91236. return _this;
  91237. }
  91238. /**
  91239. * Execute the current task
  91240. * @param scene defines the scene where you want your assets to be loaded
  91241. * @param onSuccess is a callback called when the task is successfully executed
  91242. * @param onError is a callback called if an error occurs
  91243. */
  91244. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91245. var _this = this;
  91246. scene._loadFile(this.url, function (data) {
  91247. _this.data = data;
  91248. onSuccess();
  91249. }, undefined, true, true, function (request, exception) {
  91250. if (request) {
  91251. onError(request.status + " " + request.statusText, exception);
  91252. }
  91253. });
  91254. };
  91255. return BinaryFileAssetTask;
  91256. }(AbstractAssetTask));
  91257. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  91258. /**
  91259. * Define a task used by {BABYLON.AssetsManager} to load images
  91260. */
  91261. var ImageAssetTask = /** @class */ (function (_super) {
  91262. __extends(ImageAssetTask, _super);
  91263. /**
  91264. * Creates a new ImageAssetTask
  91265. * @param name defines the name of the task
  91266. * @param url defines the location of the image to load
  91267. */
  91268. function ImageAssetTask(
  91269. /**
  91270. * Defines the name of the task
  91271. */
  91272. name,
  91273. /**
  91274. * Defines the location of the image to load
  91275. */
  91276. url) {
  91277. var _this = _super.call(this, name) || this;
  91278. _this.name = name;
  91279. _this.url = url;
  91280. return _this;
  91281. }
  91282. /**
  91283. * Execute the current task
  91284. * @param scene defines the scene where you want your assets to be loaded
  91285. * @param onSuccess is a callback called when the task is successfully executed
  91286. * @param onError is a callback called if an error occurs
  91287. */
  91288. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91289. var _this = this;
  91290. var img = new Image();
  91291. BABYLON.Tools.SetCorsBehavior(this.url, img);
  91292. img.onload = function () {
  91293. _this.image = img;
  91294. onSuccess();
  91295. };
  91296. img.onerror = function (err) {
  91297. onError("Error loading image", err);
  91298. };
  91299. img.src = this.url;
  91300. };
  91301. return ImageAssetTask;
  91302. }(AbstractAssetTask));
  91303. BABYLON.ImageAssetTask = ImageAssetTask;
  91304. /**
  91305. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  91306. */
  91307. var TextureAssetTask = /** @class */ (function (_super) {
  91308. __extends(TextureAssetTask, _super);
  91309. /**
  91310. * Creates a new TextureAssetTask object
  91311. * @param name defines the name of the task
  91312. * @param url defines the location of the file to load
  91313. * @param noMipmap defines if mipmap should not be generated (default is false)
  91314. * @param invertY defines if texture must be inverted on Y axis (default is false)
  91315. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  91316. */
  91317. function TextureAssetTask(
  91318. /**
  91319. * Defines the name of the task
  91320. */
  91321. name,
  91322. /**
  91323. * Defines the location of the file to load
  91324. */
  91325. url,
  91326. /**
  91327. * Defines if mipmap should not be generated (default is false)
  91328. */
  91329. noMipmap,
  91330. /**
  91331. * Defines if texture must be inverted on Y axis (default is false)
  91332. */
  91333. invertY,
  91334. /**
  91335. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  91336. */
  91337. samplingMode) {
  91338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91339. var _this = _super.call(this, name) || this;
  91340. _this.name = name;
  91341. _this.url = url;
  91342. _this.noMipmap = noMipmap;
  91343. _this.invertY = invertY;
  91344. _this.samplingMode = samplingMode;
  91345. return _this;
  91346. }
  91347. /**
  91348. * Execute the current task
  91349. * @param scene defines the scene where you want your assets to be loaded
  91350. * @param onSuccess is a callback called when the task is successfully executed
  91351. * @param onError is a callback called if an error occurs
  91352. */
  91353. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91354. var onload = function () {
  91355. onSuccess();
  91356. };
  91357. var onerror = function (message, exception) {
  91358. onError(message, exception);
  91359. };
  91360. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  91361. };
  91362. return TextureAssetTask;
  91363. }(AbstractAssetTask));
  91364. BABYLON.TextureAssetTask = TextureAssetTask;
  91365. /**
  91366. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  91367. */
  91368. var CubeTextureAssetTask = /** @class */ (function (_super) {
  91369. __extends(CubeTextureAssetTask, _super);
  91370. /**
  91371. * Creates a new CubeTextureAssetTask
  91372. * @param name defines the name of the task
  91373. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  91374. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  91375. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91376. * @param files defines the explicit list of files (undefined by default)
  91377. */
  91378. function CubeTextureAssetTask(
  91379. /**
  91380. * Defines the name of the task
  91381. */
  91382. name,
  91383. /**
  91384. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  91385. */
  91386. url,
  91387. /**
  91388. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  91389. */
  91390. extensions,
  91391. /**
  91392. * Defines if mipmaps should not be generated (default is false)
  91393. */
  91394. noMipmap,
  91395. /**
  91396. * Defines the explicit list of files (undefined by default)
  91397. */
  91398. files) {
  91399. var _this = _super.call(this, name) || this;
  91400. _this.name = name;
  91401. _this.url = url;
  91402. _this.extensions = extensions;
  91403. _this.noMipmap = noMipmap;
  91404. _this.files = files;
  91405. return _this;
  91406. }
  91407. /**
  91408. * Execute the current task
  91409. * @param scene defines the scene where you want your assets to be loaded
  91410. * @param onSuccess is a callback called when the task is successfully executed
  91411. * @param onError is a callback called if an error occurs
  91412. */
  91413. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91414. var onload = function () {
  91415. onSuccess();
  91416. };
  91417. var onerror = function (message, exception) {
  91418. onError(message, exception);
  91419. };
  91420. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  91421. };
  91422. return CubeTextureAssetTask;
  91423. }(AbstractAssetTask));
  91424. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  91425. /**
  91426. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  91427. */
  91428. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  91429. __extends(HDRCubeTextureAssetTask, _super);
  91430. /**
  91431. * Creates a new HDRCubeTextureAssetTask object
  91432. * @param name defines the name of the task
  91433. * @param url defines the location of the file to load
  91434. * @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.
  91435. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91436. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91437. * @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)
  91438. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91439. */
  91440. function HDRCubeTextureAssetTask(
  91441. /**
  91442. * Defines the name of the task
  91443. */
  91444. name,
  91445. /**
  91446. * Defines the location of the file to load
  91447. */
  91448. url,
  91449. /**
  91450. * 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.
  91451. */
  91452. size,
  91453. /**
  91454. * Defines if mipmaps should not be generated (default is false)
  91455. */
  91456. noMipmap,
  91457. /**
  91458. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91459. */
  91460. generateHarmonics,
  91461. /**
  91462. * 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)
  91463. */
  91464. useInGammaSpace,
  91465. /**
  91466. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91467. */
  91468. usePMREMGenerator) {
  91469. if (noMipmap === void 0) { noMipmap = false; }
  91470. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91471. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91472. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91473. var _this = _super.call(this, name) || this;
  91474. _this.name = name;
  91475. _this.url = url;
  91476. _this.size = size;
  91477. _this.noMipmap = noMipmap;
  91478. _this.generateHarmonics = generateHarmonics;
  91479. _this.useInGammaSpace = useInGammaSpace;
  91480. _this.usePMREMGenerator = usePMREMGenerator;
  91481. return _this;
  91482. }
  91483. /**
  91484. * Execute the current task
  91485. * @param scene defines the scene where you want your assets to be loaded
  91486. * @param onSuccess is a callback called when the task is successfully executed
  91487. * @param onError is a callback called if an error occurs
  91488. */
  91489. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91490. var onload = function () {
  91491. onSuccess();
  91492. };
  91493. var onerror = function (message, exception) {
  91494. onError(message, exception);
  91495. };
  91496. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  91497. };
  91498. return HDRCubeTextureAssetTask;
  91499. }(AbstractAssetTask));
  91500. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  91501. /**
  91502. * This class can be used to easily import assets into a scene
  91503. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  91504. */
  91505. var AssetsManager = /** @class */ (function () {
  91506. /**
  91507. * Creates a new AssetsManager
  91508. * @param scene defines the scene to work on
  91509. */
  91510. function AssetsManager(scene) {
  91511. this._isLoading = false;
  91512. this._tasks = new Array();
  91513. this._waitingTasksCount = 0;
  91514. this._totalTasksCount = 0;
  91515. /**
  91516. * Observable called when all tasks are processed
  91517. */
  91518. this.onTaskSuccessObservable = new BABYLON.Observable();
  91519. /**
  91520. * Observable called when a task had an error
  91521. */
  91522. this.onTaskErrorObservable = new BABYLON.Observable();
  91523. /**
  91524. * Observable called when a task is successful
  91525. */
  91526. this.onTasksDoneObservable = new BABYLON.Observable();
  91527. /**
  91528. * Observable called when a task is done (whatever the result is)
  91529. */
  91530. this.onProgressObservable = new BABYLON.Observable();
  91531. /**
  91532. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  91533. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  91534. */
  91535. this.useDefaultLoadingScreen = true;
  91536. this._scene = scene;
  91537. }
  91538. /**
  91539. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  91540. * @param taskName defines the name of the new task
  91541. * @param meshesNames defines the name of meshes to load
  91542. * @param rootUrl defines the root url to use to locate files
  91543. * @param sceneFilename defines the filename of the scene file
  91544. * @returns a new {BABYLON.MeshAssetTask} object
  91545. */
  91546. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  91547. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  91548. this._tasks.push(task);
  91549. return task;
  91550. };
  91551. /**
  91552. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  91553. * @param taskName defines the name of the new task
  91554. * @param url defines the url of the file to load
  91555. * @returns a new {BABYLON.TextFileAssetTask} object
  91556. */
  91557. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  91558. var task = new TextFileAssetTask(taskName, url);
  91559. this._tasks.push(task);
  91560. return task;
  91561. };
  91562. /**
  91563. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  91564. * @param taskName defines the name of the new task
  91565. * @param url defines the url of the file to load
  91566. * @returns a new {BABYLON.BinaryFileAssetTask} object
  91567. */
  91568. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  91569. var task = new BinaryFileAssetTask(taskName, url);
  91570. this._tasks.push(task);
  91571. return task;
  91572. };
  91573. /**
  91574. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  91575. * @param taskName defines the name of the new task
  91576. * @param url defines the url of the file to load
  91577. * @returns a new {BABYLON.ImageAssetTask} object
  91578. */
  91579. AssetsManager.prototype.addImageTask = function (taskName, url) {
  91580. var task = new ImageAssetTask(taskName, url);
  91581. this._tasks.push(task);
  91582. return task;
  91583. };
  91584. /**
  91585. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  91586. * @param taskName defines the name of the new task
  91587. * @param url defines the url of the file to load
  91588. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91589. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  91590. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  91591. * @returns a new {BABYLON.TextureAssetTask} object
  91592. */
  91593. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  91594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91595. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  91596. this._tasks.push(task);
  91597. return task;
  91598. };
  91599. /**
  91600. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  91601. * @param taskName defines the name of the new task
  91602. * @param url defines the url of the file to load
  91603. * @param extensions defines the extension to use to load the cube map (can be null)
  91604. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91605. * @param files defines the list of files to load (can be null)
  91606. * @returns a new {BABYLON.CubeTextureAssetTask} object
  91607. */
  91608. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  91609. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  91610. this._tasks.push(task);
  91611. return task;
  91612. };
  91613. /**
  91614. *
  91615. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  91616. * @param taskName defines the name of the new task
  91617. * @param url defines the url of the file to load
  91618. * @param size defines the size you want for the cubemap (can be null)
  91619. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91620. * @param generateHarmonics defines if you want to automatically generate (true by default)
  91621. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  91622. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  91623. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  91624. */
  91625. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  91626. if (noMipmap === void 0) { noMipmap = false; }
  91627. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91628. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91629. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91630. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  91631. this._tasks.push(task);
  91632. return task;
  91633. };
  91634. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  91635. var _this = this;
  91636. this._waitingTasksCount--;
  91637. try {
  91638. if (task.taskState === AssetTaskState.DONE) {
  91639. // Let's remove successfull tasks
  91640. BABYLON.Tools.SetImmediate(function () {
  91641. var index = _this._tasks.indexOf(task);
  91642. if (index > -1) {
  91643. _this._tasks.splice(index, 1);
  91644. }
  91645. });
  91646. }
  91647. if (this.onProgress) {
  91648. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  91649. }
  91650. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  91651. }
  91652. catch (e) {
  91653. BABYLON.Tools.Error("Error running progress callbacks.");
  91654. console.log(e);
  91655. }
  91656. if (this._waitingTasksCount === 0) {
  91657. try {
  91658. if (this.onFinish) {
  91659. this.onFinish(this._tasks);
  91660. }
  91661. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91662. }
  91663. catch (e) {
  91664. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  91665. console.log(e);
  91666. }
  91667. this._isLoading = false;
  91668. this._scene.getEngine().hideLoadingUI();
  91669. }
  91670. };
  91671. AssetsManager.prototype._runTask = function (task) {
  91672. var _this = this;
  91673. var done = function () {
  91674. try {
  91675. if (_this.onTaskSuccess) {
  91676. _this.onTaskSuccess(task);
  91677. }
  91678. _this.onTaskSuccessObservable.notifyObservers(task);
  91679. _this._decreaseWaitingTasksCount(task);
  91680. }
  91681. catch (e) {
  91682. error("Error executing task success callbacks", e);
  91683. }
  91684. };
  91685. var error = function (message, exception) {
  91686. task._setErrorObject(message, exception);
  91687. if (_this.onTaskError) {
  91688. _this.onTaskError(task);
  91689. }
  91690. _this.onTaskErrorObservable.notifyObservers(task);
  91691. _this._decreaseWaitingTasksCount(task);
  91692. };
  91693. task.run(this._scene, done, error);
  91694. };
  91695. /**
  91696. * Reset the {BABYLON.AssetsManager} and remove all tasks
  91697. * @return the current instance of the {BABYLON.AssetsManager}
  91698. */
  91699. AssetsManager.prototype.reset = function () {
  91700. this._isLoading = false;
  91701. this._tasks = new Array();
  91702. return this;
  91703. };
  91704. /**
  91705. * Start the loading process
  91706. * @return the current instance of the {BABYLON.AssetsManager}
  91707. */
  91708. AssetsManager.prototype.load = function () {
  91709. if (this._isLoading) {
  91710. return this;
  91711. }
  91712. this._isLoading = true;
  91713. this._waitingTasksCount = this._tasks.length;
  91714. this._totalTasksCount = this._tasks.length;
  91715. if (this._waitingTasksCount === 0) {
  91716. this._isLoading = false;
  91717. if (this.onFinish) {
  91718. this.onFinish(this._tasks);
  91719. }
  91720. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91721. return this;
  91722. }
  91723. if (this.useDefaultLoadingScreen) {
  91724. this._scene.getEngine().displayLoadingUI();
  91725. }
  91726. for (var index = 0; index < this._tasks.length; index++) {
  91727. var task = this._tasks[index];
  91728. this._runTask(task);
  91729. }
  91730. return this;
  91731. };
  91732. return AssetsManager;
  91733. }());
  91734. BABYLON.AssetsManager = AssetsManager;
  91735. })(BABYLON || (BABYLON = {}));
  91736. //# sourceMappingURL=babylon.assetsManager.js.map
  91737. "use strict";
  91738. var BABYLON;
  91739. (function (BABYLON) {
  91740. var serializedGeometries = [];
  91741. var serializeGeometry = function (geometry, serializationGeometries) {
  91742. if (serializedGeometries[geometry.id]) {
  91743. return;
  91744. }
  91745. if (geometry.doNotSerialize) {
  91746. return;
  91747. }
  91748. if (geometry instanceof BABYLON.BoxGeometry) {
  91749. serializationGeometries.boxes.push(geometry.serialize());
  91750. }
  91751. else if (geometry instanceof BABYLON.SphereGeometry) {
  91752. serializationGeometries.spheres.push(geometry.serialize());
  91753. }
  91754. else if (geometry instanceof BABYLON.CylinderGeometry) {
  91755. serializationGeometries.cylinders.push(geometry.serialize());
  91756. }
  91757. else if (geometry instanceof BABYLON.TorusGeometry) {
  91758. serializationGeometries.toruses.push(geometry.serialize());
  91759. }
  91760. else if (geometry instanceof BABYLON.GroundGeometry) {
  91761. serializationGeometries.grounds.push(geometry.serialize());
  91762. }
  91763. else if (geometry instanceof BABYLON.Plane) {
  91764. serializationGeometries.planes.push(geometry.serialize());
  91765. }
  91766. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  91767. serializationGeometries.torusKnots.push(geometry.serialize());
  91768. }
  91769. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  91770. throw new Error("Unknown primitive type");
  91771. }
  91772. else {
  91773. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  91774. }
  91775. serializedGeometries[geometry.id] = true;
  91776. };
  91777. var serializeMesh = function (mesh, serializationScene) {
  91778. var serializationObject = {};
  91779. // Geometry
  91780. var geometry = mesh._geometry;
  91781. if (geometry) {
  91782. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  91783. // 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
  91784. serializeGeometry(geometry, serializationScene.geometries);
  91785. }
  91786. }
  91787. // Custom
  91788. if (mesh.serialize) {
  91789. mesh.serialize(serializationObject);
  91790. }
  91791. return serializationObject;
  91792. };
  91793. var finalizeSingleMesh = function (mesh, serializationObject) {
  91794. //only works if the mesh is already loaded
  91795. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  91796. //serialize material
  91797. if (mesh.material) {
  91798. if (mesh.material instanceof BABYLON.StandardMaterial) {
  91799. serializationObject.materials = serializationObject.materials || [];
  91800. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91801. serializationObject.materials.push(mesh.material.serialize());
  91802. }
  91803. }
  91804. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  91805. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  91806. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91807. serializationObject.multiMaterials.push(mesh.material.serialize());
  91808. }
  91809. }
  91810. }
  91811. //serialize geometry
  91812. var geometry = mesh._geometry;
  91813. if (geometry) {
  91814. if (!serializationObject.geometries) {
  91815. serializationObject.geometries = {};
  91816. serializationObject.geometries.boxes = [];
  91817. serializationObject.geometries.spheres = [];
  91818. serializationObject.geometries.cylinders = [];
  91819. serializationObject.geometries.toruses = [];
  91820. serializationObject.geometries.grounds = [];
  91821. serializationObject.geometries.planes = [];
  91822. serializationObject.geometries.torusKnots = [];
  91823. serializationObject.geometries.vertexData = [];
  91824. }
  91825. serializeGeometry(geometry, serializationObject.geometries);
  91826. }
  91827. // Skeletons
  91828. if (mesh.skeleton) {
  91829. serializationObject.skeletons = serializationObject.skeletons || [];
  91830. serializationObject.skeletons.push(mesh.skeleton.serialize());
  91831. }
  91832. //serialize the actual mesh
  91833. serializationObject.meshes = serializationObject.meshes || [];
  91834. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  91835. }
  91836. };
  91837. var SceneSerializer = /** @class */ (function () {
  91838. function SceneSerializer() {
  91839. }
  91840. SceneSerializer.ClearCache = function () {
  91841. serializedGeometries = [];
  91842. };
  91843. SceneSerializer.Serialize = function (scene) {
  91844. var serializationObject = {};
  91845. SceneSerializer.ClearCache();
  91846. // Scene
  91847. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  91848. serializationObject.autoClear = scene.autoClear;
  91849. serializationObject.clearColor = scene.clearColor.asArray();
  91850. serializationObject.ambientColor = scene.ambientColor.asArray();
  91851. serializationObject.gravity = scene.gravity.asArray();
  91852. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  91853. serializationObject.workerCollisions = scene.workerCollisions;
  91854. // Fog
  91855. if (scene.fogMode && scene.fogMode !== 0) {
  91856. serializationObject.fogMode = scene.fogMode;
  91857. serializationObject.fogColor = scene.fogColor.asArray();
  91858. serializationObject.fogStart = scene.fogStart;
  91859. serializationObject.fogEnd = scene.fogEnd;
  91860. serializationObject.fogDensity = scene.fogDensity;
  91861. }
  91862. //Physics
  91863. if (scene.isPhysicsEnabled()) {
  91864. var physicEngine = scene.getPhysicsEngine();
  91865. if (physicEngine) {
  91866. serializationObject.physicsEnabled = true;
  91867. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  91868. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  91869. }
  91870. }
  91871. // Metadata
  91872. if (scene.metadata) {
  91873. serializationObject.metadata = scene.metadata;
  91874. }
  91875. // Morph targets
  91876. serializationObject.morphTargetManagers = [];
  91877. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  91878. var abstractMesh = _a[_i];
  91879. var manager = abstractMesh.morphTargetManager;
  91880. if (manager) {
  91881. serializationObject.morphTargetManagers.push(manager.serialize());
  91882. }
  91883. }
  91884. // Lights
  91885. serializationObject.lights = [];
  91886. var index;
  91887. var light;
  91888. for (index = 0; index < scene.lights.length; index++) {
  91889. light = scene.lights[index];
  91890. if (!light.doNotSerialize) {
  91891. serializationObject.lights.push(light.serialize());
  91892. }
  91893. }
  91894. // Cameras
  91895. serializationObject.cameras = [];
  91896. for (index = 0; index < scene.cameras.length; index++) {
  91897. var camera = scene.cameras[index];
  91898. if (!camera.doNotSerialize) {
  91899. serializationObject.cameras.push(camera.serialize());
  91900. }
  91901. }
  91902. if (scene.activeCamera) {
  91903. serializationObject.activeCameraID = scene.activeCamera.id;
  91904. }
  91905. // Animations
  91906. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  91907. // Materials
  91908. serializationObject.materials = [];
  91909. serializationObject.multiMaterials = [];
  91910. var material;
  91911. for (index = 0; index < scene.materials.length; index++) {
  91912. material = scene.materials[index];
  91913. if (!material.doNotSerialize) {
  91914. serializationObject.materials.push(material.serialize());
  91915. }
  91916. }
  91917. // MultiMaterials
  91918. serializationObject.multiMaterials = [];
  91919. for (index = 0; index < scene.multiMaterials.length; index++) {
  91920. var multiMaterial = scene.multiMaterials[index];
  91921. serializationObject.multiMaterials.push(multiMaterial.serialize());
  91922. }
  91923. // Environment texture
  91924. if (scene.environmentTexture) {
  91925. serializationObject.environmentTexture = scene.environmentTexture.name;
  91926. }
  91927. // Skeletons
  91928. serializationObject.skeletons = [];
  91929. for (index = 0; index < scene.skeletons.length; index++) {
  91930. var skeleton = scene.skeletons[index];
  91931. if (!skeleton.doNotSerialize) {
  91932. serializationObject.skeletons.push(skeleton.serialize());
  91933. }
  91934. }
  91935. // Transform nodes
  91936. serializationObject.transformNodes = [];
  91937. for (index = 0; index < scene.transformNodes.length; index++) {
  91938. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  91939. }
  91940. // Geometries
  91941. serializationObject.geometries = {};
  91942. serializationObject.geometries.boxes = [];
  91943. serializationObject.geometries.spheres = [];
  91944. serializationObject.geometries.cylinders = [];
  91945. serializationObject.geometries.toruses = [];
  91946. serializationObject.geometries.grounds = [];
  91947. serializationObject.geometries.planes = [];
  91948. serializationObject.geometries.torusKnots = [];
  91949. serializationObject.geometries.vertexData = [];
  91950. serializedGeometries = [];
  91951. var geometries = scene.getGeometries();
  91952. for (index = 0; index < geometries.length; index++) {
  91953. var geometry = geometries[index];
  91954. if (geometry.isReady()) {
  91955. serializeGeometry(geometry, serializationObject.geometries);
  91956. }
  91957. }
  91958. // Meshes
  91959. serializationObject.meshes = [];
  91960. for (index = 0; index < scene.meshes.length; index++) {
  91961. var abstractMesh = scene.meshes[index];
  91962. if (abstractMesh instanceof BABYLON.Mesh) {
  91963. var mesh = abstractMesh;
  91964. if (!mesh.doNotSerialize) {
  91965. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  91966. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  91967. }
  91968. }
  91969. }
  91970. }
  91971. // Particles Systems
  91972. serializationObject.particleSystems = [];
  91973. for (index = 0; index < scene.particleSystems.length; index++) {
  91974. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  91975. }
  91976. // Lens flares
  91977. serializationObject.lensFlareSystems = [];
  91978. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  91979. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  91980. }
  91981. // Shadows
  91982. serializationObject.shadowGenerators = [];
  91983. for (index = 0; index < scene.lights.length; index++) {
  91984. light = scene.lights[index];
  91985. var shadowGenerator = light.getShadowGenerator();
  91986. if (shadowGenerator) {
  91987. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  91988. }
  91989. }
  91990. // Action Manager
  91991. if (scene.actionManager) {
  91992. serializationObject.actions = scene.actionManager.serialize("scene");
  91993. }
  91994. // Audio
  91995. serializationObject.sounds = [];
  91996. for (index = 0; index < scene.soundTracks.length; index++) {
  91997. var soundtrack = scene.soundTracks[index];
  91998. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  91999. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  92000. }
  92001. }
  92002. // Effect layers
  92003. serializationObject.effectLayers = [];
  92004. for (index = 0; index < scene.effectLayers.length; index++) {
  92005. var layer = scene.effectLayers[index];
  92006. if (layer.serialize) {
  92007. serializationObject.effectLayers.push(layer.serialize());
  92008. }
  92009. }
  92010. return serializationObject;
  92011. };
  92012. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  92013. if (withParents === void 0) { withParents = false; }
  92014. if (withChildren === void 0) { withChildren = false; }
  92015. var serializationObject = {};
  92016. SceneSerializer.ClearCache();
  92017. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  92018. if (withParents || withChildren) {
  92019. //deliberate for loop! not for each, appended should be processed as well.
  92020. for (var i = 0; i < toSerialize.length; ++i) {
  92021. if (withChildren) {
  92022. toSerialize[i].getDescendants().forEach(function (node) {
  92023. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  92024. toSerialize.push(node);
  92025. }
  92026. });
  92027. }
  92028. //make sure the array doesn't contain the object already
  92029. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  92030. toSerialize.push(toSerialize[i].parent);
  92031. }
  92032. }
  92033. }
  92034. toSerialize.forEach(function (mesh) {
  92035. finalizeSingleMesh(mesh, serializationObject);
  92036. });
  92037. return serializationObject;
  92038. };
  92039. return SceneSerializer;
  92040. }());
  92041. BABYLON.SceneSerializer = SceneSerializer;
  92042. })(BABYLON || (BABYLON = {}));
  92043. //# sourceMappingURL=babylon.sceneSerializer.js.map
  92044. "use strict";
  92045. var BABYLON;
  92046. (function (BABYLON) {
  92047. var ReflectionProbe = /** @class */ (function () {
  92048. function ReflectionProbe(name, size, scene, generateMipMaps) {
  92049. if (generateMipMaps === void 0) { generateMipMaps = true; }
  92050. var _this = this;
  92051. this.name = name;
  92052. this._viewMatrix = BABYLON.Matrix.Identity();
  92053. this._target = BABYLON.Vector3.Zero();
  92054. this._add = BABYLON.Vector3.Zero();
  92055. this._invertYAxis = false;
  92056. this.position = BABYLON.Vector3.Zero();
  92057. this._scene = scene;
  92058. this._scene.reflectionProbes.push(this);
  92059. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  92060. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  92061. switch (faceIndex) {
  92062. case 0:
  92063. _this._add.copyFromFloats(1, 0, 0);
  92064. break;
  92065. case 1:
  92066. _this._add.copyFromFloats(-1, 0, 0);
  92067. break;
  92068. case 2:
  92069. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  92070. break;
  92071. case 3:
  92072. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  92073. break;
  92074. case 4:
  92075. _this._add.copyFromFloats(0, 0, 1);
  92076. break;
  92077. case 5:
  92078. _this._add.copyFromFloats(0, 0, -1);
  92079. break;
  92080. }
  92081. if (_this._attachedMesh) {
  92082. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  92083. }
  92084. _this.position.addToRef(_this._add, _this._target);
  92085. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  92086. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  92087. scene._forcedViewPosition = _this.position;
  92088. });
  92089. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  92090. scene._forcedViewPosition = null;
  92091. scene.updateTransformMatrix(true);
  92092. });
  92093. if (scene.activeCamera) {
  92094. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  92095. }
  92096. }
  92097. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  92098. get: function () {
  92099. return this._renderTargetTexture.samples;
  92100. },
  92101. set: function (value) {
  92102. this._renderTargetTexture.samples = value;
  92103. },
  92104. enumerable: true,
  92105. configurable: true
  92106. });
  92107. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  92108. get: function () {
  92109. return this._renderTargetTexture.refreshRate;
  92110. },
  92111. set: function (value) {
  92112. this._renderTargetTexture.refreshRate = value;
  92113. },
  92114. enumerable: true,
  92115. configurable: true
  92116. });
  92117. ReflectionProbe.prototype.getScene = function () {
  92118. return this._scene;
  92119. };
  92120. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  92121. get: function () {
  92122. return this._renderTargetTexture;
  92123. },
  92124. enumerable: true,
  92125. configurable: true
  92126. });
  92127. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  92128. get: function () {
  92129. return this._renderTargetTexture.renderList;
  92130. },
  92131. enumerable: true,
  92132. configurable: true
  92133. });
  92134. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  92135. this._attachedMesh = mesh;
  92136. };
  92137. /**
  92138. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  92139. *
  92140. * @param renderingGroupId The rendering group id corresponding to its index
  92141. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  92142. */
  92143. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  92144. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  92145. };
  92146. ReflectionProbe.prototype.dispose = function () {
  92147. var index = this._scene.reflectionProbes.indexOf(this);
  92148. if (index !== -1) {
  92149. // Remove from the scene if found
  92150. this._scene.reflectionProbes.splice(index, 1);
  92151. }
  92152. if (this._renderTargetTexture) {
  92153. this._renderTargetTexture.dispose();
  92154. this._renderTargetTexture = null;
  92155. }
  92156. };
  92157. return ReflectionProbe;
  92158. }());
  92159. BABYLON.ReflectionProbe = ReflectionProbe;
  92160. })(BABYLON || (BABYLON = {}));
  92161. //# sourceMappingURL=babylon.reflectionProbe.js.map
  92162. "use strict";
  92163. var BABYLON;
  92164. (function (BABYLON) {
  92165. var Layer = /** @class */ (function () {
  92166. function Layer(name, imgUrl, scene, isBackground, color) {
  92167. this.name = name;
  92168. this.scale = new BABYLON.Vector2(1, 1);
  92169. this.offset = new BABYLON.Vector2(0, 0);
  92170. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  92171. this.layerMask = 0x0FFFFFFF;
  92172. this._vertexBuffers = {};
  92173. // Events
  92174. /**
  92175. * An event triggered when the layer is disposed.
  92176. */
  92177. this.onDisposeObservable = new BABYLON.Observable();
  92178. /**
  92179. * An event triggered before rendering the scene
  92180. */
  92181. this.onBeforeRenderObservable = new BABYLON.Observable();
  92182. /**
  92183. * An event triggered after rendering the scene
  92184. */
  92185. this.onAfterRenderObservable = new BABYLON.Observable();
  92186. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  92187. this.isBackground = isBackground === undefined ? true : isBackground;
  92188. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  92189. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  92190. this._scene.layers.push(this);
  92191. var engine = this._scene.getEngine();
  92192. // VBO
  92193. var vertices = [];
  92194. vertices.push(1, 1);
  92195. vertices.push(-1, 1);
  92196. vertices.push(-1, -1);
  92197. vertices.push(1, -1);
  92198. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92199. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92200. this._createIndexBuffer();
  92201. // Effects
  92202. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  92203. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  92204. }
  92205. Object.defineProperty(Layer.prototype, "onDispose", {
  92206. set: function (callback) {
  92207. if (this._onDisposeObserver) {
  92208. this.onDisposeObservable.remove(this._onDisposeObserver);
  92209. }
  92210. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  92211. },
  92212. enumerable: true,
  92213. configurable: true
  92214. });
  92215. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  92216. set: function (callback) {
  92217. if (this._onBeforeRenderObserver) {
  92218. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  92219. }
  92220. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  92221. },
  92222. enumerable: true,
  92223. configurable: true
  92224. });
  92225. Object.defineProperty(Layer.prototype, "onAfterRender", {
  92226. set: function (callback) {
  92227. if (this._onAfterRenderObserver) {
  92228. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  92229. }
  92230. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  92231. },
  92232. enumerable: true,
  92233. configurable: true
  92234. });
  92235. Layer.prototype._createIndexBuffer = function () {
  92236. var engine = this._scene.getEngine();
  92237. // Indices
  92238. var indices = [];
  92239. indices.push(0);
  92240. indices.push(1);
  92241. indices.push(2);
  92242. indices.push(0);
  92243. indices.push(2);
  92244. indices.push(3);
  92245. this._indexBuffer = engine.createIndexBuffer(indices);
  92246. };
  92247. Layer.prototype._rebuild = function () {
  92248. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92249. if (vb) {
  92250. vb._rebuild();
  92251. }
  92252. this._createIndexBuffer();
  92253. };
  92254. Layer.prototype.render = function () {
  92255. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  92256. // Check
  92257. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  92258. return;
  92259. var engine = this._scene.getEngine();
  92260. this.onBeforeRenderObservable.notifyObservers(this);
  92261. // Render
  92262. engine.enableEffect(currentEffect);
  92263. engine.setState(false);
  92264. // Texture
  92265. currentEffect.setTexture("textureSampler", this.texture);
  92266. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  92267. // Color
  92268. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  92269. // Scale / offset
  92270. currentEffect.setVector2("offset", this.offset);
  92271. currentEffect.setVector2("scale", this.scale);
  92272. // VBOs
  92273. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92274. // Draw order
  92275. if (!this.alphaTest) {
  92276. engine.setAlphaMode(this.alphaBlendingMode);
  92277. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92278. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  92279. }
  92280. else {
  92281. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92282. }
  92283. this.onAfterRenderObservable.notifyObservers(this);
  92284. };
  92285. Layer.prototype.dispose = function () {
  92286. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92287. if (vertexBuffer) {
  92288. vertexBuffer.dispose();
  92289. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92290. }
  92291. if (this._indexBuffer) {
  92292. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92293. this._indexBuffer = null;
  92294. }
  92295. if (this.texture) {
  92296. this.texture.dispose();
  92297. this.texture = null;
  92298. }
  92299. // Remove from scene
  92300. var index = this._scene.layers.indexOf(this);
  92301. this._scene.layers.splice(index, 1);
  92302. // Callback
  92303. this.onDisposeObservable.notifyObservers(this);
  92304. this.onDisposeObservable.clear();
  92305. this.onAfterRenderObservable.clear();
  92306. this.onBeforeRenderObservable.clear();
  92307. };
  92308. return Layer;
  92309. }());
  92310. BABYLON.Layer = Layer;
  92311. })(BABYLON || (BABYLON = {}));
  92312. //# sourceMappingURL=babylon.layer.js.map
  92313. "use strict";
  92314. var BABYLON;
  92315. (function (BABYLON) {
  92316. var TextureTools = /** @class */ (function () {
  92317. function TextureTools() {
  92318. }
  92319. /**
  92320. * Uses the GPU to create a copy texture rescaled at a given size
  92321. * @param texture Texture to copy from
  92322. * @param width Desired width
  92323. * @param height Desired height
  92324. * @return Generated texture
  92325. */
  92326. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  92327. if (useBilinearMode === void 0) { useBilinearMode = true; }
  92328. var scene = texture.getScene();
  92329. var engine = scene.getEngine();
  92330. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  92331. rtt.wrapU = texture.wrapU;
  92332. rtt.wrapV = texture.wrapV;
  92333. rtt.uOffset = texture.uOffset;
  92334. rtt.vOffset = texture.vOffset;
  92335. rtt.uScale = texture.uScale;
  92336. rtt.vScale = texture.vScale;
  92337. rtt.uAng = texture.uAng;
  92338. rtt.vAng = texture.vAng;
  92339. rtt.wAng = texture.wAng;
  92340. rtt.coordinatesIndex = texture.coordinatesIndex;
  92341. rtt.level = texture.level;
  92342. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  92343. rtt._texture.isReady = false;
  92344. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92345. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92346. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92347. passPostProcess.getEffect().executeWhenCompiled(function () {
  92348. passPostProcess.onApply = function (effect) {
  92349. effect.setTexture("textureSampler", texture);
  92350. };
  92351. var internalTexture = rtt.getInternalTexture();
  92352. if (internalTexture) {
  92353. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  92354. engine.unBindFramebuffer(internalTexture);
  92355. rtt.disposeFramebufferObjects();
  92356. passPostProcess.dispose();
  92357. internalTexture.isReady = true;
  92358. }
  92359. });
  92360. return rtt;
  92361. };
  92362. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  92363. if (!scene._environmentBRDFTexture) {
  92364. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92365. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92366. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92367. scene._environmentBRDFTexture = texture;
  92368. }
  92369. return scene._environmentBRDFTexture;
  92370. };
  92371. 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=";
  92372. return TextureTools;
  92373. }());
  92374. BABYLON.TextureTools = TextureTools;
  92375. })(BABYLON || (BABYLON = {}));
  92376. //# sourceMappingURL=babylon.textureTools.js.map
  92377. "use strict";
  92378. var BABYLON;
  92379. (function (BABYLON) {
  92380. var FramingBehavior = /** @class */ (function () {
  92381. function FramingBehavior() {
  92382. this._mode = FramingBehavior.FitFrustumSidesMode;
  92383. this._radiusScale = 1.0;
  92384. this._positionScale = 0.5;
  92385. this._defaultElevation = 0.3;
  92386. this._elevationReturnTime = 1500;
  92387. this._elevationReturnWaitTime = 1000;
  92388. this._zoomStopsAnimation = false;
  92389. this._framingTime = 1500;
  92390. this._isPointerDown = false;
  92391. this._lastInteractionTime = -Infinity;
  92392. // Framing control
  92393. this._animatables = new Array();
  92394. this._betaIsAnimating = false;
  92395. }
  92396. Object.defineProperty(FramingBehavior.prototype, "name", {
  92397. get: function () {
  92398. return "Framing";
  92399. },
  92400. enumerable: true,
  92401. configurable: true
  92402. });
  92403. Object.defineProperty(FramingBehavior.prototype, "mode", {
  92404. /**
  92405. * Gets current mode used by the behavior.
  92406. */
  92407. get: function () {
  92408. return this._mode;
  92409. },
  92410. /**
  92411. * Sets the current mode used by the behavior
  92412. */
  92413. set: function (mode) {
  92414. this._mode = mode;
  92415. },
  92416. enumerable: true,
  92417. configurable: true
  92418. });
  92419. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  92420. /**
  92421. * Gets the scale applied to the radius
  92422. */
  92423. get: function () {
  92424. return this._radiusScale;
  92425. },
  92426. /**
  92427. * Sets the scale applied to the radius (1 by default)
  92428. */
  92429. set: function (radius) {
  92430. this._radiusScale = radius;
  92431. },
  92432. enumerable: true,
  92433. configurable: true
  92434. });
  92435. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  92436. /**
  92437. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92438. */
  92439. get: function () {
  92440. return this._positionScale;
  92441. },
  92442. /**
  92443. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92444. */
  92445. set: function (scale) {
  92446. this._positionScale = scale;
  92447. },
  92448. enumerable: true,
  92449. configurable: true
  92450. });
  92451. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  92452. /**
  92453. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92454. * behaviour is triggered, in radians.
  92455. */
  92456. get: function () {
  92457. return this._defaultElevation;
  92458. },
  92459. /**
  92460. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92461. * behaviour is triggered, in radians.
  92462. */
  92463. set: function (elevation) {
  92464. this._defaultElevation = elevation;
  92465. },
  92466. enumerable: true,
  92467. configurable: true
  92468. });
  92469. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  92470. /**
  92471. * Gets the time (in milliseconds) taken to return to the default beta position.
  92472. * Negative value indicates camera should not return to default.
  92473. */
  92474. get: function () {
  92475. return this._elevationReturnTime;
  92476. },
  92477. /**
  92478. * Sets the time (in milliseconds) taken to return to the default beta position.
  92479. * Negative value indicates camera should not return to default.
  92480. */
  92481. set: function (speed) {
  92482. this._elevationReturnTime = speed;
  92483. },
  92484. enumerable: true,
  92485. configurable: true
  92486. });
  92487. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  92488. /**
  92489. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92490. */
  92491. get: function () {
  92492. return this._elevationReturnWaitTime;
  92493. },
  92494. /**
  92495. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92496. */
  92497. set: function (time) {
  92498. this._elevationReturnWaitTime = time;
  92499. },
  92500. enumerable: true,
  92501. configurable: true
  92502. });
  92503. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  92504. /**
  92505. * Gets the flag that indicates if user zooming should stop animation.
  92506. */
  92507. get: function () {
  92508. return this._zoomStopsAnimation;
  92509. },
  92510. /**
  92511. * Sets the flag that indicates if user zooming should stop animation.
  92512. */
  92513. set: function (flag) {
  92514. this._zoomStopsAnimation = flag;
  92515. },
  92516. enumerable: true,
  92517. configurable: true
  92518. });
  92519. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  92520. /**
  92521. * Gets the transition time when framing the mesh, in milliseconds
  92522. */
  92523. get: function () {
  92524. return this._framingTime;
  92525. },
  92526. /**
  92527. * Sets the transition time when framing the mesh, in milliseconds
  92528. */
  92529. set: function (time) {
  92530. this._framingTime = time;
  92531. },
  92532. enumerable: true,
  92533. configurable: true
  92534. });
  92535. FramingBehavior.prototype.init = function () {
  92536. // Do notihng
  92537. };
  92538. FramingBehavior.prototype.attach = function (camera) {
  92539. var _this = this;
  92540. this._attachedCamera = camera;
  92541. var scene = this._attachedCamera.getScene();
  92542. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  92543. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92544. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92545. _this._isPointerDown = true;
  92546. return;
  92547. }
  92548. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92549. _this._isPointerDown = false;
  92550. }
  92551. });
  92552. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  92553. if (mesh) {
  92554. _this.zoomOnMesh(mesh);
  92555. }
  92556. });
  92557. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92558. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92559. _this._applyUserInteraction();
  92560. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  92561. // back to the default position after a given timeout
  92562. _this._maintainCameraAboveGround();
  92563. });
  92564. };
  92565. FramingBehavior.prototype.detach = function () {
  92566. if (!this._attachedCamera) {
  92567. return;
  92568. }
  92569. var scene = this._attachedCamera.getScene();
  92570. if (this._onPrePointerObservableObserver) {
  92571. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92572. }
  92573. if (this._onAfterCheckInputsObserver) {
  92574. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92575. }
  92576. if (this._onMeshTargetChangedObserver) {
  92577. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92578. }
  92579. this._attachedCamera = null;
  92580. };
  92581. /**
  92582. * Targets the given mesh and updates zoom level accordingly.
  92583. * @param mesh The mesh to target.
  92584. * @param radius Optional. If a cached radius position already exists, overrides default.
  92585. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92586. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92587. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92588. */
  92589. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92590. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92591. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92592. mesh.computeWorldMatrix(true);
  92593. var boundingBox = mesh.getBoundingInfo().boundingBox;
  92594. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  92595. };
  92596. /**
  92597. * Targets the given mesh with its children and updates zoom level accordingly.
  92598. * @param mesh The mesh to target.
  92599. * @param radius Optional. If a cached radius position already exists, overrides default.
  92600. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92601. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92602. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92603. */
  92604. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92605. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92606. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92607. mesh.computeWorldMatrix(true);
  92608. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  92609. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  92610. };
  92611. /**
  92612. * Targets the given meshes with their children and updates zoom level accordingly.
  92613. * @param meshes The mesh to target.
  92614. * @param radius Optional. If a cached radius position already exists, overrides default.
  92615. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92616. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92617. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92618. */
  92619. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  92620. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92621. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92622. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  92623. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  92624. for (var i = 0; i < meshes.length; i++) {
  92625. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  92626. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  92627. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  92628. }
  92629. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  92630. };
  92631. /**
  92632. * Targets the given mesh and updates zoom level accordingly.
  92633. * @param mesh The mesh to target.
  92634. * @param radius Optional. If a cached radius position already exists, overrides default.
  92635. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92636. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92637. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92638. */
  92639. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  92640. var _this = this;
  92641. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92642. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92643. var zoomTarget;
  92644. if (!this._attachedCamera) {
  92645. return;
  92646. }
  92647. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  92648. var bottom = minimumWorld.y;
  92649. var top = maximumWorld.y;
  92650. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  92651. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  92652. if (focusOnOriginXZ) {
  92653. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  92654. }
  92655. else {
  92656. var centerWorld = minimumWorld.add(radiusWorld);
  92657. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  92658. }
  92659. if (!this._vectorTransition) {
  92660. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  92661. }
  92662. this._betaIsAnimating = true;
  92663. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  92664. if (animatable) {
  92665. this._animatables.push(animatable);
  92666. }
  92667. // sets the radius and lower radius bounds
  92668. // Small delta ensures camera is not always at lower zoom limit.
  92669. var radius = 0;
  92670. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  92671. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92672. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  92673. radius = position;
  92674. }
  92675. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92676. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92677. if (this._attachedCamera.lowerRadiusLimit === null) {
  92678. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  92679. }
  92680. }
  92681. // Set sensibilities
  92682. var extend = maximumWorld.subtract(minimumWorld).length();
  92683. this._attachedCamera.panningSensibility = 5000 / extend;
  92684. this._attachedCamera.wheelPrecision = 100 / radius;
  92685. // transition to new radius
  92686. if (!this._radiusTransition) {
  92687. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92688. }
  92689. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  92690. _this.stopAllAnimations();
  92691. if (onAnimationEnd) {
  92692. onAnimationEnd();
  92693. }
  92694. if (_this._attachedCamera) {
  92695. _this._attachedCamera.storeState();
  92696. }
  92697. });
  92698. if (animatable) {
  92699. this._animatables.push(animatable);
  92700. }
  92701. };
  92702. /**
  92703. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  92704. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  92705. * frustum width.
  92706. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  92707. * to fully enclose the mesh in the viewing frustum.
  92708. */
  92709. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  92710. var size = maximumWorld.subtract(minimumWorld);
  92711. var boxVectorGlobalDiagonal = size.length();
  92712. var frustumSlope = this._getFrustumSlope();
  92713. // Formula for setting distance
  92714. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  92715. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  92716. // Horizon distance
  92717. var radius = radiusWithoutFraming * this._radiusScale;
  92718. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  92719. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  92720. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  92721. var camera = this._attachedCamera;
  92722. if (!camera) {
  92723. return 0;
  92724. }
  92725. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92726. // Don't exceed the requested limit
  92727. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  92728. }
  92729. // Don't exceed the upper radius limit
  92730. if (camera.upperRadiusLimit) {
  92731. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  92732. }
  92733. return distance;
  92734. };
  92735. /**
  92736. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  92737. * is automatically returned to its default position (expected to be above ground plane).
  92738. */
  92739. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  92740. var _this = this;
  92741. if (this._elevationReturnTime < 0) {
  92742. return;
  92743. }
  92744. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  92745. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  92746. var limitBeta = Math.PI * 0.5;
  92747. // Bring the camera back up if below the ground plane
  92748. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  92749. this._betaIsAnimating = true;
  92750. //Transition to new position
  92751. this.stopAllAnimations();
  92752. if (!this._betaTransition) {
  92753. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92754. }
  92755. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  92756. _this._clearAnimationLocks();
  92757. _this.stopAllAnimations();
  92758. });
  92759. if (animatabe) {
  92760. this._animatables.push(animatabe);
  92761. }
  92762. }
  92763. };
  92764. /**
  92765. * Returns the frustum slope based on the canvas ratio and camera FOV
  92766. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  92767. */
  92768. FramingBehavior.prototype._getFrustumSlope = function () {
  92769. // Calculate the viewport ratio
  92770. // Aspect Ratio is Height/Width.
  92771. var camera = this._attachedCamera;
  92772. if (!camera) {
  92773. return BABYLON.Vector2.Zero();
  92774. }
  92775. var engine = camera.getScene().getEngine();
  92776. var aspectRatio = engine.getAspectRatio(camera);
  92777. // Camera FOV is the vertical field of view (top-bottom) in radians.
  92778. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  92779. var frustumSlopeY = Math.tan(camera.fov / 2);
  92780. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  92781. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  92782. // along the forward vector.
  92783. var frustumSlopeX = frustumSlopeY * aspectRatio;
  92784. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  92785. };
  92786. /**
  92787. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  92788. */
  92789. FramingBehavior.prototype._clearAnimationLocks = function () {
  92790. this._betaIsAnimating = false;
  92791. };
  92792. /**
  92793. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92794. */
  92795. FramingBehavior.prototype._applyUserInteraction = function () {
  92796. if (this.isUserIsMoving) {
  92797. this._lastInteractionTime = BABYLON.Tools.Now;
  92798. this.stopAllAnimations();
  92799. this._clearAnimationLocks();
  92800. }
  92801. };
  92802. /**
  92803. * Stops and removes all animations that have been applied to the camera
  92804. */
  92805. FramingBehavior.prototype.stopAllAnimations = function () {
  92806. if (this._attachedCamera) {
  92807. this._attachedCamera.animations = [];
  92808. }
  92809. while (this._animatables.length) {
  92810. if (this._animatables[0]) {
  92811. this._animatables[0].onAnimationEnd = null;
  92812. this._animatables[0].stop();
  92813. }
  92814. this._animatables.shift();
  92815. }
  92816. };
  92817. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  92818. /**
  92819. * Gets a value indicating if the user is moving the camera
  92820. */
  92821. get: function () {
  92822. if (!this._attachedCamera) {
  92823. return false;
  92824. }
  92825. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92826. this._attachedCamera.inertialBetaOffset !== 0 ||
  92827. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92828. this._attachedCamera.inertialPanningX !== 0 ||
  92829. this._attachedCamera.inertialPanningY !== 0 ||
  92830. this._isPointerDown;
  92831. },
  92832. enumerable: true,
  92833. configurable: true
  92834. });
  92835. /**
  92836. * The easing function used by animations
  92837. */
  92838. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  92839. /**
  92840. * The easing mode used by animations
  92841. */
  92842. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  92843. // Statics
  92844. /**
  92845. * The camera can move all the way towards the mesh.
  92846. */
  92847. FramingBehavior.IgnoreBoundsSizeMode = 0;
  92848. /**
  92849. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  92850. */
  92851. FramingBehavior.FitFrustumSidesMode = 1;
  92852. return FramingBehavior;
  92853. }());
  92854. BABYLON.FramingBehavior = FramingBehavior;
  92855. })(BABYLON || (BABYLON = {}));
  92856. //# sourceMappingURL=babylon.framingBehavior.js.map
  92857. "use strict";
  92858. var BABYLON;
  92859. (function (BABYLON) {
  92860. /**
  92861. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  92862. */
  92863. var BouncingBehavior = /** @class */ (function () {
  92864. function BouncingBehavior() {
  92865. /**
  92866. * The duration of the animation, in milliseconds
  92867. */
  92868. this.transitionDuration = 450;
  92869. /**
  92870. * Length of the distance animated by the transition when lower radius is reached
  92871. */
  92872. this.lowerRadiusTransitionRange = 2;
  92873. /**
  92874. * Length of the distance animated by the transition when upper radius is reached
  92875. */
  92876. this.upperRadiusTransitionRange = -2;
  92877. this._autoTransitionRange = false;
  92878. // Animations
  92879. this._radiusIsAnimating = false;
  92880. this._radiusBounceTransition = null;
  92881. this._animatables = new Array();
  92882. }
  92883. Object.defineProperty(BouncingBehavior.prototype, "name", {
  92884. get: function () {
  92885. return "Bouncing";
  92886. },
  92887. enumerable: true,
  92888. configurable: true
  92889. });
  92890. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  92891. /**
  92892. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  92893. */
  92894. get: function () {
  92895. return this._autoTransitionRange;
  92896. },
  92897. /**
  92898. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  92899. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  92900. */
  92901. set: function (value) {
  92902. var _this = this;
  92903. if (this._autoTransitionRange === value) {
  92904. return;
  92905. }
  92906. this._autoTransitionRange = value;
  92907. var camera = this._attachedCamera;
  92908. if (!camera) {
  92909. return;
  92910. }
  92911. if (value) {
  92912. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  92913. if (!mesh) {
  92914. return;
  92915. }
  92916. mesh.computeWorldMatrix(true);
  92917. var diagonal = mesh.getBoundingInfo().diagonalLength;
  92918. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  92919. _this.upperRadiusTransitionRange = diagonal * 0.05;
  92920. });
  92921. }
  92922. else if (this._onMeshTargetChangedObserver) {
  92923. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92924. }
  92925. },
  92926. enumerable: true,
  92927. configurable: true
  92928. });
  92929. BouncingBehavior.prototype.init = function () {
  92930. // Do notihng
  92931. };
  92932. BouncingBehavior.prototype.attach = function (camera) {
  92933. var _this = this;
  92934. this._attachedCamera = camera;
  92935. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92936. if (!_this._attachedCamera) {
  92937. return;
  92938. }
  92939. // Add the bounce animation to the lower radius limit
  92940. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  92941. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  92942. }
  92943. // Add the bounce animation to the upper radius limit
  92944. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  92945. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  92946. }
  92947. });
  92948. };
  92949. BouncingBehavior.prototype.detach = function () {
  92950. if (!this._attachedCamera) {
  92951. return;
  92952. }
  92953. if (this._onAfterCheckInputsObserver) {
  92954. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92955. }
  92956. if (this._onMeshTargetChangedObserver) {
  92957. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92958. }
  92959. this._attachedCamera = null;
  92960. };
  92961. /**
  92962. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  92963. * @param radiusLimit The limit to check against.
  92964. * @return Bool to indicate if at limit.
  92965. */
  92966. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  92967. if (!this._attachedCamera) {
  92968. return false;
  92969. }
  92970. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  92971. return true;
  92972. }
  92973. return false;
  92974. };
  92975. /**
  92976. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  92977. * @param radiusDelta The delta by which to animate to. Can be negative.
  92978. */
  92979. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  92980. var _this = this;
  92981. if (!this._attachedCamera) {
  92982. return;
  92983. }
  92984. if (!this._radiusBounceTransition) {
  92985. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  92986. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  92987. }
  92988. // Prevent zoom until bounce has completed
  92989. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  92990. this._attachedCamera.wheelPrecision = Infinity;
  92991. this._attachedCamera.inertialRadiusOffset = 0;
  92992. // Animate to the radius limit
  92993. this.stopAllAnimations();
  92994. this._radiusIsAnimating = true;
  92995. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  92996. if (animatable) {
  92997. this._animatables.push(animatable);
  92998. }
  92999. };
  93000. /**
  93001. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  93002. */
  93003. BouncingBehavior.prototype._clearAnimationLocks = function () {
  93004. this._radiusIsAnimating = false;
  93005. if (this._attachedCamera) {
  93006. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  93007. }
  93008. };
  93009. /**
  93010. * Stops and removes all animations that have been applied to the camera
  93011. */
  93012. BouncingBehavior.prototype.stopAllAnimations = function () {
  93013. if (this._attachedCamera) {
  93014. this._attachedCamera.animations = [];
  93015. }
  93016. while (this._animatables.length) {
  93017. this._animatables[0].onAnimationEnd = null;
  93018. this._animatables[0].stop();
  93019. this._animatables.shift();
  93020. }
  93021. };
  93022. /**
  93023. * The easing function used by animations
  93024. */
  93025. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  93026. /**
  93027. * The easing mode used by animations
  93028. */
  93029. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  93030. return BouncingBehavior;
  93031. }());
  93032. BABYLON.BouncingBehavior = BouncingBehavior;
  93033. })(BABYLON || (BABYLON = {}));
  93034. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  93035. "use strict";
  93036. var BABYLON;
  93037. (function (BABYLON) {
  93038. var AutoRotationBehavior = /** @class */ (function () {
  93039. function AutoRotationBehavior() {
  93040. this._zoomStopsAnimation = false;
  93041. this._idleRotationSpeed = 0.05;
  93042. this._idleRotationWaitTime = 2000;
  93043. this._idleRotationSpinupTime = 2000;
  93044. this._isPointerDown = false;
  93045. this._lastFrameTime = null;
  93046. this._lastInteractionTime = -Infinity;
  93047. this._cameraRotationSpeed = 0;
  93048. this._lastFrameRadius = 0;
  93049. }
  93050. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  93051. get: function () {
  93052. return "AutoRotation";
  93053. },
  93054. enumerable: true,
  93055. configurable: true
  93056. });
  93057. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  93058. /**
  93059. * Gets the flag that indicates if user zooming should stop animation.
  93060. */
  93061. get: function () {
  93062. return this._zoomStopsAnimation;
  93063. },
  93064. /**
  93065. * Sets the flag that indicates if user zooming should stop animation.
  93066. */
  93067. set: function (flag) {
  93068. this._zoomStopsAnimation = flag;
  93069. },
  93070. enumerable: true,
  93071. configurable: true
  93072. });
  93073. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  93074. /**
  93075. * Gets the default speed at which the camera rotates around the model.
  93076. */
  93077. get: function () {
  93078. return this._idleRotationSpeed;
  93079. },
  93080. /**
  93081. * Sets the default speed at which the camera rotates around the model.
  93082. */
  93083. set: function (speed) {
  93084. this._idleRotationSpeed = speed;
  93085. },
  93086. enumerable: true,
  93087. configurable: true
  93088. });
  93089. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  93090. /**
  93091. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  93092. */
  93093. get: function () {
  93094. return this._idleRotationWaitTime;
  93095. },
  93096. /**
  93097. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  93098. */
  93099. set: function (time) {
  93100. this._idleRotationWaitTime = time;
  93101. },
  93102. enumerable: true,
  93103. configurable: true
  93104. });
  93105. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  93106. /**
  93107. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93108. */
  93109. get: function () {
  93110. return this._idleRotationSpinupTime;
  93111. },
  93112. /**
  93113. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93114. */
  93115. set: function (time) {
  93116. this._idleRotationSpinupTime = time;
  93117. },
  93118. enumerable: true,
  93119. configurable: true
  93120. });
  93121. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  93122. /**
  93123. * Gets a value indicating if the camera is currently rotating because of this behavior
  93124. */
  93125. get: function () {
  93126. return Math.abs(this._cameraRotationSpeed) > 0;
  93127. },
  93128. enumerable: true,
  93129. configurable: true
  93130. });
  93131. AutoRotationBehavior.prototype.init = function () {
  93132. // Do notihng
  93133. };
  93134. AutoRotationBehavior.prototype.attach = function (camera) {
  93135. var _this = this;
  93136. this._attachedCamera = camera;
  93137. var scene = this._attachedCamera.getScene();
  93138. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93139. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93140. _this._isPointerDown = true;
  93141. return;
  93142. }
  93143. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93144. _this._isPointerDown = false;
  93145. }
  93146. });
  93147. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93148. var now = BABYLON.Tools.Now;
  93149. var dt = 0;
  93150. if (_this._lastFrameTime != null) {
  93151. dt = now - _this._lastFrameTime;
  93152. }
  93153. _this._lastFrameTime = now;
  93154. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93155. _this._applyUserInteraction();
  93156. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  93157. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  93158. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  93159. // Step camera rotation by rotation speed
  93160. if (_this._attachedCamera) {
  93161. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  93162. }
  93163. });
  93164. };
  93165. AutoRotationBehavior.prototype.detach = function () {
  93166. if (!this._attachedCamera) {
  93167. return;
  93168. }
  93169. var scene = this._attachedCamera.getScene();
  93170. if (this._onPrePointerObservableObserver) {
  93171. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  93172. }
  93173. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93174. this._attachedCamera = null;
  93175. };
  93176. /**
  93177. * Returns true if user is scrolling.
  93178. * @return true if user is scrolling.
  93179. */
  93180. AutoRotationBehavior.prototype._userIsZooming = function () {
  93181. if (!this._attachedCamera) {
  93182. return false;
  93183. }
  93184. return this._attachedCamera.inertialRadiusOffset !== 0;
  93185. };
  93186. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  93187. if (!this._attachedCamera) {
  93188. return false;
  93189. }
  93190. var zoomHasHitLimit = false;
  93191. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  93192. zoomHasHitLimit = true;
  93193. }
  93194. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  93195. this._lastFrameRadius = this._attachedCamera.radius;
  93196. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  93197. };
  93198. /**
  93199. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93200. */
  93201. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  93202. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  93203. this._lastInteractionTime = BABYLON.Tools.Now;
  93204. }
  93205. };
  93206. // Tools
  93207. AutoRotationBehavior.prototype._userIsMoving = function () {
  93208. if (!this._attachedCamera) {
  93209. return false;
  93210. }
  93211. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93212. this._attachedCamera.inertialBetaOffset !== 0 ||
  93213. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93214. this._attachedCamera.inertialPanningX !== 0 ||
  93215. this._attachedCamera.inertialPanningY !== 0 ||
  93216. this._isPointerDown;
  93217. };
  93218. return AutoRotationBehavior;
  93219. }());
  93220. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  93221. })(BABYLON || (BABYLON = {}));
  93222. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  93223. "use strict";
  93224. var BABYLON;
  93225. (function (BABYLON) {
  93226. var NullEngineOptions = /** @class */ (function () {
  93227. function NullEngineOptions() {
  93228. this.renderWidth = 512;
  93229. this.renderHeight = 256;
  93230. this.textureSize = 512;
  93231. this.deterministicLockstep = false;
  93232. this.lockstepMaxSteps = 4;
  93233. }
  93234. return NullEngineOptions;
  93235. }());
  93236. BABYLON.NullEngineOptions = NullEngineOptions;
  93237. /**
  93238. * The null engine class provides support for headless version of babylon.js.
  93239. * This can be used in server side scenario or for testing purposes
  93240. */
  93241. var NullEngine = /** @class */ (function (_super) {
  93242. __extends(NullEngine, _super);
  93243. function NullEngine(options) {
  93244. if (options === void 0) { options = new NullEngineOptions(); }
  93245. var _this = _super.call(this, null) || this;
  93246. if (options.deterministicLockstep === undefined) {
  93247. options.deterministicLockstep = false;
  93248. }
  93249. if (options.lockstepMaxSteps === undefined) {
  93250. options.lockstepMaxSteps = 4;
  93251. }
  93252. _this._options = options;
  93253. // Init caps
  93254. // We consider we are on a webgl1 capable device
  93255. _this._caps = new BABYLON.EngineCapabilities();
  93256. _this._caps.maxTexturesImageUnits = 16;
  93257. _this._caps.maxVertexTextureImageUnits = 16;
  93258. _this._caps.maxTextureSize = 512;
  93259. _this._caps.maxCubemapTextureSize = 512;
  93260. _this._caps.maxRenderTextureSize = 512;
  93261. _this._caps.maxVertexAttribs = 16;
  93262. _this._caps.maxVaryingVectors = 16;
  93263. _this._caps.maxFragmentUniformVectors = 16;
  93264. _this._caps.maxVertexUniformVectors = 16;
  93265. // Extensions
  93266. _this._caps.standardDerivatives = false;
  93267. _this._caps.astc = null;
  93268. _this._caps.s3tc = null;
  93269. _this._caps.pvrtc = null;
  93270. _this._caps.etc1 = null;
  93271. _this._caps.etc2 = null;
  93272. _this._caps.textureAnisotropicFilterExtension = null;
  93273. _this._caps.maxAnisotropy = 0;
  93274. _this._caps.uintIndices = false;
  93275. _this._caps.fragmentDepthSupported = false;
  93276. _this._caps.highPrecisionShaderSupported = true;
  93277. _this._caps.colorBufferFloat = false;
  93278. _this._caps.textureFloat = false;
  93279. _this._caps.textureFloatLinearFiltering = false;
  93280. _this._caps.textureFloatRender = false;
  93281. _this._caps.textureHalfFloat = false;
  93282. _this._caps.textureHalfFloatLinearFiltering = false;
  93283. _this._caps.textureHalfFloatRender = false;
  93284. _this._caps.textureLOD = false;
  93285. _this._caps.drawBuffersExtension = false;
  93286. _this._caps.depthTextureExtension = false;
  93287. _this._caps.vertexArrayObject = false;
  93288. _this._caps.instancedArrays = false;
  93289. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  93290. // Wrappers
  93291. if (typeof URL === "undefined") {
  93292. URL = {
  93293. createObjectURL: function () { },
  93294. revokeObjectURL: function () { }
  93295. };
  93296. }
  93297. if (typeof Blob === "undefined") {
  93298. Blob = function () { };
  93299. }
  93300. return _this;
  93301. }
  93302. NullEngine.prototype.isDeterministicLockStep = function () {
  93303. return this._options.deterministicLockstep;
  93304. };
  93305. NullEngine.prototype.getLockstepMaxSteps = function () {
  93306. return this._options.lockstepMaxSteps;
  93307. };
  93308. NullEngine.prototype.getHardwareScalingLevel = function () {
  93309. return 1.0;
  93310. };
  93311. NullEngine.prototype.createVertexBuffer = function (vertices) {
  93312. return {
  93313. capacity: 0,
  93314. references: 1,
  93315. is32Bits: false
  93316. };
  93317. };
  93318. NullEngine.prototype.createIndexBuffer = function (indices) {
  93319. return {
  93320. capacity: 0,
  93321. references: 1,
  93322. is32Bits: false
  93323. };
  93324. };
  93325. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  93326. if (stencil === void 0) { stencil = false; }
  93327. };
  93328. NullEngine.prototype.getRenderWidth = function (useScreen) {
  93329. if (useScreen === void 0) { useScreen = false; }
  93330. if (!useScreen && this._currentRenderTarget) {
  93331. return this._currentRenderTarget.width;
  93332. }
  93333. return this._options.renderWidth;
  93334. };
  93335. NullEngine.prototype.getRenderHeight = function (useScreen) {
  93336. if (useScreen === void 0) { useScreen = false; }
  93337. if (!useScreen && this._currentRenderTarget) {
  93338. return this._currentRenderTarget.height;
  93339. }
  93340. return this._options.renderHeight;
  93341. };
  93342. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  93343. this._cachedViewport = viewport;
  93344. };
  93345. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  93346. return {
  93347. transformFeedback: null,
  93348. __SPECTOR_rebuildProgram: null
  93349. };
  93350. };
  93351. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  93352. return [];
  93353. };
  93354. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  93355. return [];
  93356. };
  93357. NullEngine.prototype.bindSamplers = function (effect) {
  93358. this._currentEffect = null;
  93359. };
  93360. NullEngine.prototype.enableEffect = function (effect) {
  93361. this._currentEffect = effect;
  93362. if (effect.onBind) {
  93363. effect.onBind(effect);
  93364. }
  93365. effect.onBindObservable.notifyObservers(effect);
  93366. };
  93367. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  93368. if (zOffset === void 0) { zOffset = 0; }
  93369. if (reverseSide === void 0) { reverseSide = false; }
  93370. };
  93371. NullEngine.prototype.setIntArray = function (uniform, array) {
  93372. };
  93373. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  93374. };
  93375. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  93376. };
  93377. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  93378. };
  93379. NullEngine.prototype.setFloatArray = function (uniform, array) {
  93380. };
  93381. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  93382. };
  93383. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  93384. };
  93385. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  93386. };
  93387. NullEngine.prototype.setArray = function (uniform, array) {
  93388. };
  93389. NullEngine.prototype.setArray2 = function (uniform, array) {
  93390. };
  93391. NullEngine.prototype.setArray3 = function (uniform, array) {
  93392. };
  93393. NullEngine.prototype.setArray4 = function (uniform, array) {
  93394. };
  93395. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  93396. };
  93397. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  93398. };
  93399. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  93400. };
  93401. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  93402. };
  93403. NullEngine.prototype.setFloat = function (uniform, value) {
  93404. };
  93405. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  93406. };
  93407. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  93408. };
  93409. NullEngine.prototype.setBool = function (uniform, bool) {
  93410. };
  93411. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  93412. };
  93413. NullEngine.prototype.setColor3 = function (uniform, color3) {
  93414. };
  93415. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  93416. };
  93417. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  93418. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  93419. if (this._alphaMode === mode) {
  93420. return;
  93421. }
  93422. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  93423. if (!noDepthWriteChange) {
  93424. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  93425. }
  93426. this._alphaMode = mode;
  93427. };
  93428. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  93429. };
  93430. NullEngine.prototype.wipeCaches = function (bruteForce) {
  93431. if (this.preventCacheWipeBetweenFrames) {
  93432. return;
  93433. }
  93434. this.resetTextureCache();
  93435. this._currentEffect = null;
  93436. if (bruteForce) {
  93437. this._currentProgram = null;
  93438. this._stencilState.reset();
  93439. this._depthCullingState.reset();
  93440. this._alphaState.reset();
  93441. }
  93442. this._cachedVertexBuffers = null;
  93443. this._cachedIndexBuffer = null;
  93444. this._cachedEffectForVertexBuffers = null;
  93445. };
  93446. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  93447. };
  93448. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  93449. };
  93450. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  93451. };
  93452. NullEngine.prototype._createTexture = function () {
  93453. return {};
  93454. };
  93455. NullEngine.prototype._releaseTexture = function (texture) {
  93456. };
  93457. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  93458. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93459. if (onLoad === void 0) { onLoad = null; }
  93460. if (onError === void 0) { onError = null; }
  93461. if (buffer === void 0) { buffer = null; }
  93462. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  93463. var url = String(urlArg);
  93464. texture.url = url;
  93465. texture.generateMipMaps = !noMipmap;
  93466. texture.samplingMode = samplingMode;
  93467. texture.invertY = invertY;
  93468. texture.baseWidth = this._options.textureSize;
  93469. texture.baseHeight = this._options.textureSize;
  93470. texture.width = this._options.textureSize;
  93471. texture.height = this._options.textureSize;
  93472. if (format) {
  93473. texture.format = format;
  93474. }
  93475. texture.isReady = true;
  93476. if (onLoad) {
  93477. onLoad();
  93478. }
  93479. return texture;
  93480. };
  93481. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  93482. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  93483. if (options !== undefined && typeof options === "object") {
  93484. fullOptions.generateMipMaps = options.generateMipMaps;
  93485. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  93486. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  93487. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  93488. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  93489. }
  93490. else {
  93491. fullOptions.generateMipMaps = options;
  93492. fullOptions.generateDepthBuffer = true;
  93493. fullOptions.generateStencilBuffer = false;
  93494. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93495. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  93496. }
  93497. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  93498. var width = size.width || size;
  93499. var height = size.height || size;
  93500. texture._depthStencilBuffer = {};
  93501. texture._framebuffer = {};
  93502. texture.baseWidth = width;
  93503. texture.baseHeight = height;
  93504. texture.width = width;
  93505. texture.height = height;
  93506. texture.isReady = true;
  93507. texture.samples = 1;
  93508. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  93509. texture.samplingMode = fullOptions.samplingMode;
  93510. texture.type = fullOptions.type;
  93511. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  93512. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  93513. return texture;
  93514. };
  93515. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  93516. texture.samplingMode = samplingMode;
  93517. };
  93518. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  93519. if (this._currentRenderTarget) {
  93520. this.unBindFramebuffer(this._currentRenderTarget);
  93521. }
  93522. this._currentRenderTarget = texture;
  93523. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  93524. if (this._cachedViewport && !forceFullscreenViewport) {
  93525. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  93526. }
  93527. };
  93528. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  93529. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  93530. this._currentRenderTarget = null;
  93531. if (onBeforeUnbind) {
  93532. if (texture._MSAAFramebuffer) {
  93533. this._currentFramebuffer = texture._framebuffer;
  93534. }
  93535. onBeforeUnbind();
  93536. }
  93537. this._currentFramebuffer = null;
  93538. };
  93539. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  93540. var vbo = {
  93541. capacity: 1,
  93542. references: 1,
  93543. is32Bits: false
  93544. };
  93545. return vbo;
  93546. };
  93547. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  93548. if (offset === void 0) { offset = 0; }
  93549. };
  93550. /**
  93551. * Updates a dynamic vertex buffer.
  93552. * @param vertexBuffer the vertex buffer to update
  93553. * @param data the data used to update the vertex buffer
  93554. * @param byteOffset the byte offset of the data (optional)
  93555. * @param byteLength the byte length of the data (optional)
  93556. */
  93557. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  93558. };
  93559. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  93560. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  93561. this._boundTexturesCache[this._activeChannel] = texture;
  93562. }
  93563. };
  93564. NullEngine.prototype._bindTexture = function (channel, texture) {
  93565. if (channel < 0) {
  93566. return;
  93567. }
  93568. this._bindTextureDirectly(0, texture);
  93569. };
  93570. NullEngine.prototype._releaseBuffer = function (buffer) {
  93571. buffer.references--;
  93572. if (buffer.references === 0) {
  93573. return true;
  93574. }
  93575. return false;
  93576. };
  93577. return NullEngine;
  93578. }(BABYLON.Engine));
  93579. BABYLON.NullEngine = NullEngine;
  93580. })(BABYLON || (BABYLON = {}));
  93581. //# sourceMappingURL=babylon.nullEngine.js.map
  93582. "use strict";
  93583. var BABYLON;
  93584. (function (BABYLON) {
  93585. /**
  93586. * This class can be used to get instrumentation data from a Babylon engine
  93587. */
  93588. var EngineInstrumentation = /** @class */ (function () {
  93589. function EngineInstrumentation(engine) {
  93590. this.engine = engine;
  93591. this._captureGPUFrameTime = false;
  93592. this._gpuFrameTime = new BABYLON.PerfCounter();
  93593. this._captureShaderCompilationTime = false;
  93594. this._shaderCompilationTime = new BABYLON.PerfCounter();
  93595. // Observers
  93596. this._onBeginFrameObserver = null;
  93597. this._onEndFrameObserver = null;
  93598. this._onBeforeShaderCompilationObserver = null;
  93599. this._onAfterShaderCompilationObserver = null;
  93600. }
  93601. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  93602. // Properties
  93603. /**
  93604. * Gets the perf counter used for GPU frame time
  93605. */
  93606. get: function () {
  93607. return this._gpuFrameTime;
  93608. },
  93609. enumerable: true,
  93610. configurable: true
  93611. });
  93612. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  93613. /**
  93614. * Gets the GPU frame time capture status
  93615. */
  93616. get: function () {
  93617. return this._captureGPUFrameTime;
  93618. },
  93619. /**
  93620. * Enable or disable the GPU frame time capture
  93621. */
  93622. set: function (value) {
  93623. var _this = this;
  93624. if (value === this._captureGPUFrameTime) {
  93625. return;
  93626. }
  93627. this._captureGPUFrameTime = value;
  93628. if (value) {
  93629. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  93630. if (!_this._gpuFrameTimeToken) {
  93631. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  93632. }
  93633. });
  93634. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  93635. if (!_this._gpuFrameTimeToken) {
  93636. return;
  93637. }
  93638. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  93639. if (time > -1) {
  93640. _this._gpuFrameTimeToken = null;
  93641. _this._gpuFrameTime.fetchNewFrame();
  93642. _this._gpuFrameTime.addCount(time, true);
  93643. }
  93644. });
  93645. }
  93646. else {
  93647. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93648. this._onBeginFrameObserver = null;
  93649. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93650. this._onEndFrameObserver = null;
  93651. }
  93652. },
  93653. enumerable: true,
  93654. configurable: true
  93655. });
  93656. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  93657. /**
  93658. * Gets the perf counter used for shader compilation time
  93659. */
  93660. get: function () {
  93661. return this._shaderCompilationTime;
  93662. },
  93663. enumerable: true,
  93664. configurable: true
  93665. });
  93666. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  93667. /**
  93668. * Gets the shader compilation time capture status
  93669. */
  93670. get: function () {
  93671. return this._captureShaderCompilationTime;
  93672. },
  93673. /**
  93674. * Enable or disable the shader compilation time capture
  93675. */
  93676. set: function (value) {
  93677. var _this = this;
  93678. if (value === this._captureShaderCompilationTime) {
  93679. return;
  93680. }
  93681. this._captureShaderCompilationTime = value;
  93682. if (value) {
  93683. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  93684. _this._shaderCompilationTime.fetchNewFrame();
  93685. _this._shaderCompilationTime.beginMonitoring();
  93686. });
  93687. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  93688. _this._shaderCompilationTime.endMonitoring();
  93689. });
  93690. }
  93691. else {
  93692. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93693. this._onBeforeShaderCompilationObserver = null;
  93694. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93695. this._onAfterShaderCompilationObserver = null;
  93696. }
  93697. },
  93698. enumerable: true,
  93699. configurable: true
  93700. });
  93701. EngineInstrumentation.prototype.dispose = function () {
  93702. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93703. this._onBeginFrameObserver = null;
  93704. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93705. this._onEndFrameObserver = null;
  93706. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93707. this._onBeforeShaderCompilationObserver = null;
  93708. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93709. this._onAfterShaderCompilationObserver = null;
  93710. this.engine = null;
  93711. };
  93712. return EngineInstrumentation;
  93713. }());
  93714. BABYLON.EngineInstrumentation = EngineInstrumentation;
  93715. })(BABYLON || (BABYLON = {}));
  93716. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  93717. "use strict";
  93718. var BABYLON;
  93719. (function (BABYLON) {
  93720. /**
  93721. * This class can be used to get instrumentation data from a Babylon engine
  93722. */
  93723. var SceneInstrumentation = /** @class */ (function () {
  93724. function SceneInstrumentation(scene) {
  93725. var _this = this;
  93726. this.scene = scene;
  93727. this._captureActiveMeshesEvaluationTime = false;
  93728. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  93729. this._captureRenderTargetsRenderTime = false;
  93730. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  93731. this._captureFrameTime = false;
  93732. this._frameTime = new BABYLON.PerfCounter();
  93733. this._captureRenderTime = false;
  93734. this._renderTime = new BABYLON.PerfCounter();
  93735. this._captureInterFrameTime = false;
  93736. this._interFrameTime = new BABYLON.PerfCounter();
  93737. this._captureParticlesRenderTime = false;
  93738. this._particlesRenderTime = new BABYLON.PerfCounter();
  93739. this._captureSpritesRenderTime = false;
  93740. this._spritesRenderTime = new BABYLON.PerfCounter();
  93741. this._capturePhysicsTime = false;
  93742. this._physicsTime = new BABYLON.PerfCounter();
  93743. this._captureAnimationsTime = false;
  93744. this._animationsTime = new BABYLON.PerfCounter();
  93745. // Observers
  93746. this._onBeforeActiveMeshesEvaluationObserver = null;
  93747. this._onAfterActiveMeshesEvaluationObserver = null;
  93748. this._onBeforeRenderTargetsRenderObserver = null;
  93749. this._onAfterRenderTargetsRenderObserver = null;
  93750. this._onAfterRenderObserver = null;
  93751. this._onBeforeDrawPhaseObserver = null;
  93752. this._onAfterDrawPhaseObserver = null;
  93753. this._onBeforeAnimationsObserver = null;
  93754. this._onBeforeParticlesRenderingObserver = null;
  93755. this._onAfterParticlesRenderingObserver = null;
  93756. this._onBeforeSpritesRenderingObserver = null;
  93757. this._onAfterSpritesRenderingObserver = null;
  93758. this._onBeforePhysicsObserver = null;
  93759. this._onAfterPhysicsObserver = null;
  93760. this._onAfterAnimationsObserver = null;
  93761. // Before render
  93762. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  93763. if (_this._captureActiveMeshesEvaluationTime) {
  93764. _this._activeMeshesEvaluationTime.fetchNewFrame();
  93765. }
  93766. if (_this._captureRenderTargetsRenderTime) {
  93767. _this._renderTargetsRenderTime.fetchNewFrame();
  93768. }
  93769. if (_this._captureFrameTime) {
  93770. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  93771. _this._frameTime.beginMonitoring();
  93772. }
  93773. if (_this._captureInterFrameTime) {
  93774. _this._interFrameTime.endMonitoring();
  93775. }
  93776. if (_this._captureParticlesRenderTime) {
  93777. _this._particlesRenderTime.fetchNewFrame();
  93778. }
  93779. if (_this._captureSpritesRenderTime) {
  93780. _this._spritesRenderTime.fetchNewFrame();
  93781. }
  93782. if (_this._captureAnimationsTime) {
  93783. _this._animationsTime.beginMonitoring();
  93784. }
  93785. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  93786. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  93787. });
  93788. // After render
  93789. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  93790. if (_this._captureFrameTime) {
  93791. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  93792. _this._frameTime.endMonitoring();
  93793. }
  93794. if (_this._captureRenderTime) {
  93795. _this._renderTime.endMonitoring(false);
  93796. }
  93797. if (_this._captureInterFrameTime) {
  93798. _this._interFrameTime.beginMonitoring();
  93799. }
  93800. });
  93801. }
  93802. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  93803. // Properties
  93804. /**
  93805. * Gets the perf counter used for active meshes evaluation time
  93806. */
  93807. get: function () {
  93808. return this._activeMeshesEvaluationTime;
  93809. },
  93810. enumerable: true,
  93811. configurable: true
  93812. });
  93813. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  93814. /**
  93815. * Gets the active meshes evaluation time capture status
  93816. */
  93817. get: function () {
  93818. return this._captureActiveMeshesEvaluationTime;
  93819. },
  93820. /**
  93821. * Enable or disable the active meshes evaluation time capture
  93822. */
  93823. set: function (value) {
  93824. var _this = this;
  93825. if (value === this._captureActiveMeshesEvaluationTime) {
  93826. return;
  93827. }
  93828. this._captureActiveMeshesEvaluationTime = value;
  93829. if (value) {
  93830. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  93831. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  93832. _this._activeMeshesEvaluationTime.beginMonitoring();
  93833. });
  93834. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  93835. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  93836. _this._activeMeshesEvaluationTime.endMonitoring();
  93837. });
  93838. }
  93839. else {
  93840. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  93841. this._onBeforeActiveMeshesEvaluationObserver = null;
  93842. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  93843. this._onAfterActiveMeshesEvaluationObserver = null;
  93844. }
  93845. },
  93846. enumerable: true,
  93847. configurable: true
  93848. });
  93849. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  93850. /**
  93851. * Gets the perf counter used for render targets render time
  93852. */
  93853. get: function () {
  93854. return this._renderTargetsRenderTime;
  93855. },
  93856. enumerable: true,
  93857. configurable: true
  93858. });
  93859. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  93860. /**
  93861. * Gets the render targets render time capture status
  93862. */
  93863. get: function () {
  93864. return this._captureRenderTargetsRenderTime;
  93865. },
  93866. /**
  93867. * Enable or disable the render targets render time capture
  93868. */
  93869. set: function (value) {
  93870. var _this = this;
  93871. if (value === this._captureRenderTargetsRenderTime) {
  93872. return;
  93873. }
  93874. this._captureRenderTargetsRenderTime = value;
  93875. if (value) {
  93876. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  93877. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  93878. _this._renderTargetsRenderTime.beginMonitoring();
  93879. });
  93880. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  93881. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  93882. _this._renderTargetsRenderTime.endMonitoring(false);
  93883. });
  93884. }
  93885. else {
  93886. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  93887. this._onBeforeRenderTargetsRenderObserver = null;
  93888. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  93889. this._onAfterRenderTargetsRenderObserver = null;
  93890. }
  93891. },
  93892. enumerable: true,
  93893. configurable: true
  93894. });
  93895. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  93896. /**
  93897. * Gets the perf counter used for particles render time
  93898. */
  93899. get: function () {
  93900. return this._particlesRenderTime;
  93901. },
  93902. enumerable: true,
  93903. configurable: true
  93904. });
  93905. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  93906. /**
  93907. * Gets the particles render time capture status
  93908. */
  93909. get: function () {
  93910. return this._captureParticlesRenderTime;
  93911. },
  93912. /**
  93913. * Enable or disable the particles render time capture
  93914. */
  93915. set: function (value) {
  93916. var _this = this;
  93917. if (value === this._captureParticlesRenderTime) {
  93918. return;
  93919. }
  93920. this._captureParticlesRenderTime = value;
  93921. if (value) {
  93922. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  93923. BABYLON.Tools.StartPerformanceCounter("Particles");
  93924. _this._particlesRenderTime.beginMonitoring();
  93925. });
  93926. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  93927. BABYLON.Tools.EndPerformanceCounter("Particles");
  93928. _this._particlesRenderTime.endMonitoring(false);
  93929. });
  93930. }
  93931. else {
  93932. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  93933. this._onBeforeParticlesRenderingObserver = null;
  93934. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  93935. this._onAfterParticlesRenderingObserver = null;
  93936. }
  93937. },
  93938. enumerable: true,
  93939. configurable: true
  93940. });
  93941. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  93942. /**
  93943. * Gets the perf counter used for sprites render time
  93944. */
  93945. get: function () {
  93946. return this._spritesRenderTime;
  93947. },
  93948. enumerable: true,
  93949. configurable: true
  93950. });
  93951. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  93952. /**
  93953. * Gets the sprites render time capture status
  93954. */
  93955. get: function () {
  93956. return this._captureSpritesRenderTime;
  93957. },
  93958. /**
  93959. * Enable or disable the sprites render time capture
  93960. */
  93961. set: function (value) {
  93962. var _this = this;
  93963. if (value === this._captureSpritesRenderTime) {
  93964. return;
  93965. }
  93966. this._captureSpritesRenderTime = value;
  93967. if (value) {
  93968. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  93969. BABYLON.Tools.StartPerformanceCounter("Sprites");
  93970. _this._spritesRenderTime.beginMonitoring();
  93971. });
  93972. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  93973. BABYLON.Tools.EndPerformanceCounter("Sprites");
  93974. _this._spritesRenderTime.endMonitoring(false);
  93975. });
  93976. }
  93977. else {
  93978. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  93979. this._onBeforeSpritesRenderingObserver = null;
  93980. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  93981. this._onAfterSpritesRenderingObserver = null;
  93982. }
  93983. },
  93984. enumerable: true,
  93985. configurable: true
  93986. });
  93987. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  93988. /**
  93989. * Gets the perf counter used for physics time
  93990. */
  93991. get: function () {
  93992. return this._physicsTime;
  93993. },
  93994. enumerable: true,
  93995. configurable: true
  93996. });
  93997. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  93998. /**
  93999. * Gets the physics time capture status
  94000. */
  94001. get: function () {
  94002. return this._capturePhysicsTime;
  94003. },
  94004. /**
  94005. * Enable or disable the physics time capture
  94006. */
  94007. set: function (value) {
  94008. var _this = this;
  94009. if (value === this._capturePhysicsTime) {
  94010. return;
  94011. }
  94012. this._capturePhysicsTime = value;
  94013. if (value) {
  94014. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  94015. BABYLON.Tools.StartPerformanceCounter("Physics");
  94016. _this._physicsTime.beginMonitoring();
  94017. });
  94018. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  94019. BABYLON.Tools.EndPerformanceCounter("Physics");
  94020. _this._physicsTime.endMonitoring();
  94021. });
  94022. }
  94023. else {
  94024. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94025. this._onBeforePhysicsObserver = null;
  94026. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94027. this._onAfterPhysicsObserver = null;
  94028. }
  94029. },
  94030. enumerable: true,
  94031. configurable: true
  94032. });
  94033. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  94034. /**
  94035. * Gets the perf counter used for animations time
  94036. */
  94037. get: function () {
  94038. return this._animationsTime;
  94039. },
  94040. enumerable: true,
  94041. configurable: true
  94042. });
  94043. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  94044. /**
  94045. * Gets the animations time capture status
  94046. */
  94047. get: function () {
  94048. return this._captureAnimationsTime;
  94049. },
  94050. /**
  94051. * Enable or disable the animations time capture
  94052. */
  94053. set: function (value) {
  94054. var _this = this;
  94055. if (value === this._captureAnimationsTime) {
  94056. return;
  94057. }
  94058. this._captureAnimationsTime = value;
  94059. if (value) {
  94060. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  94061. _this._animationsTime.endMonitoring();
  94062. });
  94063. }
  94064. else {
  94065. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94066. this._onAfterAnimationsObserver = null;
  94067. }
  94068. },
  94069. enumerable: true,
  94070. configurable: true
  94071. });
  94072. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  94073. /**
  94074. * Gets the perf counter used for frame time capture
  94075. */
  94076. get: function () {
  94077. return this._frameTime;
  94078. },
  94079. enumerable: true,
  94080. configurable: true
  94081. });
  94082. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  94083. /**
  94084. * Gets the frame time capture status
  94085. */
  94086. get: function () {
  94087. return this._captureFrameTime;
  94088. },
  94089. /**
  94090. * Enable or disable the frame time capture
  94091. */
  94092. set: function (value) {
  94093. this._captureFrameTime = value;
  94094. },
  94095. enumerable: true,
  94096. configurable: true
  94097. });
  94098. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  94099. /**
  94100. * Gets the perf counter used for inter-frames time capture
  94101. */
  94102. get: function () {
  94103. return this._interFrameTime;
  94104. },
  94105. enumerable: true,
  94106. configurable: true
  94107. });
  94108. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  94109. /**
  94110. * Gets the inter-frames time capture status
  94111. */
  94112. get: function () {
  94113. return this._captureInterFrameTime;
  94114. },
  94115. /**
  94116. * Enable or disable the inter-frames time capture
  94117. */
  94118. set: function (value) {
  94119. this._captureInterFrameTime = value;
  94120. },
  94121. enumerable: true,
  94122. configurable: true
  94123. });
  94124. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  94125. /**
  94126. * Gets the perf counter used for render time capture
  94127. */
  94128. get: function () {
  94129. return this._renderTime;
  94130. },
  94131. enumerable: true,
  94132. configurable: true
  94133. });
  94134. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  94135. /**
  94136. * Gets the render time capture status
  94137. */
  94138. get: function () {
  94139. return this._captureRenderTime;
  94140. },
  94141. /**
  94142. * Enable or disable the render time capture
  94143. */
  94144. set: function (value) {
  94145. var _this = this;
  94146. if (value === this._captureRenderTime) {
  94147. return;
  94148. }
  94149. this._captureRenderTime = value;
  94150. if (value) {
  94151. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  94152. _this._renderTime.beginMonitoring();
  94153. BABYLON.Tools.StartPerformanceCounter("Main render");
  94154. });
  94155. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  94156. _this._renderTime.endMonitoring(false);
  94157. BABYLON.Tools.EndPerformanceCounter("Main render");
  94158. });
  94159. }
  94160. else {
  94161. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  94162. this._onBeforeDrawPhaseObserver = null;
  94163. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  94164. this._onAfterDrawPhaseObserver = null;
  94165. }
  94166. },
  94167. enumerable: true,
  94168. configurable: true
  94169. });
  94170. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  94171. /**
  94172. * Gets the perf counter used for draw calls
  94173. */
  94174. get: function () {
  94175. return this.scene.getEngine()._drawCalls;
  94176. },
  94177. enumerable: true,
  94178. configurable: true
  94179. });
  94180. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  94181. /**
  94182. * Gets the perf counter used for texture collisions
  94183. */
  94184. get: function () {
  94185. return this.scene.getEngine()._textureCollisions;
  94186. },
  94187. enumerable: true,
  94188. configurable: true
  94189. });
  94190. SceneInstrumentation.prototype.dispose = function () {
  94191. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94192. this._onAfterRenderObserver = null;
  94193. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94194. this._onBeforeActiveMeshesEvaluationObserver = null;
  94195. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94196. this._onAfterActiveMeshesEvaluationObserver = null;
  94197. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94198. this._onBeforeRenderTargetsRenderObserver = null;
  94199. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94200. this._onAfterRenderTargetsRenderObserver = null;
  94201. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  94202. this._onBeforeAnimationsObserver = null;
  94203. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94204. this._onBeforeParticlesRenderingObserver = null;
  94205. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94206. this._onAfterParticlesRenderingObserver = null;
  94207. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94208. this._onBeforeSpritesRenderingObserver = null;
  94209. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94210. this._onAfterSpritesRenderingObserver = null;
  94211. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  94212. this._onBeforeDrawPhaseObserver = null;
  94213. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  94214. this._onAfterDrawPhaseObserver = null;
  94215. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94216. this._onBeforePhysicsObserver = null;
  94217. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94218. this._onAfterPhysicsObserver = null;
  94219. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94220. this._onAfterAnimationsObserver = null;
  94221. this.scene = null;
  94222. };
  94223. return SceneInstrumentation;
  94224. }());
  94225. BABYLON.SceneInstrumentation = SceneInstrumentation;
  94226. })(BABYLON || (BABYLON = {}));
  94227. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  94228. "use strict";
  94229. var BABYLON;
  94230. (function (BABYLON) {
  94231. var _TimeToken = /** @class */ (function () {
  94232. function _TimeToken() {
  94233. this._timeElapsedQueryEnded = false;
  94234. }
  94235. return _TimeToken;
  94236. }());
  94237. BABYLON._TimeToken = _TimeToken;
  94238. })(BABYLON || (BABYLON = {}));
  94239. //# sourceMappingURL=babylon.timeToken.js.map
  94240. "use strict";
  94241. var BABYLON;
  94242. (function (BABYLON) {
  94243. /**
  94244. * Background material defines definition.
  94245. * @ignore Mainly internal Use
  94246. */
  94247. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  94248. __extends(BackgroundMaterialDefines, _super);
  94249. /**
  94250. * Constructor of the defines.
  94251. */
  94252. function BackgroundMaterialDefines() {
  94253. var _this = _super.call(this) || this;
  94254. /**
  94255. * True if the diffuse texture is in use.
  94256. */
  94257. _this.DIFFUSE = false;
  94258. /**
  94259. * The direct UV channel to use.
  94260. */
  94261. _this.DIFFUSEDIRECTUV = 0;
  94262. /**
  94263. * True if the diffuse texture is in gamma space.
  94264. */
  94265. _this.GAMMADIFFUSE = false;
  94266. /**
  94267. * True if the diffuse texture has opacity in the alpha channel.
  94268. */
  94269. _this.DIFFUSEHASALPHA = false;
  94270. /**
  94271. * True if you want the material to fade to transparent at grazing angle.
  94272. */
  94273. _this.OPACITYFRESNEL = false;
  94274. /**
  94275. * True if an extra blur needs to be added in the reflection.
  94276. */
  94277. _this.REFLECTIONBLUR = false;
  94278. /**
  94279. * True if you want the material to fade to reflection at grazing angle.
  94280. */
  94281. _this.REFLECTIONFRESNEL = false;
  94282. /**
  94283. * True if you want the material to falloff as far as you move away from the scene center.
  94284. */
  94285. _this.REFLECTIONFALLOFF = false;
  94286. /**
  94287. * False if the current Webgl implementation does not support the texture lod extension.
  94288. */
  94289. _this.TEXTURELODSUPPORT = false;
  94290. /**
  94291. * True to ensure the data are premultiplied.
  94292. */
  94293. _this.PREMULTIPLYALPHA = false;
  94294. /**
  94295. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  94296. */
  94297. _this.USERGBCOLOR = false;
  94298. /**
  94299. * True to add noise in order to reduce the banding effect.
  94300. */
  94301. _this.NOISE = false;
  94302. /**
  94303. * is the reflection texture in BGR color scheme?
  94304. * Mainly used to solve a bug in ios10 video tag
  94305. */
  94306. _this.REFLECTIONBGR = false;
  94307. _this.IMAGEPROCESSING = false;
  94308. _this.VIGNETTE = false;
  94309. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  94310. _this.VIGNETTEBLENDMODEOPAQUE = false;
  94311. _this.TONEMAPPING = false;
  94312. _this.CONTRAST = false;
  94313. _this.COLORCURVES = false;
  94314. _this.COLORGRADING = false;
  94315. _this.COLORGRADING3D = false;
  94316. _this.SAMPLER3DGREENDEPTH = false;
  94317. _this.SAMPLER3DBGRMAP = false;
  94318. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  94319. _this.EXPOSURE = false;
  94320. // Reflection.
  94321. _this.REFLECTION = false;
  94322. _this.REFLECTIONMAP_3D = false;
  94323. _this.REFLECTIONMAP_SPHERICAL = false;
  94324. _this.REFLECTIONMAP_PLANAR = false;
  94325. _this.REFLECTIONMAP_CUBIC = false;
  94326. _this.REFLECTIONMAP_PROJECTION = false;
  94327. _this.REFLECTIONMAP_SKYBOX = false;
  94328. _this.REFLECTIONMAP_EXPLICIT = false;
  94329. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  94330. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  94331. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  94332. _this.INVERTCUBICMAP = false;
  94333. _this.REFLECTIONMAP_OPPOSITEZ = false;
  94334. _this.LODINREFLECTIONALPHA = false;
  94335. _this.GAMMAREFLECTION = false;
  94336. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  94337. // Default BJS.
  94338. _this.MAINUV1 = false;
  94339. _this.MAINUV2 = false;
  94340. _this.UV1 = false;
  94341. _this.UV2 = false;
  94342. _this.CLIPPLANE = false;
  94343. _this.POINTSIZE = false;
  94344. _this.FOG = false;
  94345. _this.NORMAL = false;
  94346. _this.NUM_BONE_INFLUENCERS = 0;
  94347. _this.BonesPerMesh = 0;
  94348. _this.INSTANCES = false;
  94349. _this.SHADOWFLOAT = false;
  94350. _this.rebuild();
  94351. return _this;
  94352. }
  94353. return BackgroundMaterialDefines;
  94354. }(BABYLON.MaterialDefines));
  94355. /**
  94356. * Background material used to create an efficient environement around your scene.
  94357. */
  94358. var BackgroundMaterial = /** @class */ (function (_super) {
  94359. __extends(BackgroundMaterial, _super);
  94360. /**
  94361. * Instantiates a Background Material in the given scene
  94362. * @param name The friendly name of the material
  94363. * @param scene The scene to add the material to
  94364. */
  94365. function BackgroundMaterial(name, scene) {
  94366. var _this = _super.call(this, name, scene) || this;
  94367. /**
  94368. * Key light Color (multiply against the R channel of the environement texture)
  94369. */
  94370. _this.primaryColor = BABYLON.Color3.White();
  94371. /**
  94372. * Key light Level (allowing HDR output of the background)
  94373. */
  94374. _this.primaryLevel = 1;
  94375. /**
  94376. * Secondary light Color (multiply against the G channel of the environement texture)
  94377. */
  94378. _this.secondaryColor = BABYLON.Color3.Gray();
  94379. /**
  94380. * Secondary light Level (allowing HDR output of the background)
  94381. */
  94382. _this.secondaryLevel = 1;
  94383. /**
  94384. * Tertiary light Color (multiply against the B channel of the environement texture)
  94385. */
  94386. _this.tertiaryColor = BABYLON.Color3.Black();
  94387. /**
  94388. * Tertiary light Level (allowing HDR output of the background)
  94389. */
  94390. _this.tertiaryLevel = 1;
  94391. /**
  94392. * Reflection Texture used in the material.
  94393. * Should be author in a specific way for the best result (refer to the documentation).
  94394. */
  94395. _this.reflectionTexture = null;
  94396. /**
  94397. * Reflection Texture level of blur.
  94398. *
  94399. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  94400. * texture twice.
  94401. */
  94402. _this.reflectionBlur = 0;
  94403. /**
  94404. * Diffuse Texture used in the material.
  94405. * Should be author in a specific way for the best result (refer to the documentation).
  94406. */
  94407. _this.diffuseTexture = null;
  94408. _this._shadowLights = null;
  94409. /**
  94410. * Specify the list of lights casting shadow on the material.
  94411. * All scene shadow lights will be included if null.
  94412. */
  94413. _this.shadowLights = null;
  94414. /**
  94415. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  94416. * soft lighting on the background.
  94417. */
  94418. _this.shadowBlurScale = 1;
  94419. /**
  94420. * Helps adjusting the shadow to a softer level if required.
  94421. * 0 means black shadows and 1 means no shadows.
  94422. */
  94423. _this.shadowLevel = 0;
  94424. /**
  94425. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  94426. * It is usually zero but might be interesting to modify according to your setup.
  94427. */
  94428. _this.sceneCenter = BABYLON.Vector3.Zero();
  94429. /**
  94430. * This helps specifying that the material is falling off to the sky box at grazing angle.
  94431. * This helps ensuring a nice transition when the camera goes under the ground.
  94432. */
  94433. _this.opacityFresnel = true;
  94434. /**
  94435. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  94436. * This helps adding a mirror texture on the ground.
  94437. */
  94438. _this.reflectionFresnel = false;
  94439. /**
  94440. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  94441. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  94442. */
  94443. _this.reflectionFalloffDistance = 0.0;
  94444. /**
  94445. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  94446. */
  94447. _this.reflectionAmount = 1.0;
  94448. /**
  94449. * This specifies the weight of the reflection at grazing angle.
  94450. */
  94451. _this.reflectionReflectance0 = 0.05;
  94452. /**
  94453. * This specifies the weight of the reflection at a perpendicular point of view.
  94454. */
  94455. _this.reflectionReflectance90 = 0.5;
  94456. /**
  94457. * Helps to directly use the maps channels instead of their level.
  94458. */
  94459. _this.useRGBColor = true;
  94460. /**
  94461. * This helps reducing the banding effect that could occur on the background.
  94462. */
  94463. _this.enableNoise = false;
  94464. _this._fovMultiplier = 1.0;
  94465. /**
  94466. * Enable the FOV adjustment feature controlled by fovMultiplier.
  94467. */
  94468. _this.useEquirectangularFOV = false;
  94469. _this._maxSimultaneousLights = 4;
  94470. /**
  94471. * Number of Simultaneous lights allowed on the material.
  94472. */
  94473. _this.maxSimultaneousLights = 4;
  94474. /**
  94475. * Keep track of the image processing observer to allow dispose and replace.
  94476. */
  94477. _this._imageProcessingObserver = null;
  94478. /**
  94479. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  94480. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  94481. */
  94482. _this.switchToBGR = false;
  94483. // Temp values kept as cache in the material.
  94484. _this._renderTargets = new BABYLON.SmartArray(16);
  94485. _this._reflectionControls = BABYLON.Vector4.Zero();
  94486. // Setup the default processing configuration to the scene.
  94487. _this._attachImageProcessingConfiguration(null);
  94488. _this.getRenderTargetTextures = function () {
  94489. _this._renderTargets.reset();
  94490. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  94491. _this._renderTargets.push(_this._diffuseTexture);
  94492. }
  94493. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  94494. _this._renderTargets.push(_this._reflectionTexture);
  94495. }
  94496. return _this._renderTargets;
  94497. };
  94498. return _this;
  94499. }
  94500. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  94501. /**
  94502. * Sets the reflection reflectance fresnel values according to the default standard
  94503. * empirically know to work well :-)
  94504. */
  94505. set: function (value) {
  94506. var reflectionWeight = value;
  94507. if (reflectionWeight < 0.5) {
  94508. reflectionWeight = reflectionWeight * 2.0;
  94509. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  94510. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  94511. }
  94512. else {
  94513. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  94514. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  94515. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  94516. }
  94517. },
  94518. enumerable: true,
  94519. configurable: true
  94520. });
  94521. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  94522. /**
  94523. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  94524. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  94525. * Recommended to be keep at 1.0 except for special cases.
  94526. */
  94527. get: function () {
  94528. return this._fovMultiplier;
  94529. },
  94530. set: function (value) {
  94531. if (isNaN(value)) {
  94532. value = 1.0;
  94533. }
  94534. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  94535. },
  94536. enumerable: true,
  94537. configurable: true
  94538. });
  94539. /**
  94540. * Attaches a new image processing configuration to the PBR Material.
  94541. * @param configuration (if null the scene configuration will be use)
  94542. */
  94543. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  94544. var _this = this;
  94545. if (configuration === this._imageProcessingConfiguration) {
  94546. return;
  94547. }
  94548. // Detaches observer.
  94549. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94550. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94551. }
  94552. // Pick the scene configuration if needed.
  94553. if (!configuration) {
  94554. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  94555. }
  94556. else {
  94557. this._imageProcessingConfiguration = configuration;
  94558. }
  94559. // Attaches observer.
  94560. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  94561. _this._markAllSubMeshesAsImageProcessingDirty();
  94562. });
  94563. };
  94564. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  94565. /**
  94566. * Gets the image processing configuration used either in this material.
  94567. */
  94568. get: function () {
  94569. return this._imageProcessingConfiguration;
  94570. },
  94571. /**
  94572. * Sets the Default image processing configuration used either in the this material.
  94573. *
  94574. * If sets to null, the scene one is in use.
  94575. */
  94576. set: function (value) {
  94577. this._attachImageProcessingConfiguration(value);
  94578. // Ensure the effect will be rebuilt.
  94579. this._markAllSubMeshesAsTexturesDirty();
  94580. },
  94581. enumerable: true,
  94582. configurable: true
  94583. });
  94584. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  94585. /**
  94586. * Gets wether the color curves effect is enabled.
  94587. */
  94588. get: function () {
  94589. return this.imageProcessingConfiguration.colorCurvesEnabled;
  94590. },
  94591. /**
  94592. * Sets wether the color curves effect is enabled.
  94593. */
  94594. set: function (value) {
  94595. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  94596. },
  94597. enumerable: true,
  94598. configurable: true
  94599. });
  94600. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  94601. /**
  94602. * Gets wether the color grading effect is enabled.
  94603. */
  94604. get: function () {
  94605. return this.imageProcessingConfiguration.colorGradingEnabled;
  94606. },
  94607. /**
  94608. * Gets wether the color grading effect is enabled.
  94609. */
  94610. set: function (value) {
  94611. this.imageProcessingConfiguration.colorGradingEnabled = value;
  94612. },
  94613. enumerable: true,
  94614. configurable: true
  94615. });
  94616. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  94617. /**
  94618. * Gets wether tonemapping is enabled or not.
  94619. */
  94620. get: function () {
  94621. return this._imageProcessingConfiguration.toneMappingEnabled;
  94622. },
  94623. /**
  94624. * Sets wether tonemapping is enabled or not
  94625. */
  94626. set: function (value) {
  94627. this._imageProcessingConfiguration.toneMappingEnabled = value;
  94628. },
  94629. enumerable: true,
  94630. configurable: true
  94631. });
  94632. ;
  94633. ;
  94634. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  94635. /**
  94636. * The camera exposure used on this material.
  94637. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94638. * This corresponds to a photographic exposure.
  94639. */
  94640. get: function () {
  94641. return this._imageProcessingConfiguration.exposure;
  94642. },
  94643. /**
  94644. * The camera exposure used on this material.
  94645. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94646. * This corresponds to a photographic exposure.
  94647. */
  94648. set: function (value) {
  94649. this._imageProcessingConfiguration.exposure = value;
  94650. },
  94651. enumerable: true,
  94652. configurable: true
  94653. });
  94654. ;
  94655. ;
  94656. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  94657. /**
  94658. * Gets The camera contrast used on this material.
  94659. */
  94660. get: function () {
  94661. return this._imageProcessingConfiguration.contrast;
  94662. },
  94663. /**
  94664. * Sets The camera contrast used on this material.
  94665. */
  94666. set: function (value) {
  94667. this._imageProcessingConfiguration.contrast = value;
  94668. },
  94669. enumerable: true,
  94670. configurable: true
  94671. });
  94672. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  94673. /**
  94674. * Gets the Color Grading 2D Lookup Texture.
  94675. */
  94676. get: function () {
  94677. return this._imageProcessingConfiguration.colorGradingTexture;
  94678. },
  94679. /**
  94680. * Sets the Color Grading 2D Lookup Texture.
  94681. */
  94682. set: function (value) {
  94683. this.imageProcessingConfiguration.colorGradingTexture = value;
  94684. },
  94685. enumerable: true,
  94686. configurable: true
  94687. });
  94688. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  94689. /**
  94690. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94691. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94692. * 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;
  94693. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94694. */
  94695. get: function () {
  94696. return this.imageProcessingConfiguration.colorCurves;
  94697. },
  94698. /**
  94699. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94700. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94701. * 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;
  94702. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94703. */
  94704. set: function (value) {
  94705. this.imageProcessingConfiguration.colorCurves = value;
  94706. },
  94707. enumerable: true,
  94708. configurable: true
  94709. });
  94710. /**
  94711. * The entire material has been created in order to prevent overdraw.
  94712. * @returns false
  94713. */
  94714. BackgroundMaterial.prototype.needAlphaTesting = function () {
  94715. return true;
  94716. };
  94717. /**
  94718. * The entire material has been created in order to prevent overdraw.
  94719. * @returns true if blending is enable
  94720. */
  94721. BackgroundMaterial.prototype.needAlphaBlending = function () {
  94722. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  94723. };
  94724. /**
  94725. * Checks wether the material is ready to be rendered for a given mesh.
  94726. * @param mesh The mesh to render
  94727. * @param subMesh The submesh to check against
  94728. * @param useInstances Specify wether or not the material is used with instances
  94729. * @returns true if all the dependencies are ready (Textures, Effects...)
  94730. */
  94731. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  94732. var _this = this;
  94733. if (useInstances === void 0) { useInstances = false; }
  94734. if (subMesh.effect && this.isFrozen) {
  94735. if (this._wasPreviouslyReady) {
  94736. return true;
  94737. }
  94738. }
  94739. if (!subMesh._materialDefines) {
  94740. subMesh._materialDefines = new BackgroundMaterialDefines();
  94741. }
  94742. var scene = this.getScene();
  94743. var defines = subMesh._materialDefines;
  94744. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  94745. if (defines._renderId === scene.getRenderId()) {
  94746. return true;
  94747. }
  94748. }
  94749. var engine = scene.getEngine();
  94750. // Lights
  94751. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  94752. defines._needNormals = true;
  94753. // Textures
  94754. if (defines._areTexturesDirty) {
  94755. defines._needUVs = false;
  94756. if (scene.texturesEnabled) {
  94757. if (scene.getEngine().getCaps().textureLOD) {
  94758. defines.TEXTURELODSUPPORT = true;
  94759. }
  94760. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94761. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  94762. return false;
  94763. }
  94764. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  94765. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  94766. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  94767. defines.OPACITYFRESNEL = this._opacityFresnel;
  94768. }
  94769. else {
  94770. defines.DIFFUSE = false;
  94771. defines.DIFFUSEHASALPHA = false;
  94772. defines.GAMMADIFFUSE = false;
  94773. defines.OPACITYFRESNEL = false;
  94774. }
  94775. var reflectionTexture = this._reflectionTexture;
  94776. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94777. if (!reflectionTexture.isReadyOrNotBlocking()) {
  94778. return false;
  94779. }
  94780. defines.REFLECTION = true;
  94781. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  94782. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  94783. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  94784. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  94785. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  94786. defines.REFLECTIONBGR = this.switchToBGR;
  94787. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  94788. defines.INVERTCUBICMAP = true;
  94789. }
  94790. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  94791. switch (reflectionTexture.coordinatesMode) {
  94792. case BABYLON.Texture.CUBIC_MODE:
  94793. case BABYLON.Texture.INVCUBIC_MODE:
  94794. defines.REFLECTIONMAP_CUBIC = true;
  94795. break;
  94796. case BABYLON.Texture.EXPLICIT_MODE:
  94797. defines.REFLECTIONMAP_EXPLICIT = true;
  94798. break;
  94799. case BABYLON.Texture.PLANAR_MODE:
  94800. defines.REFLECTIONMAP_PLANAR = true;
  94801. break;
  94802. case BABYLON.Texture.PROJECTION_MODE:
  94803. defines.REFLECTIONMAP_PROJECTION = true;
  94804. break;
  94805. case BABYLON.Texture.SKYBOX_MODE:
  94806. defines.REFLECTIONMAP_SKYBOX = true;
  94807. break;
  94808. case BABYLON.Texture.SPHERICAL_MODE:
  94809. defines.REFLECTIONMAP_SPHERICAL = true;
  94810. break;
  94811. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  94812. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  94813. break;
  94814. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  94815. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  94816. break;
  94817. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  94818. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  94819. break;
  94820. }
  94821. if (this.reflectionFresnel) {
  94822. defines.REFLECTIONFRESNEL = true;
  94823. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  94824. this._reflectionControls.x = this.reflectionAmount;
  94825. this._reflectionControls.y = this.reflectionReflectance0;
  94826. this._reflectionControls.z = this.reflectionReflectance90;
  94827. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  94828. }
  94829. else {
  94830. defines.REFLECTIONFRESNEL = false;
  94831. defines.REFLECTIONFALLOFF = false;
  94832. }
  94833. }
  94834. else {
  94835. defines.REFLECTION = false;
  94836. defines.REFLECTIONFALLOFF = false;
  94837. defines.REFLECTIONBLUR = false;
  94838. defines.REFLECTIONMAP_3D = false;
  94839. defines.REFLECTIONMAP_SPHERICAL = false;
  94840. defines.REFLECTIONMAP_PLANAR = false;
  94841. defines.REFLECTIONMAP_CUBIC = false;
  94842. defines.REFLECTIONMAP_PROJECTION = false;
  94843. defines.REFLECTIONMAP_SKYBOX = false;
  94844. defines.REFLECTIONMAP_EXPLICIT = false;
  94845. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  94846. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  94847. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  94848. defines.INVERTCUBICMAP = false;
  94849. defines.REFLECTIONMAP_OPPOSITEZ = false;
  94850. defines.LODINREFLECTIONALPHA = false;
  94851. defines.GAMMAREFLECTION = false;
  94852. }
  94853. }
  94854. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  94855. defines.USERGBCOLOR = this._useRGBColor;
  94856. defines.NOISE = this._enableNoise;
  94857. }
  94858. if (defines._areImageProcessingDirty) {
  94859. if (!this._imageProcessingConfiguration.isReady()) {
  94860. return false;
  94861. }
  94862. this._imageProcessingConfiguration.prepareDefines(defines);
  94863. }
  94864. // Misc.
  94865. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  94866. // Values that need to be evaluated on every frame
  94867. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  94868. // Attribs
  94869. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  94870. if (mesh) {
  94871. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  94872. mesh.createNormals(true);
  94873. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  94874. }
  94875. }
  94876. }
  94877. // Get correct effect
  94878. if (defines.isDirty) {
  94879. defines.markAsProcessed();
  94880. scene.resetCachedMaterial();
  94881. // Fallbacks
  94882. var fallbacks = new BABYLON.EffectFallbacks();
  94883. if (defines.FOG) {
  94884. fallbacks.addFallback(0, "FOG");
  94885. }
  94886. if (defines.POINTSIZE) {
  94887. fallbacks.addFallback(1, "POINTSIZE");
  94888. }
  94889. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  94890. if (defines.NUM_BONE_INFLUENCERS > 0) {
  94891. fallbacks.addCPUSkinningFallback(0, mesh);
  94892. }
  94893. //Attributes
  94894. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94895. if (defines.NORMAL) {
  94896. attribs.push(BABYLON.VertexBuffer.NormalKind);
  94897. }
  94898. if (defines.UV1) {
  94899. attribs.push(BABYLON.VertexBuffer.UVKind);
  94900. }
  94901. if (defines.UV2) {
  94902. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94903. }
  94904. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  94905. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  94906. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  94907. "vFogInfos", "vFogColor", "pointSize",
  94908. "vClipPlane", "mBones",
  94909. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  94910. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  94911. "shadowLevel", "alpha",
  94912. "vBackgroundCenter", "vReflectionControl",
  94913. "vDiffuseInfos", "diffuseMatrix",
  94914. ];
  94915. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  94916. var uniformBuffers = ["Material", "Scene"];
  94917. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  94918. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  94919. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  94920. uniformsNames: uniforms,
  94921. uniformBuffersNames: uniformBuffers,
  94922. samplers: samplers,
  94923. defines: defines,
  94924. maxSimultaneousLights: this._maxSimultaneousLights
  94925. });
  94926. var onCompiled = function (effect) {
  94927. if (_this.onCompiled) {
  94928. _this.onCompiled(effect);
  94929. }
  94930. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  94931. };
  94932. var join = defines.toString();
  94933. subMesh.setEffect(scene.getEngine().createEffect("background", {
  94934. attributes: attribs,
  94935. uniformsNames: uniforms,
  94936. uniformBuffersNames: uniformBuffers,
  94937. samplers: samplers,
  94938. defines: join,
  94939. fallbacks: fallbacks,
  94940. onCompiled: onCompiled,
  94941. onError: this.onError,
  94942. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  94943. }, engine), defines);
  94944. this.buildUniformLayout();
  94945. }
  94946. if (!subMesh.effect || !subMesh.effect.isReady()) {
  94947. return false;
  94948. }
  94949. defines._renderId = scene.getRenderId();
  94950. this._wasPreviouslyReady = true;
  94951. return true;
  94952. };
  94953. /**
  94954. * Build the uniform buffer used in the material.
  94955. */
  94956. BackgroundMaterial.prototype.buildUniformLayout = function () {
  94957. // Order is important !
  94958. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  94959. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  94960. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  94961. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  94962. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  94963. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  94964. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  94965. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  94966. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  94967. this._uniformBuffer.addUniform("pointSize", 1);
  94968. this._uniformBuffer.addUniform("shadowLevel", 1);
  94969. this._uniformBuffer.addUniform("alpha", 1);
  94970. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  94971. this._uniformBuffer.addUniform("vReflectionControl", 4);
  94972. this._uniformBuffer.create();
  94973. };
  94974. /**
  94975. * Unbind the material.
  94976. */
  94977. BackgroundMaterial.prototype.unbind = function () {
  94978. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  94979. this._uniformBuffer.setTexture("diffuseSampler", null);
  94980. }
  94981. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  94982. this._uniformBuffer.setTexture("reflectionSampler", null);
  94983. }
  94984. _super.prototype.unbind.call(this);
  94985. };
  94986. /**
  94987. * Bind only the world matrix to the material.
  94988. * @param world The world matrix to bind.
  94989. */
  94990. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  94991. this._activeEffect.setMatrix("world", world);
  94992. };
  94993. /**
  94994. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  94995. * @param world The world matrix to bind.
  94996. * @param subMesh The submesh to bind for.
  94997. */
  94998. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  94999. var scene = this.getScene();
  95000. var defines = subMesh._materialDefines;
  95001. if (!defines) {
  95002. return;
  95003. }
  95004. var effect = subMesh.effect;
  95005. if (!effect) {
  95006. return;
  95007. }
  95008. this._activeEffect = effect;
  95009. // Matrices
  95010. this.bindOnlyWorldMatrix(world);
  95011. // Bones
  95012. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  95013. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  95014. if (mustRebind) {
  95015. this._uniformBuffer.bindToEffect(effect, "Material");
  95016. this.bindViewProjection(effect);
  95017. var reflectionTexture = this._reflectionTexture;
  95018. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  95019. // Texture uniforms
  95020. if (scene.texturesEnabled) {
  95021. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95022. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  95023. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  95024. }
  95025. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95026. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  95027. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  95028. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  95029. }
  95030. }
  95031. if (this.shadowLevel > 0) {
  95032. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  95033. }
  95034. this._uniformBuffer.updateFloat("alpha", this.alpha);
  95035. // Point size
  95036. if (this.pointsCloud) {
  95037. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  95038. }
  95039. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  95040. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  95041. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  95042. }
  95043. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  95044. // Textures
  95045. if (scene.texturesEnabled) {
  95046. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95047. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  95048. }
  95049. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95050. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  95051. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95052. }
  95053. else if (!defines.REFLECTIONBLUR) {
  95054. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95055. }
  95056. else {
  95057. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  95058. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  95059. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  95060. }
  95061. if (defines.REFLECTIONFRESNEL) {
  95062. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  95063. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  95064. }
  95065. }
  95066. }
  95067. // Clip plane
  95068. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  95069. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  95070. }
  95071. if (mustRebind || !this.isFrozen) {
  95072. if (scene.lightsEnabled) {
  95073. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  95074. }
  95075. // View
  95076. this.bindView(effect);
  95077. // Fog
  95078. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  95079. // image processing
  95080. this._imageProcessingConfiguration.bind(this._activeEffect);
  95081. }
  95082. this._uniformBuffer.update();
  95083. this._afterBind(mesh);
  95084. };
  95085. /**
  95086. * Dispose the material.
  95087. * @param forceDisposeEffect Force disposal of the associated effect.
  95088. * @param forceDisposeTextures Force disposal of the associated textures.
  95089. */
  95090. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  95091. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  95092. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  95093. if (forceDisposeTextures) {
  95094. if (this.diffuseTexture) {
  95095. this.diffuseTexture.dispose();
  95096. }
  95097. if (this.reflectionTexture) {
  95098. this.reflectionTexture.dispose();
  95099. }
  95100. }
  95101. this._renderTargets.dispose();
  95102. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  95103. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  95104. }
  95105. _super.prototype.dispose.call(this, forceDisposeEffect);
  95106. };
  95107. /**
  95108. * Clones the material.
  95109. * @param name The cloned name.
  95110. * @returns The cloned material.
  95111. */
  95112. BackgroundMaterial.prototype.clone = function (name) {
  95113. var _this = this;
  95114. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  95115. };
  95116. /**
  95117. * Serializes the current material to its JSON representation.
  95118. * @returns The JSON representation.
  95119. */
  95120. BackgroundMaterial.prototype.serialize = function () {
  95121. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95122. serializationObject.customType = "BABYLON.BackgroundMaterial";
  95123. return serializationObject;
  95124. };
  95125. /**
  95126. * Gets the class name of the material
  95127. * @returns "BackgroundMaterial"
  95128. */
  95129. BackgroundMaterial.prototype.getClassName = function () {
  95130. return "BackgroundMaterial";
  95131. };
  95132. /**
  95133. * Parse a JSON input to create back a background material.
  95134. * @param source The JSON data to parse
  95135. * @param scene The scene to create the parsed material in
  95136. * @param rootUrl The root url of the assets the material depends upon
  95137. * @returns the instantiated BackgroundMaterial.
  95138. */
  95139. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  95140. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  95141. };
  95142. /**
  95143. * Standard reflectance value at parallel view angle.
  95144. */
  95145. BackgroundMaterial.StandardReflectance0 = 0.05;
  95146. /**
  95147. * Standard reflectance value at grazing angle.
  95148. */
  95149. BackgroundMaterial.StandardReflectance90 = 0.5;
  95150. __decorate([
  95151. BABYLON.serializeAsColor3()
  95152. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  95153. __decorate([
  95154. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95155. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  95156. __decorate([
  95157. BABYLON.serialize()
  95158. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  95159. __decorate([
  95160. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95161. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  95162. __decorate([
  95163. BABYLON.serializeAsColor3()
  95164. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  95165. __decorate([
  95166. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95167. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  95168. __decorate([
  95169. BABYLON.serialize()
  95170. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  95171. __decorate([
  95172. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95173. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  95174. __decorate([
  95175. BABYLON.serializeAsColor3()
  95176. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  95177. __decorate([
  95178. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95179. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  95180. __decorate([
  95181. BABYLON.serialize()
  95182. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  95183. __decorate([
  95184. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95185. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  95186. __decorate([
  95187. BABYLON.serializeAsTexture()
  95188. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  95189. __decorate([
  95190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95191. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  95192. __decorate([
  95193. BABYLON.serialize()
  95194. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  95195. __decorate([
  95196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95197. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  95198. __decorate([
  95199. BABYLON.serializeAsTexture()
  95200. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  95201. __decorate([
  95202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95203. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  95204. __decorate([
  95205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95206. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  95207. __decorate([
  95208. BABYLON.serialize()
  95209. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  95210. __decorate([
  95211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95212. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  95213. __decorate([
  95214. BABYLON.serialize()
  95215. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  95216. __decorate([
  95217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95218. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  95219. __decorate([
  95220. BABYLON.serializeAsVector3()
  95221. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  95222. __decorate([
  95223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95224. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  95225. __decorate([
  95226. BABYLON.serialize()
  95227. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  95228. __decorate([
  95229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95230. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  95231. __decorate([
  95232. BABYLON.serialize()
  95233. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  95234. __decorate([
  95235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95236. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  95237. __decorate([
  95238. BABYLON.serialize()
  95239. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  95240. __decorate([
  95241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95242. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  95243. __decorate([
  95244. BABYLON.serialize()
  95245. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  95246. __decorate([
  95247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95248. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  95249. __decorate([
  95250. BABYLON.serialize()
  95251. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  95252. __decorate([
  95253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95254. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  95255. __decorate([
  95256. BABYLON.serialize()
  95257. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  95258. __decorate([
  95259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95260. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  95261. __decorate([
  95262. BABYLON.serialize()
  95263. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  95264. __decorate([
  95265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95266. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  95267. __decorate([
  95268. BABYLON.serialize()
  95269. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  95270. __decorate([
  95271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95272. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  95273. __decorate([
  95274. BABYLON.serialize()
  95275. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  95276. __decorate([
  95277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95278. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  95279. __decorate([
  95280. BABYLON.serializeAsImageProcessingConfiguration()
  95281. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  95282. return BackgroundMaterial;
  95283. }(BABYLON.PushMaterial));
  95284. BABYLON.BackgroundMaterial = BackgroundMaterial;
  95285. })(BABYLON || (BABYLON = {}));
  95286. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  95287. "use strict";
  95288. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95289. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95290. s = arguments[i];
  95291. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95292. t[p] = s[p];
  95293. }
  95294. return t;
  95295. };
  95296. var BABYLON;
  95297. (function (BABYLON) {
  95298. /**
  95299. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  95300. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  95301. * It also helps with the default setup of your imageProcessing configuration.
  95302. */
  95303. var EnvironmentHelper = /** @class */ (function () {
  95304. /**
  95305. * constructor
  95306. * @param options
  95307. * @param scene The scene to add the material to
  95308. */
  95309. function EnvironmentHelper(options, scene) {
  95310. var _this = this;
  95311. this._errorHandler = function (message, exception) {
  95312. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  95313. };
  95314. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  95315. this._scene = scene;
  95316. this.onErrorObservable = new BABYLON.Observable();
  95317. this._setupBackground();
  95318. this._setupImageProcessing();
  95319. }
  95320. /**
  95321. * Creates the default options for the helper.
  95322. */
  95323. EnvironmentHelper._getDefaultOptions = function () {
  95324. return {
  95325. createGround: true,
  95326. groundSize: 15,
  95327. groundTexture: this._groundTextureCDNUrl,
  95328. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  95329. groundOpacity: 0.9,
  95330. enableGroundShadow: true,
  95331. groundShadowLevel: 0.5,
  95332. enableGroundMirror: false,
  95333. groundMirrorSizeRatio: 0.3,
  95334. groundMirrorBlurKernel: 64,
  95335. groundMirrorAmount: 1,
  95336. groundMirrorFresnelWeight: 1,
  95337. groundMirrorFallOffDistance: 0,
  95338. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  95339. groundYBias: 0.00001,
  95340. createSkybox: true,
  95341. skyboxSize: 20,
  95342. skyboxTexture: this._skyboxTextureCDNUrl,
  95343. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  95344. backgroundYRotation: 0,
  95345. sizeAuto: true,
  95346. rootPosition: BABYLON.Vector3.Zero(),
  95347. setupImageProcessing: true,
  95348. environmentTexture: this._environmentTextureCDNUrl,
  95349. cameraExposure: 0.8,
  95350. cameraContrast: 1.2,
  95351. toneMappingEnabled: true,
  95352. };
  95353. };
  95354. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  95355. /**
  95356. * Gets the root mesh created by the helper.
  95357. */
  95358. get: function () {
  95359. return this._rootMesh;
  95360. },
  95361. enumerable: true,
  95362. configurable: true
  95363. });
  95364. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  95365. /**
  95366. * Gets the skybox created by the helper.
  95367. */
  95368. get: function () {
  95369. return this._skybox;
  95370. },
  95371. enumerable: true,
  95372. configurable: true
  95373. });
  95374. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  95375. /**
  95376. * Gets the skybox texture created by the helper.
  95377. */
  95378. get: function () {
  95379. return this._skyboxTexture;
  95380. },
  95381. enumerable: true,
  95382. configurable: true
  95383. });
  95384. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  95385. /**
  95386. * Gets the skybox material created by the helper.
  95387. */
  95388. get: function () {
  95389. return this._skyboxMaterial;
  95390. },
  95391. enumerable: true,
  95392. configurable: true
  95393. });
  95394. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  95395. /**
  95396. * Gets the ground mesh created by the helper.
  95397. */
  95398. get: function () {
  95399. return this._ground;
  95400. },
  95401. enumerable: true,
  95402. configurable: true
  95403. });
  95404. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  95405. /**
  95406. * Gets the ground texture created by the helper.
  95407. */
  95408. get: function () {
  95409. return this._groundTexture;
  95410. },
  95411. enumerable: true,
  95412. configurable: true
  95413. });
  95414. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  95415. /**
  95416. * Gets the ground mirror created by the helper.
  95417. */
  95418. get: function () {
  95419. return this._groundMirror;
  95420. },
  95421. enumerable: true,
  95422. configurable: true
  95423. });
  95424. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  95425. /**
  95426. * Gets the ground mirror render list to helps pushing the meshes
  95427. * you wish in the ground reflection.
  95428. */
  95429. get: function () {
  95430. if (this._groundMirror) {
  95431. return this._groundMirror.renderList;
  95432. }
  95433. return null;
  95434. },
  95435. enumerable: true,
  95436. configurable: true
  95437. });
  95438. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  95439. /**
  95440. * Gets the ground material created by the helper.
  95441. */
  95442. get: function () {
  95443. return this._groundMaterial;
  95444. },
  95445. enumerable: true,
  95446. configurable: true
  95447. });
  95448. /**
  95449. * Updates the background according to the new options
  95450. * @param options
  95451. */
  95452. EnvironmentHelper.prototype.updateOptions = function (options) {
  95453. var newOptions = __assign({}, this._options, options);
  95454. if (this._ground && !newOptions.createGround) {
  95455. this._ground.dispose();
  95456. this._ground = null;
  95457. }
  95458. if (this._groundMaterial && !newOptions.createGround) {
  95459. this._groundMaterial.dispose();
  95460. this._groundMaterial = null;
  95461. }
  95462. if (this._groundTexture) {
  95463. if (this._options.groundTexture != newOptions.groundTexture) {
  95464. this._groundTexture.dispose();
  95465. this._groundTexture = null;
  95466. }
  95467. }
  95468. if (this._skybox && !newOptions.createSkybox) {
  95469. this._skybox.dispose();
  95470. this._skybox = null;
  95471. }
  95472. if (this._skyboxMaterial && !newOptions.createSkybox) {
  95473. this._skyboxMaterial.dispose();
  95474. this._skyboxMaterial = null;
  95475. }
  95476. if (this._skyboxTexture) {
  95477. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  95478. this._skyboxTexture.dispose();
  95479. this._skyboxTexture = null;
  95480. }
  95481. }
  95482. if (this._groundMirror && !newOptions.enableGroundMirror) {
  95483. this._groundMirror.dispose();
  95484. this._groundMirror = null;
  95485. }
  95486. if (this._scene.environmentTexture) {
  95487. if (this._options.environmentTexture != newOptions.environmentTexture) {
  95488. this._scene.environmentTexture.dispose();
  95489. }
  95490. }
  95491. this._options = newOptions;
  95492. this._setupBackground();
  95493. this._setupImageProcessing();
  95494. };
  95495. /**
  95496. * Sets the primary color of all the available elements.
  95497. * @param color
  95498. */
  95499. EnvironmentHelper.prototype.setMainColor = function (color) {
  95500. if (this.groundMaterial) {
  95501. this.groundMaterial.primaryColor = color;
  95502. }
  95503. if (this.skyboxMaterial) {
  95504. this.skyboxMaterial.primaryColor = color;
  95505. }
  95506. if (this.groundMirror) {
  95507. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  95508. }
  95509. };
  95510. /**
  95511. * Setup the image processing according to the specified options.
  95512. */
  95513. EnvironmentHelper.prototype._setupImageProcessing = function () {
  95514. if (this._options.setupImageProcessing) {
  95515. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  95516. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  95517. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  95518. this._setupEnvironmentTexture();
  95519. }
  95520. };
  95521. /**
  95522. * Setup the environment texture according to the specified options.
  95523. */
  95524. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  95525. if (this._scene.environmentTexture) {
  95526. return;
  95527. }
  95528. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  95529. this._scene.environmentTexture = this._options.environmentTexture;
  95530. return;
  95531. }
  95532. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  95533. this._scene.environmentTexture = environmentTexture;
  95534. };
  95535. /**
  95536. * Setup the background according to the specified options.
  95537. */
  95538. EnvironmentHelper.prototype._setupBackground = function () {
  95539. if (!this._rootMesh) {
  95540. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  95541. }
  95542. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  95543. var sceneSize = this._getSceneSize();
  95544. if (this._options.createGround) {
  95545. this._setupGround(sceneSize);
  95546. this._setupGroundMaterial();
  95547. this._setupGroundDiffuseTexture();
  95548. if (this._options.enableGroundMirror) {
  95549. this._setupGroundMirrorTexture(sceneSize);
  95550. }
  95551. this._setupMirrorInGroundMaterial();
  95552. }
  95553. if (this._options.createSkybox) {
  95554. this._setupSkybox(sceneSize);
  95555. this._setupSkyboxMaterial();
  95556. this._setupSkyboxReflectionTexture();
  95557. }
  95558. this._rootMesh.position.x = sceneSize.rootPosition.x;
  95559. this._rootMesh.position.z = sceneSize.rootPosition.z;
  95560. this._rootMesh.position.y = sceneSize.rootPosition.y;
  95561. };
  95562. /**
  95563. * Get the scene sizes according to the setup.
  95564. */
  95565. EnvironmentHelper.prototype._getSceneSize = function () {
  95566. var _this = this;
  95567. var groundSize = this._options.groundSize;
  95568. var skyboxSize = this._options.skyboxSize;
  95569. var rootPosition = this._options.rootPosition;
  95570. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  95571. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95572. }
  95573. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  95574. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  95575. });
  95576. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  95577. if (this._options.sizeAuto) {
  95578. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  95579. this._scene.activeCamera.upperRadiusLimit) {
  95580. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  95581. skyboxSize = groundSize;
  95582. }
  95583. var sceneDiagonalLenght = sceneDiagonal.length();
  95584. if (sceneDiagonalLenght > groundSize) {
  95585. groundSize = sceneDiagonalLenght * 2;
  95586. skyboxSize = groundSize;
  95587. }
  95588. // 10 % bigger.
  95589. groundSize *= 1.1;
  95590. skyboxSize *= 1.5;
  95591. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  95592. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  95593. }
  95594. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95595. };
  95596. /**
  95597. * Setup the ground according to the specified options.
  95598. */
  95599. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  95600. var _this = this;
  95601. if (!this._ground) {
  95602. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  95603. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  95604. this._ground.parent = this._rootMesh;
  95605. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  95606. }
  95607. this._ground.receiveShadows = this._options.enableGroundShadow;
  95608. };
  95609. /**
  95610. * Setup the ground material according to the specified options.
  95611. */
  95612. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  95613. if (!this._groundMaterial) {
  95614. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  95615. }
  95616. this._groundMaterial.alpha = this._options.groundOpacity;
  95617. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  95618. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  95619. this._groundMaterial.primaryLevel = 1;
  95620. this._groundMaterial.primaryColor = this._options.groundColor;
  95621. this._groundMaterial.secondaryLevel = 0;
  95622. this._groundMaterial.tertiaryLevel = 0;
  95623. this._groundMaterial.useRGBColor = false;
  95624. this._groundMaterial.enableNoise = true;
  95625. if (this._ground) {
  95626. this._ground.material = this._groundMaterial;
  95627. }
  95628. };
  95629. /**
  95630. * Setup the ground diffuse texture according to the specified options.
  95631. */
  95632. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  95633. if (!this._groundMaterial) {
  95634. return;
  95635. }
  95636. if (this._groundTexture) {
  95637. return;
  95638. }
  95639. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  95640. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  95641. return;
  95642. }
  95643. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95644. diffuseTexture.gammaSpace = false;
  95645. diffuseTexture.hasAlpha = true;
  95646. this._groundMaterial.diffuseTexture = diffuseTexture;
  95647. };
  95648. /**
  95649. * Setup the ground mirror texture according to the specified options.
  95650. */
  95651. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  95652. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95653. if (!this._groundMirror) {
  95654. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  95655. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  95656. this._groundMirror.anisotropicFilteringLevel = 1;
  95657. this._groundMirror.wrapU = wrapping;
  95658. this._groundMirror.wrapV = wrapping;
  95659. this._groundMirror.gammaSpace = false;
  95660. if (this._groundMirror.renderList) {
  95661. for (var i = 0; i < this._scene.meshes.length; i++) {
  95662. var mesh = this._scene.meshes[i];
  95663. if (mesh !== this._ground &&
  95664. mesh !== this._skybox &&
  95665. mesh !== this._rootMesh) {
  95666. this._groundMirror.renderList.push(mesh);
  95667. }
  95668. }
  95669. }
  95670. }
  95671. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  95672. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  95673. };
  95674. /**
  95675. * Setup the ground to receive the mirror texture.
  95676. */
  95677. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  95678. if (this._groundMaterial) {
  95679. this._groundMaterial.reflectionTexture = this._groundMirror;
  95680. this._groundMaterial.reflectionFresnel = true;
  95681. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  95682. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  95683. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  95684. }
  95685. };
  95686. /**
  95687. * Setup the skybox according to the specified options.
  95688. */
  95689. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  95690. var _this = this;
  95691. if (!this._skybox) {
  95692. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  95693. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  95694. }
  95695. this._skybox.parent = this._rootMesh;
  95696. };
  95697. /**
  95698. * Setup the skybox material according to the specified options.
  95699. */
  95700. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  95701. if (!this._skybox) {
  95702. return;
  95703. }
  95704. if (!this._skyboxMaterial) {
  95705. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  95706. }
  95707. this._skyboxMaterial.useRGBColor = false;
  95708. this._skyboxMaterial.primaryLevel = 1;
  95709. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  95710. this._skyboxMaterial.secondaryLevel = 0;
  95711. this._skyboxMaterial.tertiaryLevel = 0;
  95712. this._skyboxMaterial.enableNoise = true;
  95713. this._skybox.material = this._skyboxMaterial;
  95714. };
  95715. /**
  95716. * Setup the skybox reflection texture according to the specified options.
  95717. */
  95718. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  95719. if (!this._skyboxMaterial) {
  95720. return;
  95721. }
  95722. if (this._skyboxTexture) {
  95723. return;
  95724. }
  95725. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  95726. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  95727. return;
  95728. }
  95729. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95730. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  95731. this._skyboxTexture.gammaSpace = false;
  95732. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  95733. };
  95734. /**
  95735. * Dispose all the elements created by the Helper.
  95736. */
  95737. EnvironmentHelper.prototype.dispose = function () {
  95738. if (this._groundMaterial) {
  95739. this._groundMaterial.dispose(true, true);
  95740. }
  95741. if (this._skyboxMaterial) {
  95742. this._skyboxMaterial.dispose(true, true);
  95743. }
  95744. this._rootMesh.dispose(false);
  95745. };
  95746. /**
  95747. * Default ground texture URL.
  95748. */
  95749. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  95750. /**
  95751. * Default skybox texture URL.
  95752. */
  95753. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  95754. /**
  95755. * Default environment texture URL.
  95756. */
  95757. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  95758. return EnvironmentHelper;
  95759. }());
  95760. BABYLON.EnvironmentHelper = EnvironmentHelper;
  95761. })(BABYLON || (BABYLON = {}));
  95762. //# sourceMappingURL=babylon.environmentHelper.js.map
  95763. "use strict";
  95764. var BABYLON;
  95765. (function (BABYLON) {
  95766. /**
  95767. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  95768. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  95769. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  95770. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  95771. */
  95772. var VideoDome = /** @class */ (function (_super) {
  95773. __extends(VideoDome, _super);
  95774. /**
  95775. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  95776. * @param name Element's name, child elements will append suffixes for their own names.
  95777. * @param urlsOrVideo
  95778. * @param options An object containing optional or exposed sub element properties:
  95779. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  95780. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  95781. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  95782. * @param options **loop=true** Automatically loop video on end.
  95783. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  95784. */
  95785. function VideoDome(name, urlsOrVideo, options, scene) {
  95786. var _this = _super.call(this, name, scene) || this;
  95787. // set defaults and manage values
  95788. name = name || "videoDome";
  95789. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  95790. options.clickToPlay = Boolean(options.clickToPlay);
  95791. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  95792. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  95793. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  95794. // create
  95795. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  95796. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  95797. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  95798. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  95799. flat: false,
  95800. radius: options.size,
  95801. subdivisions: options.resolution,
  95802. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  95803. }, scene);
  95804. // configure material
  95805. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  95806. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  95807. material.reflectionTexture = _this._videoTexture;
  95808. material.useEquirectangularFOV = true;
  95809. material.fovMultiplier = 1.0;
  95810. // configure mesh
  95811. _this._mesh.material = material;
  95812. _this._mesh.parent = _this;
  95813. // optional configuration
  95814. if (options.clickToPlay) {
  95815. scene.onPointerUp = function () {
  95816. _this._videoTexture.video.play();
  95817. };
  95818. }
  95819. return _this;
  95820. }
  95821. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  95822. /**
  95823. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  95824. * Also see the options.resolution property.
  95825. */
  95826. get: function () {
  95827. return this._material.fovMultiplier;
  95828. },
  95829. set: function (value) {
  95830. this._material.fovMultiplier = value;
  95831. },
  95832. enumerable: true,
  95833. configurable: true
  95834. });
  95835. /**
  95836. * Releases resources associated with this node.
  95837. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  95838. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  95839. */
  95840. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  95841. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  95842. this._videoTexture.dispose();
  95843. this._mesh.dispose();
  95844. this._material.dispose();
  95845. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  95846. };
  95847. return VideoDome;
  95848. }(BABYLON.Node));
  95849. BABYLON.VideoDome = VideoDome;
  95850. })(BABYLON || (BABYLON = {}));
  95851. //# sourceMappingURL=babylon.videoDome.js.map
  95852. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\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\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  95853. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,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}","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;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};